@prisma-next/sql-contract 0.8.0-dev.9 → 0.9.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/factories.d.mts +1 -1
- package/dist/factories.mjs +1 -1
- package/dist/index-type-validation.d.mts +1 -1
- package/dist/index-type-validation.mjs +1 -1
- package/dist/index-type-validation.mjs.map +1 -1
- package/dist/{types-B_diLlWt.d.mts → types-B0lbr9cb.d.mts} +2 -2
- package/dist/{types-B_diLlWt.d.mts.map → types-B0lbr9cb.d.mts.map} +1 -1
- package/dist/{types-BtB74x-Z.mjs → types-iqFGDcJp.mjs} +25 -6
- package/dist/types-iqFGDcJp.mjs.map +1 -0
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +1 -1
- package/dist/validators.d.mts +2 -13
- package/dist/validators.d.mts.map +1 -1
- package/dist/validators.mjs +9 -13
- package/dist/validators.mjs.map +1 -1
- package/package.json +6 -6
- package/src/index-type-validation.ts +1 -1
- package/src/ir/sql-node.ts +1 -1
- package/src/ir/sql-storage.ts +28 -4
- package/src/validators.ts +7 -11
- package/dist/types-BtB74x-Z.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -102,10 +102,10 @@ const named = fk(['userId'], 'user', ['id'], {
|
|
|
102
102
|
Validate contract structures using Arktype validators:
|
|
103
103
|
|
|
104
104
|
```typescript
|
|
105
|
-
import {
|
|
105
|
+
import { validateSqlContractFully, validateStorage, validateModel } from '@prisma-next/sql-contract/validators';
|
|
106
106
|
|
|
107
107
|
// Validate a complete contract
|
|
108
|
-
const contract =
|
|
108
|
+
const contract = validateSqlContractFully<Contract>(contractJson);
|
|
109
109
|
|
|
110
110
|
// Validate storage structure
|
|
111
111
|
const storage = validateStorage(storageJson);
|
package/dist/factories.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as Index, H as PrimaryKey, I as UniqueConstraint, P as StorageTable, R as StorageColumn, b as SqlModelStorage, f as ForeignKeyOptions, q as ForeignKey, y as SqlModelFieldStorage, z as StorageColumnInput } from "./types-
|
|
1
|
+
import { B as Index, H as PrimaryKey, I as UniqueConstraint, P as StorageTable, R as StorageColumn, b as SqlModelStorage, f as ForeignKeyOptions, q as ForeignKey, y as SqlModelFieldStorage, z as StorageColumnInput } from "./types-B0lbr9cb.mjs";
|
|
2
2
|
import { ScalarFieldType } from "@prisma-next/contract/types";
|
|
3
3
|
|
|
4
4
|
//#region src/factories.d.ts
|
package/dist/factories.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as StorageTable, f as Index, g as ForeignKey, l as UniqueConstraint, p as PrimaryKey, r as applyFkDefaults, u as StorageColumn } from "./types-
|
|
1
|
+
import { c as StorageTable, f as Index, g as ForeignKey, l as UniqueConstraint, p as PrimaryKey, r as applyFkDefaults, u as StorageColumn } from "./types-iqFGDcJp.mjs";
|
|
2
2
|
//#region src/factories.ts
|
|
3
3
|
function col(nativeType, codecId, nullable = false) {
|
|
4
4
|
return new StorageColumn({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContractValidationError } from "@prisma-next/contract/
|
|
1
|
+
import { ContractValidationError } from "@prisma-next/contract/contract-validation-error";
|
|
2
2
|
import { type } from "arktype";
|
|
3
3
|
//#region src/index-type-validation.ts
|
|
4
4
|
function validateIndexTypes(contract, indexTypeRegistry) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-type-validation.mjs","names":[],"sources":["../src/index-type-validation.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"index-type-validation.mjs","names":[],"sources":["../src/index-type-validation.ts"],"sourcesContent":["import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\nimport type { IndexTypeRegistry } from './index-types';\nimport type { SqlStorage } from './types';\n\nexport function validateIndexTypes(\n contract: Contract<SqlStorage>,\n indexTypeRegistry: IndexTypeRegistry,\n): void {\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const index of table.indexes) {\n if (index.type === undefined && index.options !== undefined) {\n throw new ContractValidationError(\n `Table \"${tableName}\" index on columns [${index.columns.join(', ')}] has options without a type`,\n 'storage',\n );\n }\n if (index.type === undefined) continue;\n const entry = indexTypeRegistry.get(index.type);\n if (entry === undefined) {\n throw new ContractValidationError(\n `Table \"${tableName}\" index on columns [${index.columns.join(', ')}] uses unregistered index type \"${index.type}\"`,\n 'storage',\n );\n }\n const optionsValue = index.options ?? {};\n const result = entry.options(optionsValue);\n if (result instanceof type.errors) {\n throw new ContractValidationError(\n `Table \"${tableName}\" index on columns [${index.columns.join(', ')}] has invalid options for type \"${index.type}\": ${result.summary}`,\n 'storage',\n );\n }\n }\n }\n}\n"],"mappings":";;;AAMA,SAAgB,mBACd,UACA,mBACM;CACN,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,SAAS,QAAQ,OAAO,EACtE,KAAK,MAAM,SAAS,MAAM,SAAS;EACjC,IAAI,MAAM,SAAS,KAAA,KAAa,MAAM,YAAY,KAAA,GAChD,MAAM,IAAI,wBACR,UAAU,UAAU,sBAAsB,MAAM,QAAQ,KAAK,KAAK,CAAC,+BACnE,UACD;EAEH,IAAI,MAAM,SAAS,KAAA,GAAW;EAC9B,MAAM,QAAQ,kBAAkB,IAAI,MAAM,KAAK;EAC/C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,wBACR,UAAU,UAAU,sBAAsB,MAAM,QAAQ,KAAK,KAAK,CAAC,kCAAkC,MAAM,KAAK,IAChH,UACD;EAEH,MAAM,eAAe,MAAM,WAAW,EAAE;EACxC,MAAM,SAAS,MAAM,QAAQ,aAAa;EAC1C,IAAI,kBAAkB,KAAK,QACzB,MAAM,IAAI,wBACR,UAAU,UAAU,sBAAsB,MAAM,QAAQ,KAAK,KAAK,CAAC,kCAAkC,MAAM,KAAK,KAAK,OAAO,WAC5H,UACD"}
|
|
@@ -18,7 +18,7 @@ import { CodecTrait } from "@prisma-next/framework-components/codec";
|
|
|
18
18
|
*
|
|
19
19
|
* - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope
|
|
20
20
|
* shape (no `kind` field), so emitted contract.json files and the
|
|
21
|
-
* `
|
|
21
|
+
* `validateSqlContractFully` arktype schemas stay unchanged.
|
|
22
22
|
* - Test assertions that use `toEqual({...})` against the pre-lift flat
|
|
23
23
|
* shape continue to pass — only enumerable own properties are
|
|
24
24
|
* compared.
|
|
@@ -495,4 +495,4 @@ type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T
|
|
|
495
495
|
type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] ? ExtractCodecTypes<TContract> : CodecTypesOf<TTypeMaps>;
|
|
496
496
|
//#endregion
|
|
497
497
|
export { StorageTypeInstance as A, Index as B, TypeMapsPhantomKey as C, SqlStorageInput as D, SqlStorage as E, StorageTableInput as F, PostgresEnumStorageEntry as G, PrimaryKey as H, UniqueConstraint as I, ForeignKeyInput as J, isPostgresEnumStorageEntry as K, UniqueConstraintInput as L, isStorageTypeInstance as M, toStorageTypeInstance as N, SqlStorageTypeEntry as O, StorageTable as P, SqlNode as Q, StorageColumn as R, TypeMaps as S, SqlUnspecifiedNamespace as T, PrimaryKeyInput as U, IndexInput as V, POSTGRES_ENUM_KIND as W, ForeignKeyReferences as X, ReferentialAction as Y, ForeignKeyReferencesInput as Z, QueryOperationTypesOf as _, ExtractCodecTypes as a, SqlModelStorage as b, ExtractQueryOperationTypes as c, FieldOutputTypesOf as d, ForeignKeyOptions as f, QueryOperationTypesBase as g, QueryOperationTypeEntry as h, DEFAULT_FK_INDEX as i, StorageTypeInstanceInput as j, CODEC_INSTANCE_KIND as k, ExtractTypeMapsFromContract as l, QueryOperationSelfSpec as m, ContractWithTypeMaps as n, ExtractFieldInputTypes as o, QueryOperationReturn as p, ForeignKey as q, DEFAULT_FK_CONSTRAINT as r, ExtractFieldOutputTypes as s, CodecTypesOf as t, FieldInputTypesOf as u, ResolveCodecTypes as v, applyFkDefaults as w, SqlQueryOperationTypes as x, SqlModelFieldStorage as y, StorageColumnInput as z };
|
|
498
|
-
//# sourceMappingURL=types-
|
|
498
|
+
//# sourceMappingURL=types-B0lbr9cb.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-
|
|
1
|
+
{"version":3,"file":"types-B0lbr9cb.d.mts","names":[],"sources":["../src/ir/sql-node.ts","../src/ir/foreign-key-references.ts","../src/ir/foreign-key.ts","../src/ir/postgres-enum-storage-entry.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts","../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts","../src/ir/sql-unspecified-namespace.ts","../src/types.ts"],"mappings":";;;;;;;;;AAkCA;;;;;;;;;;;;AC/BA;;;;;AAYA;;;;;;;;;;;uBDmBsB,OAAA,SAAgB,UAAA;EAAA,SAC3B,IAAA;;;;;UChCM,yBAAA;EAAA,SACN,KAAA;EAAA,SACA,OAAA;AAAA;AD6BX;;;;;;;AAAA,cCnBa,oBAAA,SAA6B,OAAA;EAAA,SAC/B,KAAA;EAAA,SACA,OAAA;cAEG,KAAA,EAAO,yBAAA;AAAA;;;KCfT,iBAAA;AAAA,UAEK,eAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA,EAAY,oBAAA,GAAuB,yBAAA;EAAA,SACnC,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAA;EFuBgB;EAAA,SErB3B,UAAA;;WAEA,KAAA;AAAA;;;;ADZX;;;;;cCuBa,UAAA,SAAmB,OAAA;EAAA,SACrB,OAAA;EAAA,SACA,UAAA,EAAY,oBAAA;EAAA,SACZ,UAAA;EAAA,SACA,KAAA;EAAA,SACQ,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SAC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A,GACA,MAAA,kBACF,MAAA;AAAA,KAEM,iBAAA,OAAwB,CAAA,oBAChC,MAAA,kBACA,CAAA;EAAA,SAAqB,eAAA;AAAA,IACnB,CAAA,SAAU,MAAA,SAAe,MAAA,qBACvB,CAAA,GACA,MAAA,kBACF,MAAA;AAAA,KAEM,iBAAA,MAAuB,YAAA,CAAa,2BAAA,CAA4B,CAAA;AAAA,KAChE,0BAAA,MAAgC,qBAAA,CAAsB,2BAAA,CAA4B,CAAA;AAAA,KAClF,uBAAA,MAA6B,kBAAA,CAAmB,2BAAA,CAA4B,CAAA;AAAA,KAC5E,sBAAA,MAA4B,iBAAA,CAAkB,2BAAA,CAA4B,CAAA;AAAA,KAE1E,iBAAA,0BAA2C,SAAA,oBACnD,iBAAA,CAAkB,SAAA,IAClB,YAAA,CAAa,SAAA"}
|
|
@@ -15,7 +15,7 @@ import { IRNodeBase, NamespaceBase, UNSPECIFIED_NAMESPACE_ID, freezeNode } from
|
|
|
15
15
|
*
|
|
16
16
|
* - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope
|
|
17
17
|
* shape (no `kind` field), so emitted contract.json files and the
|
|
18
|
-
* `
|
|
18
|
+
* `validateSqlContractFully` arktype schemas stay unchanged.
|
|
19
19
|
* - Test assertions that use `toEqual({...})` against the pre-lift flat
|
|
20
20
|
* shape continue to pass — only enumerable own properties are
|
|
21
21
|
* compared.
|
|
@@ -342,17 +342,36 @@ var SqlStorage = class extends SqlNode {
|
|
|
342
342
|
this.storageHash = input.storageHash;
|
|
343
343
|
this.tables = Object.freeze(Object.fromEntries(Object.entries(input.tables).map(([name, t]) => [name, t instanceof StorageTable ? t : new StorageTable(t)])));
|
|
344
344
|
this.namespaces = input.namespaces ?? DEFAULT_NAMESPACES;
|
|
345
|
-
if (input.types !== void 0) this.types = Object.freeze(Object.fromEntries(Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(ti)])));
|
|
345
|
+
if (input.types !== void 0) this.types = Object.freeze(Object.fromEntries(Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)])));
|
|
346
346
|
freezeNode(this);
|
|
347
347
|
}
|
|
348
348
|
};
|
|
349
|
-
|
|
349
|
+
/**
|
|
350
|
+
* Strict polymorphic-slot dispatch for `SqlStorage.types` entries
|
|
351
|
+
* (TML-2536). Every entry must carry a recognised `kind` discriminator
|
|
352
|
+
* — either `'codec-instance'` (codec triple, family-shared) or
|
|
353
|
+
* `'postgres-enum'` (target-specific IR class). Untagged or
|
|
354
|
+
* unrecognised inputs throw a diagnostic naming the entry and its
|
|
355
|
+
* `kind`, so format drift surfaces loudly at the deserializer
|
|
356
|
+
* boundary instead of slipping past the seam and corrupting
|
|
357
|
+
* downstream IR walks.
|
|
358
|
+
*
|
|
359
|
+
* Codec-triple authors that have an untagged shape on hand can call
|
|
360
|
+
* `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`
|
|
361
|
+
* discriminator) before constructing `SqlStorage`. On-disk reads
|
|
362
|
+
* cross `familyInstance.deserializeContract` first; the structural
|
|
363
|
+
* arktype schema rejects untagged entries earlier, so this throw
|
|
364
|
+
* only fires for in-memory authoring bugs.
|
|
365
|
+
*/
|
|
366
|
+
function normaliseTypeEntry(name, entry) {
|
|
350
367
|
if (isPostgresEnumStorageEntry(entry)) {
|
|
351
368
|
if (entry instanceof SqlNode) return entry;
|
|
352
|
-
throw new Error(
|
|
369
|
+
throw new Error(`Encountered raw postgres-enum JSON in storage.types[${JSON.stringify(name)}] without serializer hydration; use a target ContractSerializer that registers the matching entity-type factory.`);
|
|
353
370
|
}
|
|
354
371
|
if (isStorageTypeInstance(entry)) return entry;
|
|
355
|
-
|
|
372
|
+
const rawKind = entry.kind;
|
|
373
|
+
const kindDescription = rawKind === void 0 ? "missing `kind` discriminator" : `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`;
|
|
374
|
+
throw new Error(`storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify("codec-instance")} or ${JSON.stringify("postgres-enum")}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`);
|
|
356
375
|
}
|
|
357
376
|
//#endregion
|
|
358
377
|
//#region src/types.ts
|
|
@@ -367,4 +386,4 @@ function applyFkDefaults(fk, overrideDefaults) {
|
|
|
367
386
|
//#endregion
|
|
368
387
|
export { ForeignKeyReferences as _, CODEC_INSTANCE_KIND as a, StorageTable as c, SqlUnspecifiedNamespace as d, Index as f, ForeignKey as g, isPostgresEnumStorageEntry as h, SqlStorage as i, UniqueConstraint as l, POSTGRES_ENUM_KIND as m, DEFAULT_FK_INDEX as n, isStorageTypeInstance as o, PrimaryKey as p, applyFkDefaults as r, toStorageTypeInstance as s, DEFAULT_FK_CONSTRAINT as t, StorageColumn as u, SqlNode as v };
|
|
369
388
|
|
|
370
|
-
//# sourceMappingURL=types-
|
|
389
|
+
//# sourceMappingURL=types-iqFGDcJp.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-iqFGDcJp.mjs","names":[],"sources":["../src/ir/sql-node.ts","../src/ir/foreign-key-references.ts","../src/ir/foreign-key.ts","../src/ir/postgres-enum-storage-entry.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/sql-unspecified-namespace.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts","../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts","../src/types.ts"],"sourcesContent":["import { IRNodeBase } from '@prisma-next/framework-components/ir';\n\n/**\n * SQL family IR node base. Carries the family-level `kind` discriminator\n * `'sql'` and inherits the framework's `freezeNode` affordance.\n *\n * Single family-level discriminator (not per-leaf) reflects the fact that\n * SQL IR has no polymorphic dispatch today — verifiers and serializers\n * walk by structural position (`storage.tables[name].columns[name]`),\n * not by inspecting `kind`. The abstract bar for per-leaf discriminators\n * isn't earned until a future polymorphic consumer arrives.\n *\n * `kind` is installed as a non-enumerable own property on every instance,\n * which keeps three things clean simultaneously:\n *\n * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope\n * shape (no `kind` field), so emitted contract.json files and the\n * `validateSqlContractFully` arktype schemas stay unchanged.\n * - Test assertions that use `toEqual({...})` against the pre-lift flat\n * shape continue to pass — only enumerable own properties are\n * compared.\n * - Direct access (`node.kind`) and runtime narrowing\n * (`if (node.kind === 'sql')`) still work, so future polymorphic\n * dispatch can begin reading `kind` without a runtime change.\n *\n * Future per-leaf overrides land cleanly: a class that gains a\n * polymorphic-dispatch consumer (e.g. an enum type instance walked\n * alongside other types) overrides `kind` with its narrower literal\n * at that leaf level. Per-leaf overrides will use enumerable kind\n * (matching the Mongo per-class-discriminator precedent) because they\n * encode dispatch-relevant information that callers need to see in\n * JSON envelopes; the family-level `'sql'` is uniform across all SQL\n * IR and carries no dispatch-relevant information.\n */\nexport abstract class SqlNode extends IRNodeBase {\n readonly kind?: string;\n\n constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql',\n writable: false,\n enumerable: false,\n // configurable so per-leaf subclasses (e.g. PostgresEnumType in\n // target-postgres) can override `kind` with their narrower\n // enumerable literal via a class-field initializer. SqlNode\n // itself never needs to mutate the property again, so\n // configurability has no surface impact at this layer.\n configurable: true,\n });\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface ForeignKeyReferencesInput {\n readonly table: string;\n readonly columns: readonly string[];\n}\n\n/**\n * SQL Contract IR node for the referenced side of a foreign key.\n *\n * The class is shaped around single-namespace references today; a\n * future milestone introduces a cross-namespace coordinate on top of\n * `(table, columns)` when namespace-keyed storage lands.\n */\nexport class ForeignKeyReferences extends SqlNode {\n readonly table: string;\n readonly columns: readonly string[];\n\n constructor(input: ForeignKeyReferencesInput) {\n super();\n this.table = input.table;\n this.columns = input.columns;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKeyReferences, type ForeignKeyReferencesInput } from './foreign-key-references';\nimport { SqlNode } from './sql-node';\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport interface ForeignKeyInput {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences | ForeignKeyReferencesInput;\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n}\n\n/**\n * SQL Contract IR node for a table-level foreign-key declaration.\n *\n * The nested `references` field is normalised to a\n * {@link ForeignKeyReferences} instance inside the constructor so\n * downstream walks see a uniform AST regardless of whether the input\n * was a JSON literal or an already-constructed class instance.\n */\nexport class ForeignKey extends SqlNode {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences;\n readonly constraint: boolean;\n readonly index: boolean;\n declare readonly name?: string;\n declare readonly onDelete?: ReferentialAction;\n declare readonly onUpdate?: ReferentialAction;\n\n constructor(input: ForeignKeyInput) {\n super();\n this.columns = input.columns;\n this.references =\n input.references instanceof ForeignKeyReferences\n ? input.references\n : new ForeignKeyReferences(input.references);\n this.constraint = input.constraint;\n this.index = input.index;\n if (input.name !== undefined) this.name = input.name;\n if (input.onDelete !== undefined) this.onDelete = input.onDelete;\n if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;\n freezeNode(this);\n }\n}\n","import type { StorageType } from '@prisma-next/framework-components/ir';\n\n/**\n * Discriminator literal for the Postgres-enum variant on the polymorphic\n * `SqlStorage.types` slot.\n *\n * Enums are a target-level concept: Postgres ships native\n * `CREATE TYPE … AS ENUM` while other SQL targets approximate enums via\n * constraints. The literal lives at the SQL family layer because every\n * SQL-family consumer (verifier, planner, lowering, …) needs to\n * discriminate enum-typed slot entries from codec-typed ones. The\n * concrete IR class (`PostgresEnumType`) lives in the target-postgres\n * package and implements this structural contract; cross-domain\n * layering rules forbid the SQL family from importing the concrete\n * target class directly, so the discriminator and structural interface\n * carry the dispatch.\n */\nexport const POSTGRES_ENUM_KIND = 'postgres-enum' as const;\n\n/**\n * Structural contract every Postgres-enum slot entry honours — both\n * the live `PostgresEnumType` IR-class instance and the raw JSON\n * envelope shape that survives `JSON.stringify` round-trips. SQL\n * family-layer dispatch narrows polymorphic `StorageType` slot\n * entries to this shape via `isPostgresEnumStorageEntry`.\n *\n * The `codecBinding` field is accessor-shaped (live class instance) on\n * the IR class and undefined on the raw JSON envelope; consumers that\n * need it must guard for its presence (the JSON path synthesises an\n * equivalent shape from `codecId` + `values`).\n */\nexport interface PostgresEnumStorageEntry extends StorageType {\n readonly kind: typeof POSTGRES_ENUM_KIND;\n readonly name: string;\n readonly nativeType: string;\n readonly values: readonly string[];\n /**\n * Enumerable own property on the persisted JSON envelope; the live\n * IR-class instance carries it too. Family-shared dispatch sites\n * read `codecId` directly rather than going through the IR-class\n * `codecBinding` accessor (which lives on the prototype and isn't\n * present on raw JSON envelopes).\n */\n readonly codecId: string;\n}\n\n/**\n * Narrow a polymorphic `StorageType` entry to the Postgres-enum shape\n * via its enumerable `kind` discriminator. Type guard returns true for\n * both live `PostgresEnumType` instances and raw JSON envelopes.\n */\nexport function isPostgresEnumStorageEntry(value: unknown): value is PostgresEnumStorageEntry {\n if (typeof value !== 'object' || value === null) return false;\n return (value as { kind?: unknown }).kind === POSTGRES_ENUM_KIND;\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface PrimaryKeyInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table's primary-key constraint.\n */\nexport class PrimaryKey extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: PrimaryKeyInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface IndexInput {\n readonly columns: readonly string[];\n readonly name?: string;\n readonly type?: string;\n readonly options?: Record<string, unknown>;\n}\n\n/**\n * SQL Contract IR node for a table-level secondary index.\n *\n * Note that this class shadows the global TypeScript `Index` lib type\n * at the family-shared name; consumer files that need both should\n * alias one (e.g.\n * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).\n */\nexport class Index extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n declare readonly type?: string;\n declare readonly options?: Record<string, unknown>;\n\n constructor(input: IndexInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n if (input.type !== undefined) this.type = input.type;\n if (input.options !== undefined) this.options = input.options;\n freezeNode(this);\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNSPECIFIED_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\n\n/**\n * Family-layer placeholder for the SQL unspecified-namespace singleton.\n *\n * SQL contracts honour the framework `Storage.namespaces` invariant from\n * the moment they appear in the IR. Today `SqlStorage` is family-shared\n * (Postgres + SQLite consume the same class); a per-target namespace\n * concretion (`PostgresSchema.unspecified`, `SqliteUnspecifiedDatabase.instance`)\n * earns its existence when each target's namespace shape lands. Until\n * then the family ships a single placeholder singleton so the JSON\n * envelope and runtime walk are honest at every layer.\n *\n * The `kind` discriminator is installed as a non-enumerable own property\n * so the JSON envelope reads `{ \"id\": \"__unspecified__\" }` — symmetric\n * with the family-level non-enumerable `kind` on `SqlNode` and bounded\n * to the minimum data the framework `Namespace` interface promises.\n *\n * **Freeze-trap warning.** The leaf constructor calls\n * `freezeNode(this)` after installing `kind`. The leaf-class shape\n * works today only because `NamespaceBase` does NOT freeze in its\n * constructor — the `Object.defineProperty(this, 'kind', …)` call after\n * `super()` succeeds because the instance is still mutable at that\n * point. Subclasses that add instance fields will still hit the freeze\n * trap once leaf-class `freezeNode(this)` runs; and if a future\n * framework change lifts the freeze to `NamespaceBase`, even the\n * `defineProperty` here would silently fail. To add subclass instance\n * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each\n * leaf calls explicitly at the end of its own constructor.\n */\nexport class SqlUnspecifiedNamespace extends NamespaceBase {\n static readonly instance: SqlUnspecifiedNamespace = new SqlUnspecifiedNamespace();\n\n readonly id = UNSPECIFIED_NAMESPACE_ID;\n declare readonly kind?: string;\n\n private constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageColumn}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n *\n * `typeParams` and `typeRef` remain mutually exclusive (one or the\n * other, not both); the constructor preserves whichever caller-side\n * choice the input encodes.\n */\nexport interface StorageColumnInput {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n readonly typeParams?: Record<string, unknown>;\n readonly typeRef?: string;\n readonly default?: ColumnDefault;\n}\n\n/**\n * SQL Contract IR node for a single column entry in `StorageTable.columns`.\n *\n * Single concrete family-shared class — every SQL target reads the\n * same column shape today, so there is no per-target subclass. The\n * class type accepts any caller that constructs via\n * `new StorageColumn(input)`; literal construction sites must pass\n * through the constructor or the family-base hydration walker.\n *\n * The column's `name` is not on the class — columns are keyed by name\n * in the parent `StorageTable.columns: Record<string, StorageColumn>`\n * map, so a `name` field would be redundant with the key.\n */\nexport class StorageColumn extends SqlNode {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n declare readonly typeParams?: Record<string, unknown>;\n declare readonly typeRef?: string;\n declare readonly default?: ColumnDefault;\n\n constructor(input: StorageColumnInput) {\n super();\n this.nativeType = input.nativeType;\n this.codecId = input.codecId;\n this.nullable = input.nullable;\n if (input.typeParams !== undefined) this.typeParams = input.typeParams;\n if (input.typeRef !== undefined) this.typeRef = input.typeRef;\n if (input.default !== undefined) this.default = input.default;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface UniqueConstraintInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table-level unique constraint.\n */\nexport class UniqueConstraint extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: UniqueConstraintInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKey, type ForeignKeyInput } from './foreign-key';\nimport { PrimaryKey, type PrimaryKeyInput } from './primary-key';\nimport { Index, type IndexInput } from './sql-index';\nimport { SqlNode } from './sql-node';\nimport { StorageColumn, type StorageColumnInput } from './storage-column';\nimport { UniqueConstraint, type UniqueConstraintInput } from './unique-constraint';\n\nexport interface StorageTableInput {\n readonly columns: Record<string, StorageColumn | StorageColumnInput>;\n readonly primaryKey?: PrimaryKey | PrimaryKeyInput;\n readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>;\n readonly indexes: ReadonlyArray<Index | IndexInput>;\n readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>;\n}\n\n/**\n * SQL Contract IR node for a single table entry in `SqlStorage.tables`.\n *\n * The constructor normalises nested IR-class fields (columns, primary\n * key, uniques, indexes, foreign keys) into the appropriate class\n * instances so downstream walks see a uniform AST regardless of whether\n * the input was a JSON literal or an already-constructed class.\n *\n * The table's `name` is not on the class — tables are keyed by name in\n * the parent `SqlStorage.tables: Record<string, StorageTable>` map.\n * A future namespace-aware milestone will add a `namespaceId` field\n * when namespace-keyed storage lands; today's single-namespace shape\n * needs neither field.\n */\nexport class StorageTable extends SqlNode {\n readonly columns: Readonly<Record<string, StorageColumn>>;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n declare readonly primaryKey?: PrimaryKey;\n\n constructor(input: StorageTableInput) {\n super();\n this.columns = Object.freeze(\n Object.fromEntries(\n Object.entries(input.columns).map(([name, col]) => [\n name,\n col instanceof StorageColumn ? col : new StorageColumn(col),\n ]),\n ),\n );\n if (input.primaryKey !== undefined) {\n this.primaryKey =\n input.primaryKey instanceof PrimaryKey\n ? input.primaryKey\n : new PrimaryKey(input.primaryKey);\n }\n this.uniques = Object.freeze(\n input.uniques.map((u) => (u instanceof UniqueConstraint ? u : new UniqueConstraint(u))),\n );\n this.indexes = Object.freeze(input.indexes.map((i) => (i instanceof Index ? i : new Index(i))));\n this.foreignKeys = Object.freeze(\n input.foreignKeys.map((fk) => (fk instanceof ForeignKey ? fk : new ForeignKey(fk))),\n );\n freezeNode(this);\n }\n}\n","import type { StorageType } from '@prisma-next/framework-components/ir';\n\n/**\n * Sentinel kind for the legacy codec-triple shape persisted under\n * `SqlStorage.types`. Plain JSON-clean object literals carry this\n * discriminator so the polymorphic slot dispatch can route them down\n * the codec path while target-specific IR class instances (e.g. the\n * Postgres enum class) keep their own narrower `kind` literal.\n */\nexport const CODEC_INSTANCE_KIND = 'codec-instance' as const;\n\n/**\n * Structural sub-interface of {@link StorageType} for codec-typed entries\n * in `SqlStorage.types`. These are plain object literals — there is no\n * runtime IR class, the JSON envelope round-trips through the slot\n * unchanged. The `kind: 'codec-instance'` discriminator is the dispatch\n * key that distinguishes codec-typed entries from class-instance entries\n * (e.g. `PostgresEnumType`) sharing the polymorphic slot.\n */\nexport interface StorageTypeInstance extends StorageType {\n readonly kind: typeof CODEC_INSTANCE_KIND;\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n}\n\n/**\n * Construction-time input for a codec-triple entry. Symmetric with the\n * structural runtime shape minus the `kind` discriminator — callers may\n * omit `kind`; the helper {@link toStorageTypeInstance} stamps it on.\n */\nexport interface StorageTypeInstanceInput {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n}\n\n/**\n * Stamp the codec-instance `kind` discriminator on a caller-supplied\n * codec triple. Idempotent: input that already carries the discriminator\n * passes through unchanged.\n */\nexport function toStorageTypeInstance(input: StorageTypeInstanceInput): StorageTypeInstance {\n return {\n kind: CODEC_INSTANCE_KIND,\n codecId: input.codecId,\n nativeType: input.nativeType,\n typeParams: input.typeParams,\n };\n}\n\n/**\n * Type-guard for codec-typed entries on the polymorphic\n * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from\n * class-instance kinds (e.g. `PostgresEnumType`).\n */\nexport function isStorageTypeInstance(value: unknown): value is StorageTypeInstance {\n if (typeof value !== 'object' || value === null) return false;\n return (value as { kind?: unknown }).kind === CODEC_INSTANCE_KIND;\n}\n","import type { StorageHashBase } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n type Namespace,\n type Storage,\n UNSPECIFIED_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n} from './postgres-enum-storage-entry';\nimport { SqlNode } from './sql-node';\nimport { SqlUnspecifiedNamespace } from './sql-unspecified-namespace';\nimport { StorageTable, type StorageTableInput } from './storage-table';\nimport {\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n} from './storage-type-instance';\n\n/**\n * Polymorphic value type for `SqlStorage.types` entries (Decision 18,\n * Option B). The slot's framework alphabet is `StorageType` — codec\n * triples (`StorageTypeInstance` with `kind: 'codec-instance'`) and\n * target-specific IR class instances structurally satisfying\n * `PostgresEnumStorageEntry` (with `kind: 'postgres-enum'`) are the\n * two variants the SQL family ships today. The construction side also\n * accepts {@link StorageTypeInstanceInput} so callers can pass raw\n * codec triples; the constructor stamps the discriminator.\n */\nexport type SqlStorageTypeEntry =\n | StorageTypeInstance\n | PostgresEnumStorageEntry\n | StorageTypeInstanceInput;\n\nconst DEFAULT_NAMESPACES: Readonly<Record<string, Namespace>> = Object.freeze({\n [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance,\n});\n\nexport interface SqlStorageInput<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n readonly tables: Record<string, StorageTable | StorageTableInput>;\n readonly types?: Record<string, SqlStorageTypeEntry>;\n readonly namespaces?: Readonly<Record<string, Namespace>>;\n}\n\n/**\n * SQL Contract IR root node for the `storage` field.\n *\n * Single concrete family-shared class — both Postgres and SQLite\n * consume this same class today. Per-target storage subclasses are\n * introduced when each target's namespace shape earns its\n * target-specific concretion (target-specific derived fields,\n * target-specific storage extensions).\n *\n * Honours the framework `Storage` interface: every SQL IR carries a\n * `namespaces` map keyed by namespace id. The default singleton\n * (`{ [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance }`)\n * binds every contract authored before per-target namespace concretions\n * land; per-target namespace classes (`PostgresSchema.unspecified`,\n * `SqliteUnspecifiedDatabase.instance`) earn their slots when each\n * target's namespace shape lands.\n *\n * The constructor normalises nested IR-class fields (`tables`, optional\n * `types`) into class instances so downstream walks see a uniform AST.\n * `types` is polymorphic per Decision 18 Option B: codec-triple inputs\n * are stamped with `kind: 'codec-instance'`; class-instance kinds\n * (e.g. Postgres-enum entries satisfying `PostgresEnumStorageEntry`)\n * pass through; hydration of raw JSON class-instance entries (carrying\n * their narrower `kind` literal) is the per-target serializer's\n * responsibility (so the family base does not import target-specific\n * subclasses).\n */\nexport class SqlStorage<THash extends string = string> extends SqlNode implements Storage {\n readonly storageHash: StorageHashBase<THash>;\n readonly tables: Readonly<Record<string, StorageTable>>;\n readonly namespaces: Readonly<Record<string, Namespace>>;\n // SQL-family slot view: the two structural variants the family ships\n // today (codec triples + Postgres-enum structural entries). Each\n // variant extends the framework `StorageType` alphabet; the SQL\n // narrowing keeps cross-domain layering clean — SQL-family consumers\n // dispatch via `isStorageTypeInstance` / `isPostgresEnumStorageEntry`\n // type guards rather than importing the target's concrete IR class\n // (cross-domain rule: SQL may not import `target-*`).\n declare readonly types?: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n\n constructor(input: SqlStorageInput<THash>) {\n super();\n this.storageHash = input.storageHash;\n this.tables = Object.freeze(\n Object.fromEntries(\n Object.entries(input.tables).map(([name, t]) => [\n name,\n t instanceof StorageTable ? t : new StorageTable(t),\n ]),\n ),\n );\n this.namespaces = input.namespaces ?? DEFAULT_NAMESPACES;\n if (input.types !== undefined) {\n this.types = Object.freeze(\n Object.fromEntries(\n Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]),\n ),\n );\n }\n freezeNode(this);\n }\n}\n\n/**\n * Strict polymorphic-slot dispatch for `SqlStorage.types` entries\n * (TML-2536). Every entry must carry a recognised `kind` discriminator\n * — either `'codec-instance'` (codec triple, family-shared) or\n * `'postgres-enum'` (target-specific IR class). Untagged or\n * unrecognised inputs throw a diagnostic naming the entry and its\n * `kind`, so format drift surfaces loudly at the deserializer\n * boundary instead of slipping past the seam and corrupting\n * downstream IR walks.\n *\n * Codec-triple authors that have an untagged shape on hand can call\n * `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`\n * discriminator) before constructing `SqlStorage`. On-disk reads\n * cross `familyInstance.deserializeContract` first; the structural\n * arktype schema rejects untagged entries earlier, so this throw\n * only fires for in-memory authoring bugs.\n */\nfunction normaliseTypeEntry(\n name: string,\n entry: SqlStorageTypeEntry,\n): StorageTypeInstance | PostgresEnumStorageEntry {\n if (isPostgresEnumStorageEntry(entry)) {\n // Live class instances pass through unchanged; raw JSON envelopes\n // (e.g. `kind: 'postgres-enum'` without the class identity) are\n // rejected so the target serializer's hydration path is the only\n // way IR class instances enter the slot.\n if (entry instanceof SqlNode) {\n return entry;\n }\n throw new Error(\n `Encountered raw postgres-enum JSON in storage.types[${JSON.stringify(name)}] without serializer hydration; use a target ContractSerializer that registers the matching entity-type factory.`,\n );\n }\n if (isStorageTypeInstance(entry)) {\n return entry;\n }\n const rawKind = (entry as { kind?: unknown }).kind;\n const kindDescription =\n rawKind === undefined\n ? 'missing `kind` discriminator'\n : `unrecognised \\`kind\\` discriminator ${JSON.stringify(rawKind)}`;\n throw new Error(\n `storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify('codec-instance')} or ${JSON.stringify('postgres-enum')}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`,\n );\n}\n","import type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { ReferentialAction } from './ir/foreign-key';\n\nexport {\n ForeignKey,\n type ForeignKeyInput,\n type ReferentialAction,\n} from './ir/foreign-key';\nexport {\n ForeignKeyReferences,\n type ForeignKeyReferencesInput,\n} from './ir/foreign-key-references';\nexport {\n isPostgresEnumStorageEntry,\n POSTGRES_ENUM_KIND,\n type PostgresEnumStorageEntry,\n} from './ir/postgres-enum-storage-entry';\nexport { PrimaryKey, type PrimaryKeyInput } from './ir/primary-key';\nexport { Index, type IndexInput } from './ir/sql-index';\nexport { SqlNode } from './ir/sql-node';\nexport {\n SqlStorage,\n type SqlStorageInput,\n type SqlStorageTypeEntry,\n} from './ir/sql-storage';\nexport { SqlUnspecifiedNamespace } from './ir/sql-unspecified-namespace';\nexport { StorageColumn, type StorageColumnInput } from './ir/storage-column';\nexport { StorageTable, type StorageTableInput } from './ir/storage-table';\nexport {\n CODEC_INSTANCE_KIND,\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n toStorageTypeInstance,\n} from './ir/storage-type-instance';\nexport {\n UniqueConstraint,\n type UniqueConstraintInput,\n} from './ir/unique-constraint';\n\nexport type ForeignKeyOptions = {\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\nexport type SqlModelFieldStorage = {\n readonly column: string;\n readonly codecId?: string;\n readonly nullable?: boolean;\n};\n\nexport type SqlModelStorage = {\n readonly table: string;\n readonly fields: Record<string, SqlModelFieldStorage>;\n};\n\nexport const DEFAULT_FK_CONSTRAINT = true;\nexport const DEFAULT_FK_INDEX = true;\n\nexport function applyFkDefaults(\n fk: { constraint?: boolean | undefined; index?: boolean | undefined },\n overrideDefaults?: { constraint?: boolean | undefined; index?: boolean | undefined },\n): { constraint: boolean; index: boolean } {\n return {\n constraint: fk.constraint ?? overrideDefaults?.constraint ?? DEFAULT_FK_CONSTRAINT,\n index: fk.index ?? overrideDefaults?.index ?? DEFAULT_FK_INDEX,\n };\n}\n\nexport type TypeMaps<\n TCodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n TQueryOperationTypes extends Record<string, unknown> = Record<string, never>,\n TFieldOutputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,\n TFieldInputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,\n> = {\n readonly codecTypes: TCodecTypes;\n readonly queryOperationTypes: TQueryOperationTypes;\n readonly fieldOutputTypes: TFieldOutputTypes;\n readonly fieldInputTypes: TFieldInputTypes;\n};\n\nexport type CodecTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly codecTypes: infer C }\n ? C extends Record<string, { output: unknown }>\n ? C\n : Record<string, never>\n : Record<string, never>;\n\n/**\n * Dispatch hint identifying the first-argument target of an operation.\n *\n * Used by ORM column helpers to decide whether an operation is reachable on a\n * field. Either names a concrete codec identity or a set of capability traits\n * that the field's codec must carry.\n */\nexport type QueryOperationSelfSpec =\n | { readonly codecId: string; readonly traits?: never }\n | { readonly traits: readonly CodecTrait[]; readonly codecId?: never };\n\n/**\n * Structural shape an operation's impl must return: any value carrying a\n * codec-exact `returnType` descriptor. `Expression<T>` (from\n * `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`)\n * extends this. Trait-targeted returns are deliberately excluded — predicate\n * detection and result decoding both depend on knowing the concrete return\n * codec.\n */\nexport type QueryOperationReturn = {\n readonly returnType: { readonly codecId: string; readonly nullable: boolean };\n};\n\nexport type QueryOperationTypeEntry = {\n readonly self?: QueryOperationSelfSpec;\n readonly impl: (...args: never[]) => QueryOperationReturn;\n};\n\nexport type SqlQueryOperationTypes<\n _CT extends Record<string, { readonly input: unknown; readonly output: unknown }>,\n T extends Record<string, QueryOperationTypeEntry>,\n> = T;\n\nexport type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>;\n\nexport type QueryOperationTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly queryOperationTypes: infer Q }\n ? Q extends Record<string, unknown>\n ? Q\n : Record<string, never>\n : Record<string, never>;\n\nexport type TypeMapsPhantomKey = '__@prisma-next/sql-contract/typeMaps@__';\n\nexport type ContractWithTypeMaps<TContract, TTypeMaps> = TContract & {\n readonly [K in TypeMapsPhantomKey]?: TTypeMaps;\n};\n\nexport type ExtractTypeMapsFromContract<T> = TypeMapsPhantomKey extends keyof T\n ? NonNullable<T[TypeMapsPhantomKey & keyof T]>\n : never;\n\nexport type FieldOutputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly fieldOutputTypes: infer F }\n ? F extends Record<string, Record<string, unknown>>\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type FieldInputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly fieldInputTypes: infer F }\n ? F extends Record<string, Record<string, unknown>>\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldOutputTypes<T> = FieldOutputTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>;\n\nexport type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never]\n ? ExtractCodecTypes<TContract>\n : CodecTypesOf<TTypeMaps>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAsB,UAAtB,cAAsC,WAAW;CAC/C;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;;;;;;;;;;;;;;;AAqBpB,SAAS,mBACP,MACA,OACgD;CAChD,IAAI,2BAA2B,MAAM,EAAE;EAKrC,IAAI,iBAAiB,SACnB,OAAO;EAET,MAAM,IAAI,MACR,uDAAuD,KAAK,UAAU,KAAK,CAAC,kHAC7E;;CAEH,IAAI,sBAAsB,MAAM,EAC9B,OAAO;CAET,MAAM,UAAW,MAA6B;CAC9C,MAAM,kBACJ,YAAY,KAAA,IACR,iCACA,uCAAuC,KAAK,UAAU,QAAQ;CACpE,MAAM,IAAI,MACR,iBAAiB,KAAK,UAAU,KAAK,CAAC,QAAQ,gBAAgB,aAAa,KAAK,UAAU,iBAAiB,CAAC,MAAM,KAAK,UAAU,gBAAgB,CAAC,iGACnJ;;;;AC/FH,MAAa,wBAAwB;AACrC,MAAa,mBAAmB;AAEhC,SAAgB,gBACd,IACA,kBACyC;CACzC,OAAO;EACL,YAAY,GAAG,cAAc,kBAAkB,cAAA;EAC/C,OAAO,GAAG,SAAS,kBAAkB,SAAA;EACtC"}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as StorageTypeInstance, B as Index, C as TypeMapsPhantomKey, D as SqlStorageInput, E as SqlStorage, F as StorageTableInput, G as PostgresEnumStorageEntry, H as PrimaryKey, I as UniqueConstraint, J as ForeignKeyInput, K as isPostgresEnumStorageEntry, L as UniqueConstraintInput, M as isStorageTypeInstance, N as toStorageTypeInstance, O as SqlStorageTypeEntry, P as StorageTable, Q as SqlNode, R as StorageColumn, S as TypeMaps, T as SqlUnspecifiedNamespace, U as PrimaryKeyInput, V as IndexInput, W as POSTGRES_ENUM_KIND, X as ForeignKeyReferences, Y as ReferentialAction, Z as ForeignKeyReferencesInput, _ as QueryOperationTypesOf, a as ExtractCodecTypes, b as SqlModelStorage, c as ExtractQueryOperationTypes, d as FieldOutputTypesOf, f as ForeignKeyOptions, g as QueryOperationTypesBase, h as QueryOperationTypeEntry, i as DEFAULT_FK_INDEX, j as StorageTypeInstanceInput, k as CODEC_INSTANCE_KIND, l as ExtractTypeMapsFromContract, m as QueryOperationSelfSpec, n as ContractWithTypeMaps, o as ExtractFieldInputTypes, p as QueryOperationReturn, q as ForeignKey, r as DEFAULT_FK_CONSTRAINT, s as ExtractFieldOutputTypes, t as CodecTypesOf, u as FieldInputTypesOf, v as ResolveCodecTypes, w as applyFkDefaults, x as SqlQueryOperationTypes, y as SqlModelFieldStorage, z as StorageColumnInput } from "./types-
|
|
1
|
+
import { A as StorageTypeInstance, B as Index, C as TypeMapsPhantomKey, D as SqlStorageInput, E as SqlStorage, F as StorageTableInput, G as PostgresEnumStorageEntry, H as PrimaryKey, I as UniqueConstraint, J as ForeignKeyInput, K as isPostgresEnumStorageEntry, L as UniqueConstraintInput, M as isStorageTypeInstance, N as toStorageTypeInstance, O as SqlStorageTypeEntry, P as StorageTable, Q as SqlNode, R as StorageColumn, S as TypeMaps, T as SqlUnspecifiedNamespace, U as PrimaryKeyInput, V as IndexInput, W as POSTGRES_ENUM_KIND, X as ForeignKeyReferences, Y as ReferentialAction, Z as ForeignKeyReferencesInput, _ as QueryOperationTypesOf, a as ExtractCodecTypes, b as SqlModelStorage, c as ExtractQueryOperationTypes, d as FieldOutputTypesOf, f as ForeignKeyOptions, g as QueryOperationTypesBase, h as QueryOperationTypeEntry, i as DEFAULT_FK_INDEX, j as StorageTypeInstanceInput, k as CODEC_INSTANCE_KIND, l as ExtractTypeMapsFromContract, m as QueryOperationSelfSpec, n as ContractWithTypeMaps, o as ExtractFieldInputTypes, p as QueryOperationReturn, q as ForeignKey, r as DEFAULT_FK_CONSTRAINT, s as ExtractFieldOutputTypes, t as CodecTypesOf, u as FieldInputTypesOf, v as ResolveCodecTypes, w as applyFkDefaults, x as SqlQueryOperationTypes, y as SqlModelFieldStorage, z as StorageColumnInput } from "./types-B0lbr9cb.mjs";
|
|
2
2
|
export { CODEC_INSTANCE_KIND, type CodecTypesOf, type ContractWithTypeMaps, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, type ExtractCodecTypes, type ExtractFieldInputTypes, type ExtractFieldOutputTypes, type ExtractQueryOperationTypes, type ExtractTypeMapsFromContract, type FieldInputTypesOf, type FieldOutputTypesOf, ForeignKey, type ForeignKeyInput, type ForeignKeyOptions, ForeignKeyReferences, type ForeignKeyReferencesInput, Index, type IndexInput, POSTGRES_ENUM_KIND, type PostgresEnumStorageEntry, PrimaryKey, type PrimaryKeyInput, type QueryOperationReturn, type QueryOperationSelfSpec, type QueryOperationTypeEntry, type QueryOperationTypesBase, type QueryOperationTypesOf, type ReferentialAction, type ResolveCodecTypes, type SqlModelFieldStorage, type SqlModelStorage, SqlNode, type SqlQueryOperationTypes, SqlStorage, type SqlStorageInput, type SqlStorageTypeEntry, SqlUnspecifiedNamespace, StorageColumn, type StorageColumnInput, StorageTable, type StorageTableInput, type StorageTypeInstance, type StorageTypeInstanceInput, type TypeMaps, type TypeMapsPhantomKey, UniqueConstraint, type UniqueConstraintInput, applyFkDefaults, isPostgresEnumStorageEntry, isStorageTypeInstance, toStorageTypeInstance };
|
package/dist/types.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as ForeignKeyReferences, a as CODEC_INSTANCE_KIND, c as StorageTable, d as SqlUnspecifiedNamespace, f as Index, g as ForeignKey, h as isPostgresEnumStorageEntry, i as SqlStorage, l as UniqueConstraint, m as POSTGRES_ENUM_KIND, n as DEFAULT_FK_INDEX, o as isStorageTypeInstance, p as PrimaryKey, r as applyFkDefaults, s as toStorageTypeInstance, t as DEFAULT_FK_CONSTRAINT, u as StorageColumn, v as SqlNode } from "./types-
|
|
1
|
+
import { _ as ForeignKeyReferences, a as CODEC_INSTANCE_KIND, c as StorageTable, d as SqlUnspecifiedNamespace, f as Index, g as ForeignKey, h as isPostgresEnumStorageEntry, i as SqlStorage, l as UniqueConstraint, m as POSTGRES_ENUM_KIND, n as DEFAULT_FK_INDEX, o as isStorageTypeInstance, p as PrimaryKey, r as applyFkDefaults, s as toStorageTypeInstance, t as DEFAULT_FK_CONSTRAINT, u as StorageColumn, v as SqlNode } from "./types-iqFGDcJp.mjs";
|
|
2
2
|
export { CODEC_INSTANCE_KIND, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, ForeignKey, ForeignKeyReferences, Index, POSTGRES_ENUM_KIND, PrimaryKey, SqlNode, SqlStorage, SqlUnspecifiedNamespace, StorageColumn, StorageTable, UniqueConstraint, applyFkDefaults, isPostgresEnumStorageEntry, isStorageTypeInstance, toStorageTypeInstance };
|
package/dist/validators.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as SqlStorage, J as ForeignKeyInput, Y as ReferentialAction, Z as ForeignKeyReferencesInput } from "./types-
|
|
1
|
+
import { E as SqlStorage, J as ForeignKeyInput, Y as ReferentialAction, Z as ForeignKeyReferencesInput } from "./types-B0lbr9cb.mjs";
|
|
2
2
|
import { Contract } from "@prisma-next/contract/types";
|
|
3
3
|
import * as _$arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
4
4
|
import * as _$arktype_internal_variants_string_ts0 from "arktype/internal/variants/string.ts";
|
|
@@ -33,17 +33,6 @@ declare const ForeignKeySchema: _$arktype_internal_variants_object_ts0.ObjectTyp
|
|
|
33
33
|
*/
|
|
34
34
|
declare function validateStorage(value: unknown): SqlStorage;
|
|
35
35
|
declare function validateModel(value: unknown): unknown;
|
|
36
|
-
/**
|
|
37
|
-
* Validates the structural shape of an SQL contract using Arktype.
|
|
38
|
-
*
|
|
39
|
-
* Ensures all required fields are present and have the correct types,
|
|
40
|
-
* including SQL-specific storage structure (tables, columns, constraints).
|
|
41
|
-
*
|
|
42
|
-
* @param value - The contract value to validate (typically from a JSON import)
|
|
43
|
-
* @returns The validated contract if structure is valid
|
|
44
|
-
* @throws ContractValidationError if the contract structure is invalid
|
|
45
|
-
*/
|
|
46
|
-
declare function validateSqlContract<T extends Contract<SqlStorage>>(value: unknown): T;
|
|
47
36
|
/**
|
|
48
37
|
* Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.
|
|
49
38
|
*
|
|
@@ -82,5 +71,5 @@ declare function validateSqlStorageConsistency(contract: Contract<SqlStorage>):
|
|
|
82
71
|
*/
|
|
83
72
|
declare function validateSqlContractFully<T extends Contract<SqlStorage>>(value: unknown): T;
|
|
84
73
|
//#endregion
|
|
85
|
-
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateModelStorageReferences,
|
|
74
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateModelStorageReferences, validateSqlContractFully, validateSqlStorageConsistency, validateStorage, validateStorageSemantics };
|
|
86
75
|
//# sourceMappingURL=validators.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"mappings":";;;;;;KAgBK,oBAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,8BAAmC,MAAA;AAAA;AAAA,KAEzC,qBAAA;EAAA,SAAmC,IAAA;EAAA,SAA2B,UAAA;AAAA;AAAA,cAQtD,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,oBAAA;AAAA,cAK1B,2BAAA,EAA2B,sCAAA,CAAA,UAAA,CAAA,qBAAA;AAAA,cAK3B,mBAAA,EAAmB,sCAAA,CAAA,UAAA,CAAA,oBAAA,GAAA,qBAAA;AAAA,cA4GnB,WAAA,EAKX,sCAAA,CALsB,UAAA;;;;YAKtB,MAAA;AAAA;AAAA,cAEW,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,yBAAA;AAAA,cAK1B,uBAAA,EAAuB,sCAAA,CAAA,UAAA,CAAA,iBAAA;AAAA,cAIvB,gBAAA,EAAgB,sCAAA,CAAA,UAAA,CAAA,eAAA;;;;AAjI7B;;;;iBA8QgB,eAAA,CAAgB,KAAA,YAAiB,UAAA;AAAA,iBAajC,aAAA,CAAc,KAAA
|
|
1
|
+
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"mappings":";;;;;;KAgBK,oBAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,8BAAmC,MAAA;AAAA;AAAA,KAEzC,qBAAA;EAAA,SAAmC,IAAA;EAAA,SAA2B,UAAA;AAAA;AAAA,cAQtD,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,oBAAA;AAAA,cAK1B,2BAAA,EAA2B,sCAAA,CAAA,UAAA,CAAA,qBAAA;AAAA,cAK3B,mBAAA,EAAmB,sCAAA,CAAA,UAAA,CAAA,oBAAA,GAAA,qBAAA;AAAA,cA4GnB,WAAA,EAKX,sCAAA,CALsB,UAAA;;;;YAKtB,MAAA;AAAA;AAAA,cAEW,0BAAA,EAA0B,sCAAA,CAAA,UAAA,CAAA,yBAAA;AAAA,cAK1B,uBAAA,EAAuB,sCAAA,CAAA,UAAA,CAAA,iBAAA;AAAA,cAIvB,gBAAA,EAAgB,sCAAA,CAAA,UAAA,CAAA,eAAA;;;;AAjI7B;;;;iBA8QgB,eAAA,CAAgB,KAAA,YAAiB,UAAA;AAAA,iBAajC,aAAA,CAAc,KAAA;;;;;;;;;;;;;AA1K9B;iBAqOgB,wBAAA,CAAyB,OAAA,EAAS,UAAA;;;;;;;iBAmJlC,8BAAA,CAA+B,QAAA,EAAU,QAAA,CAAS,UAAA;;;;AAjXlE;;;iBAkagB,6BAAA,CAA8B,QAAA,EAAU,QAAA,CAAS,UAAA;;AA7ZjE;;;;;AAIA;;iBAwfgB,wBAAA,WAAmC,QAAA,CAAS,UAAA,EAAA,CAAa,KAAA,YAAiB,CAAA"}
|
package/dist/validators.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as SqlStorage } from "./types-
|
|
2
|
-
import { ContractValidationError } from "@prisma-next/contract/
|
|
1
|
+
import { i as SqlStorage } from "./types-iqFGDcJp.mjs";
|
|
2
|
+
import { ContractValidationError } from "@prisma-next/contract/contract-validation-error";
|
|
3
3
|
import { validateContractDomain } from "@prisma-next/contract/validate-domain";
|
|
4
4
|
import { type } from "arktype";
|
|
5
5
|
//#region src/validators.ts
|
|
@@ -229,16 +229,12 @@ function validateModel(value) {
|
|
|
229
229
|
return result;
|
|
230
230
|
}
|
|
231
231
|
/**
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
* @param value - The contract value to validate (typically from a JSON import)
|
|
238
|
-
* @returns The validated contract if structure is valid
|
|
239
|
-
* @throws ContractValidationError if the contract structure is invalid
|
|
232
|
+
* Structural arktype validation of an SQL contract envelope. Internal
|
|
233
|
+
* helper for {@link validateSqlContractFully} — exposed only inside
|
|
234
|
+
* this module, since the family seam-of-record is the
|
|
235
|
+
* `SqlContractSerializerBase.deserializeContract` SPI.
|
|
240
236
|
*/
|
|
241
|
-
function
|
|
237
|
+
function validateSqlContractStructure(value) {
|
|
242
238
|
if (typeof value !== "object" || value === null) throw new ContractValidationError("Contract structural validation failed: value must be an object", "structural");
|
|
243
239
|
const rawValue = value;
|
|
244
240
|
if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql") throw new ContractValidationError(`Unsupported target family: ${rawValue.targetFamily}`, "structural");
|
|
@@ -392,7 +388,7 @@ function validateSqlStorageConsistency(contract) {
|
|
|
392
388
|
* base on top of this helper.
|
|
393
389
|
*/
|
|
394
390
|
function validateSqlContractFully(value) {
|
|
395
|
-
const validated =
|
|
391
|
+
const validated = validateSqlContractStructure(typeof value === "object" && value !== null ? (() => {
|
|
396
392
|
const { schemaVersion: _, _generated: _g, ...rest } = value;
|
|
397
393
|
return rest;
|
|
398
394
|
})() : value);
|
|
@@ -408,6 +404,6 @@ function validateSqlContractFully(value) {
|
|
|
408
404
|
return validated;
|
|
409
405
|
}
|
|
410
406
|
//#endregion
|
|
411
|
-
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateModelStorageReferences,
|
|
407
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, IndexSchema, ReferentialActionSchema, validateModel, validateModelStorageReferences, validateSqlContractFully, validateSqlStorageConsistency, validateStorage, validateStorageSemantics };
|
|
412
408
|
|
|
413
409
|
//# sourceMappingURL=validators.mjs.map
|
package/dist/validators.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.mjs","names":["f"],"sources":["../src/validators.ts"],"sourcesContent":["import type { Contract, ContractField, ContractModel } from '@prisma-next/contract/types';\nimport { ContractValidationError } from '@prisma-next/contract/validate-contract';\nimport { validateContractDomain } from '@prisma-next/contract/validate-domain';\nimport { type } from 'arktype';\nimport {\n type ForeignKeyInput,\n type ForeignKeyReferencesInput,\n type PrimaryKeyInput,\n type ReferentialAction,\n type SqlModelStorage,\n SqlStorage,\n type SqlStorageInput,\n type StorageTypeInstanceInput,\n type UniqueConstraintInput,\n} from './types';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst generatorKindSchema = type(\"'generator'\");\nconst generatorIdSchema = type('string').narrow((value, ctx) => {\n return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value) ? true : ctx.mustBe('a flat generator id');\n});\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst ExecutionMutationDefaultValueSchema = type({\n '+': 'reject',\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n '+': 'reject',\n ref: {\n '+': 'reject',\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n '+': 'reject',\n executionHash: 'string',\n mutations: {\n '+': 'reject',\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst StorageColumnSchema = type({\n '+': 'reject',\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\n});\n\n/**\n * Codec-triple entry persisted under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'codec-instance'` discriminator so the\n * polymorphic slot dispatch can distinguish codec triples from\n * class-instance kinds (e.g. `'postgres-enum'`) sharing the slot.\n */\nconst StorageTypeInstanceSchema = type\n .declare<StorageTypeInstanceInput & { kind: 'codec-instance' }>()\n .type({\n kind: \"'codec-instance'\",\n codecId: 'string',\n nativeType: 'string',\n typeParams: 'Record<string, unknown>',\n });\n\n/**\n * Polymorphic enum-type entry under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'postgres-enum'` discriminator so the\n * per-target hydration walker can dispatch cleanly back to a typed\n * IR-class instance during `deserializeContract`. The discriminator\n * reflects target-level behaviour (Postgres-native enums versus\n * family-layer codec triples) — not the family abstract altitude alone.\n *\n * The schema literal lives at the family layer today because\n * registry-driven validation for arbitrary slot shapes is not wired\n * yet; once a second polymorphic kind ships through the slot, this\n * structural enumeration can move to the registry-dispatch site and\n * per-target schemas can live in their target packages.\n */\nconst PostgresEnumTypeSchema = type({\n kind: \"'postgres-enum'\",\n name: 'string',\n nativeType: 'string',\n values: type.string.array().readonly(),\n});\n\n/**\n * Family-layer arktype validation enumerates the polymorphic shapes the\n * SQL family ships today (codec-instance + Postgres-enum). Pack-contributed\n * entity types ship a parallel arktype schema entry here when they\n * introduce a new persisted shape; the registry-driven hydration seam at\n * `SqlContractSerializerBase.hydrateStorageTypeEntry` is open, but the\n * family-layer structural validator is closed by design — extension\n * packs cannot inject arbitrary persisted shapes through the slot\n * without their structural shape being known at the family layer.\n *\n * A future refinement is to lift `StorageTypeEntrySchema` toward an\n * `unknown` fallback and move structural diagnostics to the\n * registry-dispatch site at hydration time, earned once a non-enum\n * storage shape needs to flow through the slot without growing another\n * closed union arm here first.\n */\nconst StorageTypeEntrySchema = PostgresEnumTypeSchema.or(StorageTypeInstanceSchema);\n\nconst PrimaryKeySchema = type.declare<PrimaryKeyInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraintInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nexport const IndexSchema = type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n 'type?': 'string',\n 'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferencesInput>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKeyInput>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nconst StorageTableSchema = type({\n '+': 'reject',\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\n/**\n * Namespace entry under `storage.namespaces[id]`. SQL contracts honour\n * the framework `Storage.namespaces` invariant from PR1; today every\n * contract binds to the singleton placeholder\n * (`SqlUnspecifiedNamespace.instance`) and the persisted shape carries\n * just the namespace id. Per-target namespace concretions\n * (`PostgresSchema`, `SqliteUnspecifiedDatabase`) can additively grow\n * the persisted shape when they earn their slots.\n */\nconst NamespaceEntrySchema = type({\n id: 'string',\n});\n\nconst StorageSchema = type({\n '+': 'reject',\n storageHash: 'string',\n tables: type({ '[string]': StorageTableSchema }),\n 'types?': type({ '[string]': StorageTypeEntrySchema }),\n 'namespaces?': type({ '[string]': NamespaceEntrySchema }),\n});\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction findDuplicateValue(values: readonly string[]): string | undefined {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n }\n return undefined;\n}\n\nfunction isContractFieldType(value: unknown): boolean {\n if (!isPlainRecord(value)) return false;\n const kind = value['kind'];\n if (kind === 'scalar') {\n if (typeof value['codecId'] !== 'string') return false;\n const typeParams = value['typeParams'];\n if (typeParams !== undefined && !isPlainRecord(typeParams)) return false;\n return true;\n }\n if (kind === 'valueObject') {\n return typeof value['name'] === 'string';\n }\n if (kind === 'union') {\n const members = value['members'];\n if (!Array.isArray(members)) return false;\n return members.every((m) => isContractFieldType(m));\n }\n return false;\n}\n\nconst ContractFieldTypeSchema = type('unknown').narrow((value, ctx) =>\n isContractFieldType(value) ? true : ctx.mustBe('scalar, valueObject, or union field type'),\n);\n\nconst ModelFieldSchema = type({\n '+': 'reject',\n nullable: 'boolean',\n type: ContractFieldTypeSchema,\n 'many?': 'true',\n 'dict?': 'true',\n});\n\nconst ModelStorageFieldSchema = type({\n column: 'string',\n 'codecId?': 'string',\n 'nullable?': 'boolean',\n});\n\nconst ModelStorageSchema = type({\n table: 'string',\n fields: type({ '[string]': ModelStorageFieldSchema }),\n});\n\nconst ModelSchema = type({\n storage: ModelStorageSchema,\n 'fields?': type({ '[string]': ModelFieldSchema }),\n 'relations?': type({ '[string]': 'unknown' }),\n 'discriminator?': 'unknown',\n 'variants?': 'unknown',\n 'base?': 'string',\n 'owner?': 'string',\n});\n\nconst ContractMetaSchema = type({\n '[string]': 'unknown',\n});\n\nconst SqlContractSchema = type({\n '+': 'reject',\n target: 'string',\n targetFamily: \"'sql'\",\n 'coreHash?': 'string',\n profileHash: 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': ContractMetaSchema,\n 'roots?': 'Record<string, string>',\n models: type({ '[string]': ModelSchema }),\n 'valueObjects?': 'Record<string, unknown>',\n storage: StorageSchema,\n 'execution?': ExecutionSchema,\n});\n\n// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()\n// instead of type.declare<T>().type() because the ColumnDefault union's value field\n// includes bigint | Date (runtime-only types after decoding) which cannot be expressed\n// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges\n// the gap between the JSON-safe Arktype output and the runtime TypeScript type.\n\n/**\n * Validates the structural shape of SqlStorage using Arktype.\n *\n * @param value - The storage value to validate\n * @returns The validated storage if structure is valid\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): SqlStorage {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n // The arktype-validated shape matches `SqlStorageInput`\n // structurally. Funnel through the constructor so nested IR fields\n // (`tables`, `types`) are normalised into class instances and the\n // branded `storageHash` is preserved on the returned `SqlStorage`.\n return new SqlStorage(result as SqlStorageInput);\n}\n\nexport function validateModel(value: unknown): unknown {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Validates the structural shape of an SQL contract using Arktype.\n *\n * Ensures all required fields are present and have the correct types,\n * including SQL-specific storage structure (tables, columns, constraints).\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 ContractValidationError if the contract structure is invalid\n */\nexport function validateSqlContract<T extends Contract<SqlStorage>>(value: unknown): T {\n if (typeof value !== 'object' || value === null) {\n throw new ContractValidationError(\n 'Contract structural validation failed: value must be an object',\n 'structural',\n );\n }\n\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n throw new ContractValidationError(\n `Unsupported target family: ${rawValue.targetFamily}`,\n 'structural',\n );\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 ContractValidationError(\n `Contract structural validation failed: ${messages}`,\n 'structural',\n );\n }\n\n // Arktype's inferred output type differs from T due to exactOptionalPropertyTypes\n // and branded hash types — the runtime value is structurally compatible after validation\n return contractResult as unknown as T;\n}\n\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - duplicate named primary key / unique / index / foreign key objects within a table\n * - duplicate unique, index, or foreign key declarations within a table\n * - duplicate columns within primary key / unique / index definitions\n * - nullable columns in primary key definitions\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const namedObjects = new Map<string, string[]>();\n const registerNamedObject = (kind: string, name: string | undefined) => {\n if (!name) return;\n namedObjects.set(name, [...(namedObjects.get(name) ?? []), kind]);\n };\n\n registerNamedObject('primary key', table.primaryKey?.name);\n for (const unique of table.uniques) {\n registerNamedObject('unique constraint', unique.name);\n }\n for (const index of table.indexes) {\n registerNamedObject('index', index.name);\n }\n for (const fk of table.foreignKeys) {\n registerNamedObject('foreign key', fk.name);\n }\n\n for (const [name, kinds] of namedObjects) {\n if (kinds.length > 1) {\n errors.push(\n `Table \"${tableName}\": named object \"${name}\" is declared multiple times (${kinds.join(', ')})`,\n );\n }\n }\n\n if (table.primaryKey) {\n const duplicateColumn = findDuplicateValue(table.primaryKey.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": primary key contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n for (const columnName of table.primaryKey.columns) {\n const column = table.columns[columnName];\n if (column?.nullable === true) {\n errors.push(\n `Table \"${tableName}\": primary key column \"${columnName}\" is nullable; primary key columns must be NOT NULL`,\n );\n }\n }\n }\n\n const seenUniqueDefinitions = new Set<string>();\n for (const unique of table.uniques) {\n const duplicateColumn = findDuplicateValue(unique.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": unique constraint contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({ columns: unique.columns });\n if (seenUniqueDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate unique constraint definition on columns [${unique.columns.join(', ')}]`,\n );\n continue;\n }\n seenUniqueDefinitions.add(signature);\n }\n\n const sortOptions = (o: Record<string, unknown> | undefined): Record<string, unknown> | null =>\n o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;\n\n const seenIndexDefinitions = new Set<string>();\n for (const index of table.indexes) {\n const duplicateColumn = findDuplicateValue(index.columns);\n if (duplicateColumn !== undefined) {\n errors.push(`Table \"${tableName}\": index contains duplicate column \"${duplicateColumn}\"`);\n }\n\n const signature = JSON.stringify({\n columns: index.columns,\n type: index.type ?? null,\n options: sortOptions(index.options),\n });\n if (seenIndexDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate index definition on columns [${index.columns.join(', ')}]`,\n );\n continue;\n }\n seenIndexDefinitions.add(signature);\n }\n\n const seenForeignKeyDefinitions = new Set<string>();\n for (const fk of table.foreignKeys) {\n const signature = JSON.stringify({\n columns: fk.columns,\n references: fk.references,\n onDelete: fk.onDelete ?? null,\n onUpdate: fk.onUpdate ?? null,\n constraint: fk.constraint,\n index: fk.index,\n });\n if (seenForeignKeyDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate foreign key definition on columns [${fk.columns.join(', ')}]`,\n );\n continue;\n }\n seenForeignKeyDefinitions.add(signature);\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n }\n\n return errors;\n}\n\n/**\n * SQL storage logical-consistency checks: every model.storage.table\n * resolves to a real table, every model.storage.fields[*].column\n * resolves to a real column, and value-object fields land on JSON-native\n * columns. Throws `ContractValidationError` on the first mismatch.\n */\nexport function validateModelStorageReferences(contract: Contract<SqlStorage>): void {\n const models = contract.models as Record<string, ContractModel<SqlModelStorage>>;\n for (const [modelName, model] of Object.entries(models)) {\n const storageTable = model.storage.table;\n\n const table = contract.storage.tables[storageTable] as\n | (typeof contract.storage.tables)[string]\n | undefined;\n if (!table) {\n throw new ContractValidationError(\n `Model \"${modelName}\" references non-existent table \"${storageTable}\"`,\n 'storage',\n );\n }\n\n const columnNames = new Set(Object.keys(table.columns));\n for (const [fieldName, field] of Object.entries(model.storage.fields)) {\n if (!columnNames.has(field.column)) {\n throw new ContractValidationError(\n `Model \"${modelName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${storageTable}\"`,\n 'storage',\n );\n }\n }\n\n const JSON_NATIVE_TYPES = new Set(['json', 'jsonb']);\n for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) {\n const f = domainField as ContractField;\n if (f.type?.kind !== 'valueObject') continue;\n const storageField = model.storage.fields[fieldName];\n if (!storageField) continue;\n const column = table.columns[storageField.column];\n if (!column) continue;\n if (!JSON_NATIVE_TYPES.has(column.nativeType)) {\n throw new ContractValidationError(\n `Model \"${modelName}\" field \"${fieldName}\" is a value object but storage column \"${storageField.column}\" has nativeType \"${column.nativeType}\" (expected json or jsonb)`,\n 'storage',\n );\n }\n }\n }\n}\n\n/**\n * Cross-table consistency checks for SQL storage: primary key, unique,\n * index, and foreign key column references resolve to real columns;\n * NOT NULL columns don't carry a literal `null` default; FK column\n * counts match their referenced columns. Throws on the first mismatch.\n */\nexport function validateSqlStorageConsistency(contract: Contract<SqlStorage>): void {\n const tableNames = new Set(Object.keys(contract.storage.tables));\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" index references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const [colName, column] of Object.entries(table.columns)) {\n if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {\n throw new ContractValidationError(\n `Table \"${tableName}\" column \"${colName}\" is NOT NULL but has a literal null default`,\n 'storage',\n );\n }\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n\n if (!tableNames.has(fk.references.table)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n 'storage',\n );\n }\n\n const referencedTable = contract.storage.tables[fk.references.table];\n if (!referencedTable) continue;\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n 'storage',\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n 'storage',\n );\n }\n }\n }\n}\n\n/**\n * Full SQL contract validation: structural (arktype) +\n * framework-shared domain + SQL storage logical-consistency + SQL\n * storage semantic + model ↔ storage reference checks. Throws\n * `ContractValidationError` on the first failure. Returns the\n * validated flat-data shape; IR class hydration happens in the SPI\n * base on top of this helper.\n */\nexport function validateSqlContractFully<T extends Contract<SqlStorage>>(value: unknown): T {\n const stripped =\n typeof value === 'object' && value !== null\n ? (() => {\n const { schemaVersion: _, _generated: _g, ...rest } = value as Record<string, unknown>;\n return rest;\n })()\n : value;\n const validated = validateSqlContract<T>(stripped);\n validateContractDomain({\n roots: validated.roots,\n models: validated.models,\n ...(validated.valueObjects ? { valueObjects: validated.valueObjects } : {}),\n });\n validateSqlStorageConsistency(validated);\n const semanticErrors = validateStorageSemantics(validated.storage);\n if (semanticErrors.length > 0) {\n throw new ContractValidationError(\n `Contract semantic validation failed: ${semanticErrors.join('; ')}`,\n 'storage',\n );\n }\n validateModelStorageReferences(validated);\n return validated;\n}\n"],"mappings":";;;;;AAqBA,MAAM,oBAAoB,KAAK,YAAY;AAC3C,MAAM,qBAAqB,KAAK,aAAa;AAC7C,MAAM,sBAAsB,KAAK,cAAc;AAC/C,MAAM,oBAAoB,KAAK,SAAS,CAAC,QAAQ,OAAO,QAAQ;CAC9D,OAAO,8BAA8B,KAAK,MAAM,GAAG,OAAO,IAAI,OAAO,sBAAsB;EAC3F;AAEF,MAAa,6BAA6B,KAAK,SAA+B,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;CACR,CAAC;AAEF,MAAa,8BAA8B,KAAK,SAAgC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;CACb,CAAC;AAEF,MAAa,sBAAsB,2BAA2B,GAAG,4BAA4B;AAE7F,MAAM,sCAAsC,KAAK;CAC/C,KAAK;CACL,MAAM;CACN,IAAI;CACJ,WAAW;CACZ,CAAC;AAaF,MAAM,kBAAkB,KAAK;CAC3B,KAAK;CACL,eAAe;CACf,WAAW;EACT,KAAK;EACL,UAhBmC,KAAK;GAC1C,KAAK;GACL,KAAK;IACH,KAAK;IACL,OAAO;IACP,QAAQ;IACT;GACD,aAAa;GACb,aAAa;GACd,CAO2C,CAAC,OAAO,CAAC,UAAU;EAC5D;CACF,CAAC;AAEF,MAAM,sBAAsB,KAAK;CAC/B,KAAK;CACL,YAAY;CACZ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AA8B,UAAU;CACxC,MAAM,iBAAiB,yBAAyB,UAAU,QAAQ;CAClE,IAAI,eAAe,SAAS,GAC1B,MAAM,IAAI,wBACR,wCAAwC,eAAe,KAAK,KAAK,IACjE,UACD;CAEH,+BAA+B,UAAU;CACzC,OAAO"}
|
|
1
|
+
{"version":3,"file":"validators.mjs","names":["f"],"sources":["../src/validators.ts"],"sourcesContent":["import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';\nimport type { Contract, ContractField, ContractModel } from '@prisma-next/contract/types';\nimport { validateContractDomain } from '@prisma-next/contract/validate-domain';\nimport { type } from 'arktype';\nimport {\n type ForeignKeyInput,\n type ForeignKeyReferencesInput,\n type PrimaryKeyInput,\n type ReferentialAction,\n type SqlModelStorage,\n SqlStorage,\n type SqlStorageInput,\n type StorageTypeInstanceInput,\n type UniqueConstraintInput,\n} from './types';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst generatorKindSchema = type(\"'generator'\");\nconst generatorIdSchema = type('string').narrow((value, ctx) => {\n return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value) ? true : ctx.mustBe('a flat generator id');\n});\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst ExecutionMutationDefaultValueSchema = type({\n '+': 'reject',\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n '+': 'reject',\n ref: {\n '+': 'reject',\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n '+': 'reject',\n executionHash: 'string',\n mutations: {\n '+': 'reject',\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst StorageColumnSchema = type({\n '+': 'reject',\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\n});\n\n/**\n * Codec-triple entry persisted under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'codec-instance'` discriminator so the\n * polymorphic slot dispatch can distinguish codec triples from\n * class-instance kinds (e.g. `'postgres-enum'`) sharing the slot.\n */\nconst StorageTypeInstanceSchema = type\n .declare<StorageTypeInstanceInput & { kind: 'codec-instance' }>()\n .type({\n kind: \"'codec-instance'\",\n codecId: 'string',\n nativeType: 'string',\n typeParams: 'Record<string, unknown>',\n });\n\n/**\n * Polymorphic enum-type entry under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'postgres-enum'` discriminator so the\n * per-target hydration walker can dispatch cleanly back to a typed\n * IR-class instance during `deserializeContract`. The discriminator\n * reflects target-level behaviour (Postgres-native enums versus\n * family-layer codec triples) — not the family abstract altitude alone.\n *\n * The schema literal lives at the family layer today because\n * registry-driven validation for arbitrary slot shapes is not wired\n * yet; once a second polymorphic kind ships through the slot, this\n * structural enumeration can move to the registry-dispatch site and\n * per-target schemas can live in their target packages.\n */\nconst PostgresEnumTypeSchema = type({\n kind: \"'postgres-enum'\",\n name: 'string',\n nativeType: 'string',\n values: type.string.array().readonly(),\n});\n\n/**\n * Family-layer arktype validation enumerates the polymorphic shapes the\n * SQL family ships today (codec-instance + Postgres-enum). Pack-contributed\n * entity types ship a parallel arktype schema entry here when they\n * introduce a new persisted shape; the registry-driven hydration seam at\n * `SqlContractSerializerBase.hydrateStorageTypeEntry` is open, but the\n * family-layer structural validator is closed by design — extension\n * packs cannot inject arbitrary persisted shapes through the slot\n * without their structural shape being known at the family layer.\n *\n * A future refinement is to lift `StorageTypeEntrySchema` toward an\n * `unknown` fallback and move structural diagnostics to the\n * registry-dispatch site at hydration time, earned once a non-enum\n * storage shape needs to flow through the slot without growing another\n * closed union arm here first.\n */\nconst StorageTypeEntrySchema = PostgresEnumTypeSchema.or(StorageTypeInstanceSchema);\n\nconst PrimaryKeySchema = type.declare<PrimaryKeyInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraintInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nexport const IndexSchema = type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n 'type?': 'string',\n 'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferencesInput>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKeyInput>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nconst StorageTableSchema = type({\n '+': 'reject',\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\n/**\n * Namespace entry under `storage.namespaces[id]`. SQL contracts honour\n * the framework `Storage.namespaces` invariant from PR1; today every\n * contract binds to the singleton placeholder\n * (`SqlUnspecifiedNamespace.instance`) and the persisted shape carries\n * just the namespace id. Per-target namespace concretions\n * (`PostgresSchema`, `SqliteUnspecifiedDatabase`) can additively grow\n * the persisted shape when they earn their slots.\n */\nconst NamespaceEntrySchema = type({\n id: 'string',\n});\n\nconst StorageSchema = type({\n '+': 'reject',\n storageHash: 'string',\n tables: type({ '[string]': StorageTableSchema }),\n 'types?': type({ '[string]': StorageTypeEntrySchema }),\n 'namespaces?': type({ '[string]': NamespaceEntrySchema }),\n});\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction findDuplicateValue(values: readonly string[]): string | undefined {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n }\n return undefined;\n}\n\nfunction isContractFieldType(value: unknown): boolean {\n if (!isPlainRecord(value)) return false;\n const kind = value['kind'];\n if (kind === 'scalar') {\n if (typeof value['codecId'] !== 'string') return false;\n const typeParams = value['typeParams'];\n if (typeParams !== undefined && !isPlainRecord(typeParams)) return false;\n return true;\n }\n if (kind === 'valueObject') {\n return typeof value['name'] === 'string';\n }\n if (kind === 'union') {\n const members = value['members'];\n if (!Array.isArray(members)) return false;\n return members.every((m) => isContractFieldType(m));\n }\n return false;\n}\n\nconst ContractFieldTypeSchema = type('unknown').narrow((value, ctx) =>\n isContractFieldType(value) ? true : ctx.mustBe('scalar, valueObject, or union field type'),\n);\n\nconst ModelFieldSchema = type({\n '+': 'reject',\n nullable: 'boolean',\n type: ContractFieldTypeSchema,\n 'many?': 'true',\n 'dict?': 'true',\n});\n\nconst ModelStorageFieldSchema = type({\n column: 'string',\n 'codecId?': 'string',\n 'nullable?': 'boolean',\n});\n\nconst ModelStorageSchema = type({\n table: 'string',\n fields: type({ '[string]': ModelStorageFieldSchema }),\n});\n\nconst ModelSchema = type({\n storage: ModelStorageSchema,\n 'fields?': type({ '[string]': ModelFieldSchema }),\n 'relations?': type({ '[string]': 'unknown' }),\n 'discriminator?': 'unknown',\n 'variants?': 'unknown',\n 'base?': 'string',\n 'owner?': 'string',\n});\n\nconst ContractMetaSchema = type({\n '[string]': 'unknown',\n});\n\nconst SqlContractSchema = type({\n '+': 'reject',\n target: 'string',\n targetFamily: \"'sql'\",\n 'coreHash?': 'string',\n profileHash: 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': ContractMetaSchema,\n 'roots?': 'Record<string, string>',\n models: type({ '[string]': ModelSchema }),\n 'valueObjects?': 'Record<string, unknown>',\n storage: StorageSchema,\n 'execution?': ExecutionSchema,\n});\n\n// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()\n// instead of type.declare<T>().type() because the ColumnDefault union's value field\n// includes bigint | Date (runtime-only types after decoding) which cannot be expressed\n// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges\n// the gap between the JSON-safe Arktype output and the runtime TypeScript type.\n\n/**\n * Validates the structural shape of SqlStorage using Arktype.\n *\n * @param value - The storage value to validate\n * @returns The validated storage if structure is valid\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): SqlStorage {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n // The arktype-validated shape matches `SqlStorageInput`\n // structurally. Funnel through the constructor so nested IR fields\n // (`tables`, `types`) are normalised into class instances and the\n // branded `storageHash` is preserved on the returned `SqlStorage`.\n return new SqlStorage(result as SqlStorageInput);\n}\n\nexport function validateModel(value: unknown): unknown {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Structural arktype validation of an SQL contract envelope. Internal\n * helper for {@link validateSqlContractFully} — exposed only inside\n * this module, since the family seam-of-record is the\n * `SqlContractSerializerBase.deserializeContract` SPI.\n */\nfunction validateSqlContractStructure<T extends Contract<SqlStorage>>(value: unknown): T {\n if (typeof value !== 'object' || value === null) {\n throw new ContractValidationError(\n 'Contract structural validation failed: value must be an object',\n 'structural',\n );\n }\n\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n throw new ContractValidationError(\n `Unsupported target family: ${rawValue.targetFamily}`,\n 'structural',\n );\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 ContractValidationError(\n `Contract structural validation failed: ${messages}`,\n 'structural',\n );\n }\n\n // Arktype's inferred output type differs from T due to exactOptionalPropertyTypes\n // and branded hash types — the runtime value is structurally compatible after validation\n return contractResult as unknown as T;\n}\n\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - duplicate named primary key / unique / index / foreign key objects within a table\n * - duplicate unique, index, or foreign key declarations within a table\n * - duplicate columns within primary key / unique / index definitions\n * - nullable columns in primary key definitions\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const namedObjects = new Map<string, string[]>();\n const registerNamedObject = (kind: string, name: string | undefined) => {\n if (!name) return;\n namedObjects.set(name, [...(namedObjects.get(name) ?? []), kind]);\n };\n\n registerNamedObject('primary key', table.primaryKey?.name);\n for (const unique of table.uniques) {\n registerNamedObject('unique constraint', unique.name);\n }\n for (const index of table.indexes) {\n registerNamedObject('index', index.name);\n }\n for (const fk of table.foreignKeys) {\n registerNamedObject('foreign key', fk.name);\n }\n\n for (const [name, kinds] of namedObjects) {\n if (kinds.length > 1) {\n errors.push(\n `Table \"${tableName}\": named object \"${name}\" is declared multiple times (${kinds.join(', ')})`,\n );\n }\n }\n\n if (table.primaryKey) {\n const duplicateColumn = findDuplicateValue(table.primaryKey.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": primary key contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n for (const columnName of table.primaryKey.columns) {\n const column = table.columns[columnName];\n if (column?.nullable === true) {\n errors.push(\n `Table \"${tableName}\": primary key column \"${columnName}\" is nullable; primary key columns must be NOT NULL`,\n );\n }\n }\n }\n\n const seenUniqueDefinitions = new Set<string>();\n for (const unique of table.uniques) {\n const duplicateColumn = findDuplicateValue(unique.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Table \"${tableName}\": unique constraint contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({ columns: unique.columns });\n if (seenUniqueDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate unique constraint definition on columns [${unique.columns.join(', ')}]`,\n );\n continue;\n }\n seenUniqueDefinitions.add(signature);\n }\n\n const sortOptions = (o: Record<string, unknown> | undefined): Record<string, unknown> | null =>\n o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;\n\n const seenIndexDefinitions = new Set<string>();\n for (const index of table.indexes) {\n const duplicateColumn = findDuplicateValue(index.columns);\n if (duplicateColumn !== undefined) {\n errors.push(`Table \"${tableName}\": index contains duplicate column \"${duplicateColumn}\"`);\n }\n\n const signature = JSON.stringify({\n columns: index.columns,\n type: index.type ?? null,\n options: sortOptions(index.options),\n });\n if (seenIndexDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate index definition on columns [${index.columns.join(', ')}]`,\n );\n continue;\n }\n seenIndexDefinitions.add(signature);\n }\n\n const seenForeignKeyDefinitions = new Set<string>();\n for (const fk of table.foreignKeys) {\n const signature = JSON.stringify({\n columns: fk.columns,\n references: fk.references,\n onDelete: fk.onDelete ?? null,\n onUpdate: fk.onUpdate ?? null,\n constraint: fk.constraint,\n index: fk.index,\n });\n if (seenForeignKeyDefinitions.has(signature)) {\n errors.push(\n `Table \"${tableName}\": duplicate foreign key definition on columns [${fk.columns.join(', ')}]`,\n );\n continue;\n }\n seenForeignKeyDefinitions.add(signature);\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n }\n\n return errors;\n}\n\n/**\n * SQL storage logical-consistency checks: every model.storage.table\n * resolves to a real table, every model.storage.fields[*].column\n * resolves to a real column, and value-object fields land on JSON-native\n * columns. Throws `ContractValidationError` on the first mismatch.\n */\nexport function validateModelStorageReferences(contract: Contract<SqlStorage>): void {\n const models = contract.models as Record<string, ContractModel<SqlModelStorage>>;\n for (const [modelName, model] of Object.entries(models)) {\n const storageTable = model.storage.table;\n\n const table = contract.storage.tables[storageTable] as\n | (typeof contract.storage.tables)[string]\n | undefined;\n if (!table) {\n throw new ContractValidationError(\n `Model \"${modelName}\" references non-existent table \"${storageTable}\"`,\n 'storage',\n );\n }\n\n const columnNames = new Set(Object.keys(table.columns));\n for (const [fieldName, field] of Object.entries(model.storage.fields)) {\n if (!columnNames.has(field.column)) {\n throw new ContractValidationError(\n `Model \"${modelName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${storageTable}\"`,\n 'storage',\n );\n }\n }\n\n const JSON_NATIVE_TYPES = new Set(['json', 'jsonb']);\n for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) {\n const f = domainField as ContractField;\n if (f.type?.kind !== 'valueObject') continue;\n const storageField = model.storage.fields[fieldName];\n if (!storageField) continue;\n const column = table.columns[storageField.column];\n if (!column) continue;\n if (!JSON_NATIVE_TYPES.has(column.nativeType)) {\n throw new ContractValidationError(\n `Model \"${modelName}\" field \"${fieldName}\" is a value object but storage column \"${storageField.column}\" has nativeType \"${column.nativeType}\" (expected json or jsonb)`,\n 'storage',\n );\n }\n }\n }\n}\n\n/**\n * Cross-table consistency checks for SQL storage: primary key, unique,\n * index, and foreign key column references resolve to real columns;\n * NOT NULL columns don't carry a literal `null` default; FK column\n * counts match their referenced columns. Throws on the first mismatch.\n */\nexport function validateSqlStorageConsistency(contract: Contract<SqlStorage>): void {\n const tableNames = new Set(Object.keys(contract.storage.tables));\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" index references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const [colName, column] of Object.entries(table.columns)) {\n if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {\n throw new ContractValidationError(\n `Table \"${tableName}\" column \"${colName}\" is NOT NULL but has a literal null default`,\n 'storage',\n );\n }\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n\n if (!tableNames.has(fk.references.table)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n 'storage',\n );\n }\n\n const referencedTable = contract.storage.tables[fk.references.table];\n if (!referencedTable) continue;\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n 'storage',\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n throw new ContractValidationError(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n 'storage',\n );\n }\n }\n }\n}\n\n/**\n * Full SQL contract validation: structural (arktype) +\n * framework-shared domain + SQL storage logical-consistency + SQL\n * storage semantic + model ↔ storage reference checks. Throws\n * `ContractValidationError` on the first failure. Returns the\n * validated flat-data shape; IR class hydration happens in the SPI\n * base on top of this helper.\n */\nexport function validateSqlContractFully<T extends Contract<SqlStorage>>(value: unknown): T {\n const stripped =\n typeof value === 'object' && value !== null\n ? (() => {\n const { schemaVersion: _, _generated: _g, ...rest } = value as Record<string, unknown>;\n return rest;\n })()\n : value;\n const validated = validateSqlContractStructure<T>(stripped);\n validateContractDomain({\n roots: validated.roots,\n models: validated.models,\n ...(validated.valueObjects ? { valueObjects: validated.valueObjects } : {}),\n });\n validateSqlStorageConsistency(validated);\n const semanticErrors = validateStorageSemantics(validated.storage);\n if (semanticErrors.length > 0) {\n throw new ContractValidationError(\n `Contract semantic validation failed: ${semanticErrors.join('; ')}`,\n 'storage',\n );\n }\n validateModelStorageReferences(validated);\n return validated;\n}\n"],"mappings":";;;;;AAqBA,MAAM,oBAAoB,KAAK,YAAY;AAC3C,MAAM,qBAAqB,KAAK,aAAa;AAC7C,MAAM,sBAAsB,KAAK,cAAc;AAC/C,MAAM,oBAAoB,KAAK,SAAS,CAAC,QAAQ,OAAO,QAAQ;CAC9D,OAAO,8BAA8B,KAAK,MAAM,GAAG,OAAO,IAAI,OAAO,sBAAsB;EAC3F;AAEF,MAAa,6BAA6B,KAAK,SAA+B,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;CACR,CAAC;AAEF,MAAa,8BAA8B,KAAK,SAAgC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;CACb,CAAC;AAEF,MAAa,sBAAsB,2BAA2B,GAAG,4BAA4B;AAE7F,MAAM,sCAAsC,KAAK;CAC/C,KAAK;CACL,MAAM;CACN,IAAI;CACJ,WAAW;CACZ,CAAC;AAaF,MAAM,kBAAkB,KAAK;CAC3B,KAAK;CACL,eAAe;CACf,WAAW;EACT,KAAK;EACL,UAhBmC,KAAK;GAC1C,KAAK;GACL,KAAK;IACH,KAAK;IACL,OAAO;IACP,QAAQ;IACT;GACD,aAAa;GACb,aAAa;GACd,CAO2C,CAAC,OAAO,CAAC,UAAU;EAC5D;CACF,CAAC;AAEF,MAAM,sBAAsB,KAAK;CAC/B,KAAK;CACL,YAAY;CACZ,SAAS;CACT,UAAU;CACV,eAAe;CACf,YAAY;CACZ,YAAY;CACb,CAAC,CAAC,QAAQ,KAAK,QAAQ;CACtB,IAAI,IAAI,eAAe,KAAA,KAAa,IAAI,YAAY,KAAA,GAClD,OAAO,IAAI,OAAO,uDAAuD;CAE3E,OAAO;EACP;;;;;;;AAQF,MAAM,4BAA4B,KAC/B,SAAgE,CAChE,KAAK;CACJ,MAAM;CACN,SAAS;CACT,YAAY;CACZ,YAAY;CACb,CAAC;;;;;;;;;;;;;;;;;AAuC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ache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "SQL contract types, validators, and IR factories for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/contract": "0.
|
|
10
|
-
"@prisma-next/framework-components": "0.
|
|
9
|
+
"@prisma-next/contract": "0.9.0-dev.1",
|
|
10
|
+
"@prisma-next/framework-components": "0.9.0-dev.1",
|
|
11
11
|
"arktype": "^2.1.29"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
|
-
"@prisma-next/test-utils": "0.
|
|
15
|
-
"@prisma-next/tsconfig": "0.
|
|
16
|
-
"@prisma-next/tsdown": "0.
|
|
14
|
+
"@prisma-next/test-utils": "0.9.0-dev.1",
|
|
15
|
+
"@prisma-next/tsconfig": "0.9.0-dev.1",
|
|
16
|
+
"@prisma-next/tsdown": "0.9.0-dev.1",
|
|
17
17
|
"tsdown": "0.22.0",
|
|
18
18
|
"typescript": "5.9.3",
|
|
19
19
|
"vitest": "4.1.5"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';
|
|
1
2
|
import type { Contract } from '@prisma-next/contract/types';
|
|
2
|
-
import { ContractValidationError } from '@prisma-next/contract/validate-contract';
|
|
3
3
|
import { type } from 'arktype';
|
|
4
4
|
import type { IndexTypeRegistry } from './index-types';
|
|
5
5
|
import type { SqlStorage } from './types';
|
package/src/ir/sql-node.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { IRNodeBase } from '@prisma-next/framework-components/ir';
|
|
|
15
15
|
*
|
|
16
16
|
* - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope
|
|
17
17
|
* shape (no `kind` field), so emitted contract.json files and the
|
|
18
|
-
* `
|
|
18
|
+
* `validateSqlContractFully` arktype schemas stay unchanged.
|
|
19
19
|
* - Test assertions that use `toEqual({...})` against the pre-lift flat
|
|
20
20
|
* shape continue to pass — only enumerable own properties are
|
|
21
21
|
* compared.
|
package/src/ir/sql-storage.ts
CHANGED
|
@@ -16,7 +16,6 @@ import {
|
|
|
16
16
|
isStorageTypeInstance,
|
|
17
17
|
type StorageTypeInstance,
|
|
18
18
|
type StorageTypeInstanceInput,
|
|
19
|
-
toStorageTypeInstance,
|
|
20
19
|
} from './storage-type-instance';
|
|
21
20
|
|
|
22
21
|
/**
|
|
@@ -100,7 +99,7 @@ export class SqlStorage<THash extends string = string> extends SqlNode implement
|
|
|
100
99
|
if (input.types !== undefined) {
|
|
101
100
|
this.types = Object.freeze(
|
|
102
101
|
Object.fromEntries(
|
|
103
|
-
Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(ti)]),
|
|
102
|
+
Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]),
|
|
104
103
|
),
|
|
105
104
|
);
|
|
106
105
|
}
|
|
@@ -108,7 +107,25 @@ export class SqlStorage<THash extends string = string> extends SqlNode implement
|
|
|
108
107
|
}
|
|
109
108
|
}
|
|
110
109
|
|
|
110
|
+
/**
|
|
111
|
+
* Strict polymorphic-slot dispatch for `SqlStorage.types` entries
|
|
112
|
+
* (TML-2536). Every entry must carry a recognised `kind` discriminator
|
|
113
|
+
* — either `'codec-instance'` (codec triple, family-shared) or
|
|
114
|
+
* `'postgres-enum'` (target-specific IR class). Untagged or
|
|
115
|
+
* unrecognised inputs throw a diagnostic naming the entry and its
|
|
116
|
+
* `kind`, so format drift surfaces loudly at the deserializer
|
|
117
|
+
* boundary instead of slipping past the seam and corrupting
|
|
118
|
+
* downstream IR walks.
|
|
119
|
+
*
|
|
120
|
+
* Codec-triple authors that have an untagged shape on hand can call
|
|
121
|
+
* `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`
|
|
122
|
+
* discriminator) before constructing `SqlStorage`. On-disk reads
|
|
123
|
+
* cross `familyInstance.deserializeContract` first; the structural
|
|
124
|
+
* arktype schema rejects untagged entries earlier, so this throw
|
|
125
|
+
* only fires for in-memory authoring bugs.
|
|
126
|
+
*/
|
|
111
127
|
function normaliseTypeEntry(
|
|
128
|
+
name: string,
|
|
112
129
|
entry: SqlStorageTypeEntry,
|
|
113
130
|
): StorageTypeInstance | PostgresEnumStorageEntry {
|
|
114
131
|
if (isPostgresEnumStorageEntry(entry)) {
|
|
@@ -120,11 +137,18 @@ function normaliseTypeEntry(
|
|
|
120
137
|
return entry;
|
|
121
138
|
}
|
|
122
139
|
throw new Error(
|
|
123
|
-
|
|
140
|
+
`Encountered raw postgres-enum JSON in storage.types[${JSON.stringify(name)}] without serializer hydration; use a target ContractSerializer that registers the matching entity-type factory.`,
|
|
124
141
|
);
|
|
125
142
|
}
|
|
126
143
|
if (isStorageTypeInstance(entry)) {
|
|
127
144
|
return entry;
|
|
128
145
|
}
|
|
129
|
-
|
|
146
|
+
const rawKind = (entry as { kind?: unknown }).kind;
|
|
147
|
+
const kindDescription =
|
|
148
|
+
rawKind === undefined
|
|
149
|
+
? 'missing `kind` discriminator'
|
|
150
|
+
: `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`;
|
|
151
|
+
throw new Error(
|
|
152
|
+
`storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify('codec-instance')} or ${JSON.stringify('postgres-enum')}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`,
|
|
153
|
+
);
|
|
130
154
|
}
|
package/src/validators.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';
|
|
1
2
|
import type { Contract, ContractField, ContractModel } from '@prisma-next/contract/types';
|
|
2
|
-
import { ContractValidationError } from '@prisma-next/contract/validate-contract';
|
|
3
3
|
import { validateContractDomain } from '@prisma-next/contract/validate-domain';
|
|
4
4
|
import { type } from 'arktype';
|
|
5
5
|
import {
|
|
@@ -324,16 +324,12 @@ export function validateModel(value: unknown): unknown {
|
|
|
324
324
|
}
|
|
325
325
|
|
|
326
326
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
-
* @param value - The contract value to validate (typically from a JSON import)
|
|
333
|
-
* @returns The validated contract if structure is valid
|
|
334
|
-
* @throws ContractValidationError if the contract structure is invalid
|
|
327
|
+
* Structural arktype validation of an SQL contract envelope. Internal
|
|
328
|
+
* helper for {@link validateSqlContractFully} — exposed only inside
|
|
329
|
+
* this module, since the family seam-of-record is the
|
|
330
|
+
* `SqlContractSerializerBase.deserializeContract` SPI.
|
|
335
331
|
*/
|
|
336
|
-
|
|
332
|
+
function validateSqlContractStructure<T extends Contract<SqlStorage>>(value: unknown): T {
|
|
337
333
|
if (typeof value !== 'object' || value === null) {
|
|
338
334
|
throw new ContractValidationError(
|
|
339
335
|
'Contract structural validation failed: value must be an object',
|
|
@@ -676,7 +672,7 @@ export function validateSqlContractFully<T extends Contract<SqlStorage>>(value:
|
|
|
676
672
|
return rest;
|
|
677
673
|
})()
|
|
678
674
|
: value;
|
|
679
|
-
const validated =
|
|
675
|
+
const validated = validateSqlContractStructure<T>(stripped);
|
|
680
676
|
validateContractDomain({
|
|
681
677
|
roots: validated.roots,
|
|
682
678
|
models: validated.models,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-BtB74x-Z.mjs","names":[],"sources":["../src/ir/sql-node.ts","../src/ir/foreign-key-references.ts","../src/ir/foreign-key.ts","../src/ir/postgres-enum-storage-entry.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/sql-unspecified-namespace.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts","../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts","../src/types.ts"],"sourcesContent":["import { IRNodeBase } from '@prisma-next/framework-components/ir';\n\n/**\n * SQL family IR node base. Carries the family-level `kind` discriminator\n * `'sql'` and inherits the framework's `freezeNode` affordance.\n *\n * Single family-level discriminator (not per-leaf) reflects the fact that\n * SQL IR has no polymorphic dispatch today — verifiers and serializers\n * walk by structural position (`storage.tables[name].columns[name]`),\n * not by inspecting `kind`. The abstract bar for per-leaf discriminators\n * isn't earned until a future polymorphic consumer arrives.\n *\n * `kind` is installed as a non-enumerable own property on every instance,\n * which keeps three things clean simultaneously:\n *\n * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope\n * shape (no `kind` field), so emitted contract.json files and the\n * `validateSqlContract` arktype schemas stay unchanged.\n * - Test assertions that use `toEqual({...})` against the pre-lift flat\n * shape continue to pass — only enumerable own properties are\n * compared.\n * - Direct access (`node.kind`) and runtime narrowing\n * (`if (node.kind === 'sql')`) still work, so future polymorphic\n * dispatch can begin reading `kind` without a runtime change.\n *\n * Future per-leaf overrides land cleanly: a class that gains a\n * polymorphic-dispatch consumer (e.g. an enum type instance walked\n * alongside other types) overrides `kind` with its narrower literal\n * at that leaf level. Per-leaf overrides will use enumerable kind\n * (matching the Mongo per-class-discriminator precedent) because they\n * encode dispatch-relevant information that callers need to see in\n * JSON envelopes; the family-level `'sql'` is uniform across all SQL\n * IR and carries no dispatch-relevant information.\n */\nexport abstract class SqlNode extends IRNodeBase {\n readonly kind?: string;\n\n constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql',\n writable: false,\n enumerable: false,\n // configurable so per-leaf subclasses (e.g. PostgresEnumType in\n // target-postgres) can override `kind` with their narrower\n // enumerable literal via a class-field initializer. SqlNode\n // itself never needs to mutate the property again, so\n // configurability has no surface impact at this layer.\n configurable: true,\n });\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface ForeignKeyReferencesInput {\n readonly table: string;\n readonly columns: readonly string[];\n}\n\n/**\n * SQL Contract IR node for the referenced side of a foreign key.\n *\n * The class is shaped around single-namespace references today; a\n * future milestone introduces a cross-namespace coordinate on top of\n * `(table, columns)` when namespace-keyed storage lands.\n */\nexport class ForeignKeyReferences extends SqlNode {\n readonly table: string;\n readonly columns: readonly string[];\n\n constructor(input: ForeignKeyReferencesInput) {\n super();\n this.table = input.table;\n this.columns = input.columns;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKeyReferences, type ForeignKeyReferencesInput } from './foreign-key-references';\nimport { SqlNode } from './sql-node';\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport interface ForeignKeyInput {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences | ForeignKeyReferencesInput;\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n}\n\n/**\n * SQL Contract IR node for a table-level foreign-key declaration.\n *\n * The nested `references` field is normalised to a\n * {@link ForeignKeyReferences} instance inside the constructor so\n * downstream walks see a uniform AST regardless of whether the input\n * was a JSON literal or an already-constructed class instance.\n */\nexport class ForeignKey extends SqlNode {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences;\n readonly constraint: boolean;\n readonly index: boolean;\n declare readonly name?: string;\n declare readonly onDelete?: ReferentialAction;\n declare readonly onUpdate?: ReferentialAction;\n\n constructor(input: ForeignKeyInput) {\n super();\n this.columns = input.columns;\n this.references =\n input.references instanceof ForeignKeyReferences\n ? input.references\n : new ForeignKeyReferences(input.references);\n this.constraint = input.constraint;\n this.index = input.index;\n if (input.name !== undefined) this.name = input.name;\n if (input.onDelete !== undefined) this.onDelete = input.onDelete;\n if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;\n freezeNode(this);\n }\n}\n","import type { StorageType } from '@prisma-next/framework-components/ir';\n\n/**\n * Discriminator literal for the Postgres-enum variant on the polymorphic\n * `SqlStorage.types` slot.\n *\n * Enums are a target-level concept: Postgres ships native\n * `CREATE TYPE … AS ENUM` while other SQL targets approximate enums via\n * constraints. The literal lives at the SQL family layer because every\n * SQL-family consumer (verifier, planner, lowering, …) needs to\n * discriminate enum-typed slot entries from codec-typed ones. The\n * concrete IR class (`PostgresEnumType`) lives in the target-postgres\n * package and implements this structural contract; cross-domain\n * layering rules forbid the SQL family from importing the concrete\n * target class directly, so the discriminator and structural interface\n * carry the dispatch.\n */\nexport const POSTGRES_ENUM_KIND = 'postgres-enum' as const;\n\n/**\n * Structural contract every Postgres-enum slot entry honours — both\n * the live `PostgresEnumType` IR-class instance and the raw JSON\n * envelope shape that survives `JSON.stringify` round-trips. SQL\n * family-layer dispatch narrows polymorphic `StorageType` slot\n * entries to this shape via `isPostgresEnumStorageEntry`.\n *\n * The `codecBinding` field is accessor-shaped (live class instance) on\n * the IR class and undefined on the raw JSON envelope; consumers that\n * need it must guard for its presence (the JSON path synthesises an\n * equivalent shape from `codecId` + `values`).\n */\nexport interface PostgresEnumStorageEntry extends StorageType {\n readonly kind: typeof POSTGRES_ENUM_KIND;\n readonly name: string;\n readonly nativeType: string;\n readonly values: readonly string[];\n /**\n * Enumerable own property on the persisted JSON envelope; the live\n * IR-class instance carries it too. Family-shared dispatch sites\n * read `codecId` directly rather than going through the IR-class\n * `codecBinding` accessor (which lives on the prototype and isn't\n * present on raw JSON envelopes).\n */\n readonly codecId: string;\n}\n\n/**\n * Narrow a polymorphic `StorageType` entry to the Postgres-enum shape\n * via its enumerable `kind` discriminator. Type guard returns true for\n * both live `PostgresEnumType` instances and raw JSON envelopes.\n */\nexport function isPostgresEnumStorageEntry(value: unknown): value is PostgresEnumStorageEntry {\n if (typeof value !== 'object' || value === null) return false;\n return (value as { kind?: unknown }).kind === POSTGRES_ENUM_KIND;\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface PrimaryKeyInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table's primary-key constraint.\n */\nexport class PrimaryKey extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: PrimaryKeyInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface IndexInput {\n readonly columns: readonly string[];\n readonly name?: string;\n readonly type?: string;\n readonly options?: Record<string, unknown>;\n}\n\n/**\n * SQL Contract IR node for a table-level secondary index.\n *\n * Note that this class shadows the global TypeScript `Index` lib type\n * at the family-shared name; consumer files that need both should\n * alias one (e.g.\n * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).\n */\nexport class Index extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n declare readonly type?: string;\n declare readonly options?: Record<string, unknown>;\n\n constructor(input: IndexInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n if (input.type !== undefined) this.type = input.type;\n if (input.options !== undefined) this.options = input.options;\n freezeNode(this);\n }\n}\n","import {\n freezeNode,\n NamespaceBase,\n UNSPECIFIED_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\n\n/**\n * Family-layer placeholder for the SQL unspecified-namespace singleton.\n *\n * SQL contracts honour the framework `Storage.namespaces` invariant from\n * the moment they appear in the IR. Today `SqlStorage` is family-shared\n * (Postgres + SQLite consume the same class); a per-target namespace\n * concretion (`PostgresSchema.unspecified`, `SqliteUnspecifiedDatabase.instance`)\n * earns its existence when each target's namespace shape lands. Until\n * then the family ships a single placeholder singleton so the JSON\n * envelope and runtime walk are honest at every layer.\n *\n * The `kind` discriminator is installed as a non-enumerable own property\n * so the JSON envelope reads `{ \"id\": \"__unspecified__\" }` — symmetric\n * with the family-level non-enumerable `kind` on `SqlNode` and bounded\n * to the minimum data the framework `Namespace` interface promises.\n *\n * **Freeze-trap warning.** The leaf constructor calls\n * `freezeNode(this)` after installing `kind`. The leaf-class shape\n * works today only because `NamespaceBase` does NOT freeze in its\n * constructor — the `Object.defineProperty(this, 'kind', …)` call after\n * `super()` succeeds because the instance is still mutable at that\n * point. Subclasses that add instance fields will still hit the freeze\n * trap once leaf-class `freezeNode(this)` runs; and if a future\n * framework change lifts the freeze to `NamespaceBase`, even the\n * `defineProperty` here would silently fail. To add subclass instance\n * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each\n * leaf calls explicitly at the end of its own constructor.\n */\nexport class SqlUnspecifiedNamespace extends NamespaceBase {\n static readonly instance: SqlUnspecifiedNamespace = new SqlUnspecifiedNamespace();\n\n readonly id = UNSPECIFIED_NAMESPACE_ID;\n declare readonly kind?: string;\n\n private constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageColumn}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n *\n * `typeParams` and `typeRef` remain mutually exclusive (one or the\n * other, not both); the constructor preserves whichever caller-side\n * choice the input encodes.\n */\nexport interface StorageColumnInput {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n readonly typeParams?: Record<string, unknown>;\n readonly typeRef?: string;\n readonly default?: ColumnDefault;\n}\n\n/**\n * SQL Contract IR node for a single column entry in `StorageTable.columns`.\n *\n * Single concrete family-shared class — every SQL target reads the\n * same column shape today, so there is no per-target subclass. The\n * class type accepts any caller that constructs via\n * `new StorageColumn(input)`; literal construction sites must pass\n * through the constructor or the family-base hydration walker.\n *\n * The column's `name` is not on the class — columns are keyed by name\n * in the parent `StorageTable.columns: Record<string, StorageColumn>`\n * map, so a `name` field would be redundant with the key.\n */\nexport class StorageColumn extends SqlNode {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n declare readonly typeParams?: Record<string, unknown>;\n declare readonly typeRef?: string;\n declare readonly default?: ColumnDefault;\n\n constructor(input: StorageColumnInput) {\n super();\n this.nativeType = input.nativeType;\n this.codecId = input.codecId;\n this.nullable = input.nullable;\n if (input.typeParams !== undefined) this.typeParams = input.typeParams;\n if (input.typeRef !== undefined) this.typeRef = input.typeRef;\n if (input.default !== undefined) this.default = input.default;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface UniqueConstraintInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table-level unique constraint.\n */\nexport class UniqueConstraint extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: UniqueConstraintInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKey, type ForeignKeyInput } from './foreign-key';\nimport { PrimaryKey, type PrimaryKeyInput } from './primary-key';\nimport { Index, type IndexInput } from './sql-index';\nimport { SqlNode } from './sql-node';\nimport { StorageColumn, type StorageColumnInput } from './storage-column';\nimport { UniqueConstraint, type UniqueConstraintInput } from './unique-constraint';\n\nexport interface StorageTableInput {\n readonly columns: Record<string, StorageColumn | StorageColumnInput>;\n readonly primaryKey?: PrimaryKey | PrimaryKeyInput;\n readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>;\n readonly indexes: ReadonlyArray<Index | IndexInput>;\n readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>;\n}\n\n/**\n * SQL Contract IR node for a single table entry in `SqlStorage.tables`.\n *\n * The constructor normalises nested IR-class fields (columns, primary\n * key, uniques, indexes, foreign keys) into the appropriate class\n * instances so downstream walks see a uniform AST regardless of whether\n * the input was a JSON literal or an already-constructed class.\n *\n * The table's `name` is not on the class — tables are keyed by name in\n * the parent `SqlStorage.tables: Record<string, StorageTable>` map.\n * A future namespace-aware milestone will add a `namespaceId` field\n * when namespace-keyed storage lands; today's single-namespace shape\n * needs neither field.\n */\nexport class StorageTable extends SqlNode {\n readonly columns: Readonly<Record<string, StorageColumn>>;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n declare readonly primaryKey?: PrimaryKey;\n\n constructor(input: StorageTableInput) {\n super();\n this.columns = Object.freeze(\n Object.fromEntries(\n Object.entries(input.columns).map(([name, col]) => [\n name,\n col instanceof StorageColumn ? col : new StorageColumn(col),\n ]),\n ),\n );\n if (input.primaryKey !== undefined) {\n this.primaryKey =\n input.primaryKey instanceof PrimaryKey\n ? input.primaryKey\n : new PrimaryKey(input.primaryKey);\n }\n this.uniques = Object.freeze(\n input.uniques.map((u) => (u instanceof UniqueConstraint ? u : new UniqueConstraint(u))),\n );\n this.indexes = Object.freeze(input.indexes.map((i) => (i instanceof Index ? i : new Index(i))));\n this.foreignKeys = Object.freeze(\n input.foreignKeys.map((fk) => (fk instanceof ForeignKey ? fk : new ForeignKey(fk))),\n );\n freezeNode(this);\n }\n}\n","import type { StorageType } from '@prisma-next/framework-components/ir';\n\n/**\n * Sentinel kind for the legacy codec-triple shape persisted under\n * `SqlStorage.types`. Plain JSON-clean object literals carry this\n * discriminator so the polymorphic slot dispatch can route them down\n * the codec path while target-specific IR class instances (e.g. the\n * Postgres enum class) keep their own narrower `kind` literal.\n */\nexport const CODEC_INSTANCE_KIND = 'codec-instance' as const;\n\n/**\n * Structural sub-interface of {@link StorageType} for codec-typed entries\n * in `SqlStorage.types`. These are plain object literals — there is no\n * runtime IR class, the JSON envelope round-trips through the slot\n * unchanged. The `kind: 'codec-instance'` discriminator is the dispatch\n * key that distinguishes codec-typed entries from class-instance entries\n * (e.g. `PostgresEnumType`) sharing the polymorphic slot.\n */\nexport interface StorageTypeInstance extends StorageType {\n readonly kind: typeof CODEC_INSTANCE_KIND;\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n}\n\n/**\n * Construction-time input for a codec-triple entry. Symmetric with the\n * structural runtime shape minus the `kind` discriminator — callers may\n * omit `kind`; the helper {@link toStorageTypeInstance} stamps it on.\n */\nexport interface StorageTypeInstanceInput {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n}\n\n/**\n * Stamp the codec-instance `kind` discriminator on a caller-supplied\n * codec triple. Idempotent: input that already carries the discriminator\n * passes through unchanged.\n */\nexport function toStorageTypeInstance(input: StorageTypeInstanceInput): StorageTypeInstance {\n return {\n kind: CODEC_INSTANCE_KIND,\n codecId: input.codecId,\n nativeType: input.nativeType,\n typeParams: input.typeParams,\n };\n}\n\n/**\n * Type-guard for codec-typed entries on the polymorphic\n * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from\n * class-instance kinds (e.g. `PostgresEnumType`).\n */\nexport function isStorageTypeInstance(value: unknown): value is StorageTypeInstance {\n if (typeof value !== 'object' || value === null) return false;\n return (value as { kind?: unknown }).kind === CODEC_INSTANCE_KIND;\n}\n","import type { StorageHashBase } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n type Namespace,\n type Storage,\n UNSPECIFIED_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n} from './postgres-enum-storage-entry';\nimport { SqlNode } from './sql-node';\nimport { SqlUnspecifiedNamespace } from './sql-unspecified-namespace';\nimport { StorageTable, type StorageTableInput } from './storage-table';\nimport {\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n toStorageTypeInstance,\n} from './storage-type-instance';\n\n/**\n * Polymorphic value type for `SqlStorage.types` entries (Decision 18,\n * Option B). The slot's framework alphabet is `StorageType` — codec\n * triples (`StorageTypeInstance` with `kind: 'codec-instance'`) and\n * target-specific IR class instances structurally satisfying\n * `PostgresEnumStorageEntry` (with `kind: 'postgres-enum'`) are the\n * two variants the SQL family ships today. The construction side also\n * accepts {@link StorageTypeInstanceInput} so callers can pass raw\n * codec triples; the constructor stamps the discriminator.\n */\nexport type SqlStorageTypeEntry =\n | StorageTypeInstance\n | PostgresEnumStorageEntry\n | StorageTypeInstanceInput;\n\nconst DEFAULT_NAMESPACES: Readonly<Record<string, Namespace>> = Object.freeze({\n [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance,\n});\n\nexport interface SqlStorageInput<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n readonly tables: Record<string, StorageTable | StorageTableInput>;\n readonly types?: Record<string, SqlStorageTypeEntry>;\n readonly namespaces?: Readonly<Record<string, Namespace>>;\n}\n\n/**\n * SQL Contract IR root node for the `storage` field.\n *\n * Single concrete family-shared class — both Postgres and SQLite\n * consume this same class today. Per-target storage subclasses are\n * introduced when each target's namespace shape earns its\n * target-specific concretion (target-specific derived fields,\n * target-specific storage extensions).\n *\n * Honours the framework `Storage` interface: every SQL IR carries a\n * `namespaces` map keyed by namespace id. The default singleton\n * (`{ [UNSPECIFIED_NAMESPACE_ID]: SqlUnspecifiedNamespace.instance }`)\n * binds every contract authored before per-target namespace concretions\n * land; per-target namespace classes (`PostgresSchema.unspecified`,\n * `SqliteUnspecifiedDatabase.instance`) earn their slots when each\n * target's namespace shape lands.\n *\n * The constructor normalises nested IR-class fields (`tables`, optional\n * `types`) into class instances so downstream walks see a uniform AST.\n * `types` is polymorphic per Decision 18 Option B: codec-triple inputs\n * are stamped with `kind: 'codec-instance'`; class-instance kinds\n * (e.g. Postgres-enum entries satisfying `PostgresEnumStorageEntry`)\n * pass through; hydration of raw JSON class-instance entries (carrying\n * their narrower `kind` literal) is the per-target serializer's\n * responsibility (so the family base does not import target-specific\n * subclasses).\n */\nexport class SqlStorage<THash extends string = string> extends SqlNode implements Storage {\n readonly storageHash: StorageHashBase<THash>;\n readonly tables: Readonly<Record<string, StorageTable>>;\n readonly namespaces: Readonly<Record<string, Namespace>>;\n // SQL-family slot view: the two structural variants the family ships\n // today (codec triples + Postgres-enum structural entries). Each\n // variant extends the framework `StorageType` alphabet; the SQL\n // narrowing keeps cross-domain layering clean — SQL-family consumers\n // dispatch via `isStorageTypeInstance` / `isPostgresEnumStorageEntry`\n // type guards rather than importing the target's concrete IR class\n // (cross-domain rule: SQL may not import `target-*`).\n declare readonly types?: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n\n constructor(input: SqlStorageInput<THash>) {\n super();\n this.storageHash = input.storageHash;\n this.tables = Object.freeze(\n Object.fromEntries(\n Object.entries(input.tables).map(([name, t]) => [\n name,\n t instanceof StorageTable ? t : new StorageTable(t),\n ]),\n ),\n );\n this.namespaces = input.namespaces ?? DEFAULT_NAMESPACES;\n if (input.types !== undefined) {\n this.types = Object.freeze(\n Object.fromEntries(\n Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(ti)]),\n ),\n );\n }\n freezeNode(this);\n }\n}\n\nfunction normaliseTypeEntry(\n entry: SqlStorageTypeEntry,\n): StorageTypeInstance | PostgresEnumStorageEntry {\n if (isPostgresEnumStorageEntry(entry)) {\n // Live class instances pass through unchanged; raw JSON envelopes\n // (e.g. `kind: 'postgres-enum'` without the class identity) are\n // rejected so the target serializer's hydration path is the only\n // way IR class instances enter the slot.\n if (entry instanceof SqlNode) {\n return entry;\n }\n throw new Error(\n 'Encountered raw postgres-enum JSON in storage.types without serializer hydration; use a target ContractSerializer that registers the matching entity-type factory.',\n );\n }\n if (isStorageTypeInstance(entry)) {\n return entry;\n }\n return toStorageTypeInstance(entry as StorageTypeInstanceInput);\n}\n","import type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { ReferentialAction } from './ir/foreign-key';\n\nexport {\n ForeignKey,\n type ForeignKeyInput,\n type ReferentialAction,\n} from './ir/foreign-key';\nexport {\n ForeignKeyReferences,\n type ForeignKeyReferencesInput,\n} from './ir/foreign-key-references';\nexport {\n isPostgresEnumStorageEntry,\n POSTGRES_ENUM_KIND,\n type PostgresEnumStorageEntry,\n} from './ir/postgres-enum-storage-entry';\nexport { PrimaryKey, type PrimaryKeyInput } from './ir/primary-key';\nexport { Index, type IndexInput } from './ir/sql-index';\nexport { SqlNode } from './ir/sql-node';\nexport {\n SqlStorage,\n type SqlStorageInput,\n type SqlStorageTypeEntry,\n} from './ir/sql-storage';\nexport { SqlUnspecifiedNamespace } from './ir/sql-unspecified-namespace';\nexport { StorageColumn, type StorageColumnInput } from './ir/storage-column';\nexport { StorageTable, type StorageTableInput } from './ir/storage-table';\nexport {\n CODEC_INSTANCE_KIND,\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n toStorageTypeInstance,\n} from './ir/storage-type-instance';\nexport {\n UniqueConstraint,\n type UniqueConstraintInput,\n} from './ir/unique-constraint';\n\nexport type ForeignKeyOptions = {\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\nexport type SqlModelFieldStorage = {\n readonly column: string;\n readonly codecId?: string;\n readonly nullable?: boolean;\n};\n\nexport type SqlModelStorage = {\n readonly table: string;\n readonly fields: Record<string, SqlModelFieldStorage>;\n};\n\nexport const DEFAULT_FK_CONSTRAINT = true;\nexport const DEFAULT_FK_INDEX = true;\n\nexport function applyFkDefaults(\n fk: { constraint?: boolean | undefined; index?: boolean | undefined },\n overrideDefaults?: { constraint?: boolean | undefined; index?: boolean | undefined },\n): { constraint: boolean; index: boolean } {\n return {\n constraint: fk.constraint ?? overrideDefaults?.constraint ?? DEFAULT_FK_CONSTRAINT,\n index: fk.index ?? overrideDefaults?.index ?? DEFAULT_FK_INDEX,\n };\n}\n\nexport type TypeMaps<\n TCodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n TQueryOperationTypes extends Record<string, unknown> = Record<string, never>,\n TFieldOutputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,\n TFieldInputTypes extends Record<string, Record<string, unknown>> = Record<string, never>,\n> = {\n readonly codecTypes: TCodecTypes;\n readonly queryOperationTypes: TQueryOperationTypes;\n readonly fieldOutputTypes: TFieldOutputTypes;\n readonly fieldInputTypes: TFieldInputTypes;\n};\n\nexport type CodecTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly codecTypes: infer C }\n ? C extends Record<string, { output: unknown }>\n ? C\n : Record<string, never>\n : Record<string, never>;\n\n/**\n * Dispatch hint identifying the first-argument target of an operation.\n *\n * Used by ORM column helpers to decide whether an operation is reachable on a\n * field. Either names a concrete codec identity or a set of capability traits\n * that the field's codec must carry.\n */\nexport type QueryOperationSelfSpec =\n | { readonly codecId: string; readonly traits?: never }\n | { readonly traits: readonly CodecTrait[]; readonly codecId?: never };\n\n/**\n * Structural shape an operation's impl must return: any value carrying a\n * codec-exact `returnType` descriptor. `Expression<T>` (from\n * `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`)\n * extends this. Trait-targeted returns are deliberately excluded — predicate\n * detection and result decoding both depend on knowing the concrete return\n * codec.\n */\nexport type QueryOperationReturn = {\n readonly returnType: { readonly codecId: string; readonly nullable: boolean };\n};\n\nexport type QueryOperationTypeEntry = {\n readonly self?: QueryOperationSelfSpec;\n readonly impl: (...args: never[]) => QueryOperationReturn;\n};\n\nexport type SqlQueryOperationTypes<\n _CT extends Record<string, { readonly input: unknown; readonly output: unknown }>,\n T extends Record<string, QueryOperationTypeEntry>,\n> = T;\n\nexport type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>;\n\nexport type QueryOperationTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly queryOperationTypes: infer Q }\n ? Q extends Record<string, unknown>\n ? Q\n : Record<string, never>\n : Record<string, never>;\n\nexport type TypeMapsPhantomKey = '__@prisma-next/sql-contract/typeMaps@__';\n\nexport type ContractWithTypeMaps<TContract, TTypeMaps> = TContract & {\n readonly [K in TypeMapsPhantomKey]?: TTypeMaps;\n};\n\nexport type ExtractTypeMapsFromContract<T> = TypeMapsPhantomKey extends keyof T\n ? NonNullable<T[TypeMapsPhantomKey & keyof T]>\n : never;\n\nexport type FieldOutputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly fieldOutputTypes: infer F }\n ? F extends Record<string, Record<string, unknown>>\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type FieldInputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly fieldInputTypes: infer F }\n ? F extends Record<string, Record<string, unknown>>\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldOutputTypes<T> = FieldOutputTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>;\n\nexport type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never]\n ? ExtractCodecTypes<TContract>\n : CodecTypesOf<TTypeMaps>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAsB,UAAtB,cAAsC,WAAW;CAC/C;CAEA,cAAc;EACZ,OAAO;EACP,OAAO,eAAe,MAAM,QAAQ;GAClC,OAAO;GACP,UAAU;GACV,YAAY;GAMZ,cAAc;GACf,CAAC;;;;;;;;;;;;AClCN,IAAa,uBAAb,cAA0C,QAAQ;CAChD;CACA;CAEA,YAAY,OAAkC;EAC5C,OAAO;EACP,KAAK,QAAQ,MAAM;EACnB,KAAK,UAAU,MAAM;EACrB,WAAW,KAAK;;;;;;;;;;;;;ACGpB,IAAa,aAAb,cAAgC,QAAQ;CACtC;CACA;CACA;CACA;CAKA,YAAY,OAAwB;EAClC,OAAO;EACP,KAAK,UAAU,MAAM;EACrB,KAAK,aACH,MAAM,sBAAsB,uBACxB,MAAM,aACN,IAAI,qBAAqB,MAAM,WAAW;EAChD,K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