@prisma-next/sql-contract 0.3.0-dev.34 → 0.3.0-dev.35

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.
Files changed (54) hide show
  1. package/README.md +24 -8
  2. package/dist/factories.d.mts +45 -0
  3. package/dist/factories.d.mts.map +1 -0
  4. package/dist/factories.mjs +76 -0
  5. package/dist/factories.mjs.map +1 -0
  6. package/dist/pack-types.d.mts +13 -0
  7. package/dist/pack-types.d.mts.map +1 -0
  8. package/dist/pack-types.mjs +1 -0
  9. package/dist/types-D3AOQgwo.d.mts +117 -0
  10. package/dist/types-D3AOQgwo.d.mts.map +1 -0
  11. package/dist/types.d.mts +2 -0
  12. package/dist/types.mjs +1 -0
  13. package/dist/validate.d.mts +7 -0
  14. package/dist/validate.d.mts.map +1 -0
  15. package/dist/validate.mjs +171 -0
  16. package/dist/validate.mjs.map +1 -0
  17. package/dist/validators-DY_87pfS.mjs +160 -0
  18. package/dist/validators-DY_87pfS.mjs.map +1 -0
  19. package/dist/{validators.d.ts → validators.d.mts} +21 -5
  20. package/dist/validators.d.mts.map +1 -0
  21. package/dist/validators.mjs +3 -0
  22. package/package.json +19 -22
  23. package/src/exports/validate.ts +1 -0
  24. package/src/exports/validators.ts +1 -1
  25. package/src/factories.ts +33 -6
  26. package/src/index.ts +1 -0
  27. package/src/types.ts +18 -2
  28. package/src/validate.ts +324 -0
  29. package/src/validators.ts +60 -17
  30. package/dist/exports/factories.d.ts +0 -2
  31. package/dist/exports/factories.d.ts.map +0 -1
  32. package/dist/exports/factories.js +0 -83
  33. package/dist/exports/factories.js.map +0 -1
  34. package/dist/exports/pack-types.d.ts +0 -2
  35. package/dist/exports/pack-types.d.ts.map +0 -1
  36. package/dist/exports/pack-types.js +0 -1
  37. package/dist/exports/pack-types.js.map +0 -1
  38. package/dist/exports/types.d.ts +0 -2
  39. package/dist/exports/types.d.ts.map +0 -1
  40. package/dist/exports/types.js +0 -1
  41. package/dist/exports/types.js.map +0 -1
  42. package/dist/exports/validators.d.ts +0 -2
  43. package/dist/exports/validators.d.ts.map +0 -1
  44. package/dist/exports/validators.js +0 -109
  45. package/dist/exports/validators.js.map +0 -1
  46. package/dist/factories.d.ts +0 -38
  47. package/dist/factories.d.ts.map +0 -1
  48. package/dist/index.d.ts +0 -4
  49. package/dist/index.d.ts.map +0 -1
  50. package/dist/pack-types.d.ts +0 -10
  51. package/dist/pack-types.d.ts.map +0 -1
  52. package/dist/types.d.ts +0 -106
  53. package/dist/types.d.ts.map +0 -1
  54. package/dist/validators.d.ts.map +0 -1
package/README.md CHANGED
@@ -9,7 +9,7 @@ This package provides TypeScript type definitions, Arktype validators, and facto
9
9
  ## Responsibilities
10
10
 
11
11
  - **SQL Contract Types**: Defines SQL-specific contract types (`SqlContract`, `SqlStorage`, `StorageTable`, `ModelDefinition`, `SqlMappings`) that extend framework-level contract types
12
- - **Contract Validation**: Provides Arktype-based validators for structural validation of SQL contracts, storage, and models
12
+ - **Contract Validation**: Provides Arktype-based structural validators and the shared `validateContract` entrypoint for runtime-safe contract validation
13
13
  - **IR Factories**: Provides pure factory functions for constructing contract IR structures in tests and authoring
14
14
  - **Shared Plane Access**: Enables both migration-plane and runtime-plane packages to import SQL contract types without violating plane boundaries
15
15
 
@@ -19,6 +19,7 @@ Each `StorageColumn` in SQL contracts includes both:
19
19
  - **`nativeType`** (required): Native database type identifier (e.g., `'int4'`, `'text'`, `'vector'`) - used for database structure verification and migration planning
20
20
  - **`codecId`** (required): Codec identifier (e.g., `'pg/int4@1'`, `'pg/text@1'`, `'pg/vector@1'`) - used for query builders and runtime codecs
21
21
  - **`nullable`** (required): Whether the column is nullable
22
+ - **`default`** (optional): Uses the shared `ColumnDefault` type from `@prisma-next/contract` for db-agnostic defaults (literal or function). Client-generated defaults live in `execution.mutations.defaults`.
22
23
 
23
24
  Both `nativeType` and `codecId` are required to ensure contracts are consumable by both the application (via codec IDs) and the database (via native types). See `docs/briefs/Sql-Contract-Native-and-Codec-Types.md` for details.
24
25
 
@@ -40,7 +41,7 @@ import type {
40
41
  SqlStorage,
41
42
  StorageTable,
42
43
  ModelDefinition,
43
- } from '@prisma-next/sql-contract/exports/types';
44
+ } from '@prisma-next/sql-contract/types';
44
45
  ```
45
46
 
46
47
  ### Validators
@@ -48,7 +49,7 @@ import type {
48
49
  Validate contract structures using Arktype validators:
49
50
 
50
51
  ```typescript
51
- import { validateSqlContract, validateStorage, validateModel } from '@prisma-next/sql-contract/exports/validators';
52
+ import { validateSqlContract, validateStorage, validateModel } from '@prisma-next/sql-contract/validators';
52
53
 
53
54
  // Validate a complete contract
54
55
  const contract = validateSqlContract<Contract>(contractJson);
@@ -60,12 +61,25 @@ const storage = validateStorage(storageJson);
60
61
  const model = validateModel(modelJson);
61
62
  ```
62
63
 
64
+ Validate JSON-emitted contracts with mapping + logic checks:
65
+
66
+ ```typescript
67
+ import { validateContract } from '@prisma-next/sql-contract/validate';
68
+
69
+ const contract = validateContract<Contract>(contractJson);
70
+ ```
71
+
72
+ Mapping overrides in `contract.mappings` follow strict pair semantics:
73
+ - `modelToTable` and `tableToModel` must either both be omitted (auto-computed) or both be provided as inverse maps.
74
+ - `fieldToColumn` and `columnToField` must either both be omitted (auto-computed) or both be provided as inverse maps.
75
+ - `codecTypes` and `operationTypes` are merged additively on top of defaults.
76
+
63
77
  ### Factories
64
78
 
65
79
  Use factory functions to construct contract IR structures in tests:
66
80
 
67
81
  ```typescript
68
- import { col, table, storage, model, contract, pk, unique, index, fk } from '@prisma-next/sql-contract/exports/factories';
82
+ import { col, table, storage, model, contract, pk, unique, index, fk } from '@prisma-next/sql-contract/factories';
69
83
 
70
84
  // Create a column (nativeType, codecId, nullable)
71
85
  const idColumn = col('int4', 'pg/int4@1', false);
@@ -95,7 +109,7 @@ const userModel = model('user', {
95
109
  // Create a complete contract
96
110
  const c = contract({
97
111
  target: 'postgres',
98
- coreHash: 'sha256:abc123',
112
+ storageHash: 'sha256:abc123',
99
113
  storage: s,
100
114
  models: { User: userModel },
101
115
  });
@@ -103,9 +117,11 @@ const c = contract({
103
117
 
104
118
  ## Exports
105
119
 
106
- - `./exports/types`: TypeScript type definitions
107
- - `./exports/validators`: Arktype validators for structural validation
108
- - `./exports/factories`: Factory functions for constructing contract IR
120
+ - `./types`: TypeScript type definitions
121
+ - `./validators`: Arktype validators for structural validation
122
+ - `./validate`: Shared `validateContract` helper for JSON imports
123
+ - `./factories`: Factory functions for constructing contract IR
124
+ - `./pack-types`: Shared extension/pack typing helpers
109
125
 
110
126
  ## Architecture
111
127
 
@@ -0,0 +1,45 @@
1
+ import { a as Index, d as SqlMappings, f as SqlStorage, g as UniqueConstraint, l as PrimaryKey, m as StorageTable, o as ModelDefinition, p as StorageColumn, r as ForeignKey, s as ModelField, u as SqlContract } from "./types-D3AOQgwo.mjs";
2
+ import { ExecutionHashBase, ProfileHashBase, StorageHashBase } from "@prisma-next/contract/types";
3
+
4
+ //#region src/factories.d.ts
5
+
6
+ /**
7
+ * Creates a StorageColumn with nativeType and codecId.
8
+ *
9
+ * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')
10
+ * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')
11
+ * @param nullable - Whether the column is nullable (default: false)
12
+ * @returns StorageColumn with nativeType and codecId
13
+ */
14
+ declare function col(nativeType: string, codecId: string, nullable?: boolean): StorageColumn;
15
+ declare function pk(...columns: readonly string[]): PrimaryKey;
16
+ declare function unique(...columns: readonly string[]): UniqueConstraint;
17
+ declare function index(...columns: readonly string[]): Index;
18
+ declare function fk(columns: readonly string[], refTable: string, refColumns: readonly string[], name?: string): ForeignKey;
19
+ declare function table(columns: Record<string, StorageColumn>, opts?: {
20
+ pk?: PrimaryKey;
21
+ uniques?: readonly UniqueConstraint[];
22
+ indexes?: readonly Index[];
23
+ fks?: readonly ForeignKey[];
24
+ }): StorageTable;
25
+ declare function model(table: string, fields: Record<string, ModelField>, relations?: Record<string, unknown>): ModelDefinition;
26
+ declare function storage(tables: Record<string, StorageTable>): SqlStorage;
27
+ declare function contract<TStorageHash extends StorageHashBase<string> = StorageHashBase<string>, TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>, TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>>(opts: {
28
+ target: string;
29
+ storageHash: TStorageHash;
30
+ executionHash?: TExecutionHash;
31
+ storage: SqlStorage;
32
+ models?: Record<string, ModelDefinition>;
33
+ relations?: Record<string, unknown>;
34
+ mappings?: Partial<SqlMappings>;
35
+ schemaVersion?: '1';
36
+ targetFamily?: 'sql';
37
+ profileHash?: TProfileHash;
38
+ capabilities?: Record<string, Record<string, boolean>>;
39
+ extensionPacks?: Record<string, unknown>;
40
+ meta?: Record<string, unknown>;
41
+ sources?: Record<string, unknown>;
42
+ }): SqlContract<SqlStorage, Record<string, unknown>, Record<string, unknown>, SqlMappings, TStorageHash, TExecutionHash, TProfileHash>;
43
+ //#endregion
44
+ export { col, contract, fk, index, model, pk, storage, table, unique };
45
+ //# sourceMappingURL=factories.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factories.d.mts","names":[],"sources":["../src/factories.ts"],"sourcesContent":[],"mappings":";;;;;;;AA6BA;AAQA;AAMA;AAMA;AAMA;AAiBA;AAC0B,iBA5CV,GAAA,CA4CU,UAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EA5CkD,aA4ClD;AAAf,iBApCK,EAAA,CAoCL,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EApCwC,UAoCxC;AAEF,iBAhCO,MAAA,CAgCP,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EAhC8C,gBAgC9C;AACc,iBA3BP,KAAA,CA2BO,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EA3B+B,KA2B/B;AACA,iBAtBP,EAAA,CAsBO,OAAA,EAAA,SAAA,MAAA,EAAA,EAAA,QAAA,EAAA,MAA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A;EAA4B,WAAA,CAAA,EAYrC,YAZqC;EAC9B,YAAA,CAAA,EAYN,MAZM,CAAA,MAAA,EAYS,MAZT,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA;EAA0B,cAAA,CAAA,EAa9B,MAb8B,CAAA,MAAA,EAAA,OAAA,CAAA;EAGlC,IAAA,CAAA,EAWN,MAXM,CAAA,MAAA,EAAA,OAAA,CAAA;EACG,OAAA,CAAA,EAWN,MAXM,CAAA,MAAA,EAAA,OAAA,CAAA;CACP,CAAA,EAWP,WAXO,CAYT,UAZS,EAaT,MAbS,CAAA,MAAA,EAAA,OAAA,CAAA,EAcT,MAdS,CAAA,MAAA,EAAA,OAAA,CAAA,EAeT,WAfS,EAgBT,YAhBS,EAiBT,cAjBS,EAkBT,YAlBS,CAAA"}
@@ -0,0 +1,76 @@
1
+ //#region src/factories.ts
2
+ /**
3
+ * Creates a StorageColumn with nativeType and codecId.
4
+ *
5
+ * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')
6
+ * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')
7
+ * @param nullable - Whether the column is nullable (default: false)
8
+ * @returns StorageColumn with nativeType and codecId
9
+ */
10
+ function col(nativeType, codecId, nullable = false) {
11
+ return {
12
+ nativeType,
13
+ codecId,
14
+ nullable
15
+ };
16
+ }
17
+ function pk(...columns) {
18
+ return { columns };
19
+ }
20
+ function unique(...columns) {
21
+ return { columns };
22
+ }
23
+ function index(...columns) {
24
+ return { columns };
25
+ }
26
+ function fk(columns, refTable, refColumns, name) {
27
+ return {
28
+ columns,
29
+ references: {
30
+ table: refTable,
31
+ columns: refColumns
32
+ },
33
+ ...name !== void 0 && { name }
34
+ };
35
+ }
36
+ function table(columns, opts) {
37
+ return {
38
+ columns,
39
+ ...opts?.pk !== void 0 && { primaryKey: opts.pk },
40
+ uniques: opts?.uniques ?? [],
41
+ indexes: opts?.indexes ?? [],
42
+ foreignKeys: opts?.fks ?? []
43
+ };
44
+ }
45
+ function model(table$1, fields, relations = {}) {
46
+ return {
47
+ storage: { table: table$1 },
48
+ fields,
49
+ relations
50
+ };
51
+ }
52
+ function storage(tables) {
53
+ return { tables };
54
+ }
55
+ function contract(opts) {
56
+ return {
57
+ schemaVersion: opts.schemaVersion ?? "1",
58
+ target: opts.target,
59
+ targetFamily: opts.targetFamily ?? "sql",
60
+ storageHash: opts.storageHash,
61
+ ...opts.executionHash !== void 0 && { executionHash: opts.executionHash },
62
+ storage: opts.storage,
63
+ models: opts.models ?? {},
64
+ relations: opts.relations ?? {},
65
+ mappings: opts.mappings ?? {},
66
+ ...opts.profileHash !== void 0 && { profileHash: opts.profileHash },
67
+ ...opts.capabilities !== void 0 && { capabilities: opts.capabilities },
68
+ ...opts.extensionPacks !== void 0 && { extensionPacks: opts.extensionPacks },
69
+ ...opts.meta !== void 0 && { meta: opts.meta },
70
+ ...opts.sources !== void 0 && { sources: opts.sources }
71
+ };
72
+ }
73
+
74
+ //#endregion
75
+ export { col, contract, fk, index, model, pk, storage, table, unique };
76
+ //# sourceMappingURL=factories.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factories.mjs","names":[],"sources":["../src/factories.ts"],"sourcesContent":["import type {\n ExecutionHashBase,\n ProfileHashBase,\n StorageHashBase,\n} from '@prisma-next/contract/types';\nimport type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from './types';\n\n/**\n * Creates a StorageColumn with nativeType and codecId.\n *\n * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')\n * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')\n * @param nullable - Whether the column is nullable (default: false)\n * @returns StorageColumn with nativeType and codecId\n */\nexport function col(nativeType: string, codecId: string, nullable = false): StorageColumn {\n return {\n nativeType,\n codecId,\n nullable,\n };\n}\n\nexport function pk(...columns: readonly string[]): PrimaryKey {\n return {\n columns,\n };\n}\n\nexport function unique(...columns: readonly string[]): UniqueConstraint {\n return {\n columns,\n };\n}\n\nexport function index(...columns: readonly string[]): Index {\n return {\n columns,\n };\n}\n\nexport function fk(\n columns: readonly string[],\n refTable: string,\n refColumns: readonly string[],\n name?: string,\n): ForeignKey {\n const references: ForeignKeyReferences = {\n table: refTable,\n columns: refColumns,\n };\n return {\n columns,\n references,\n ...(name !== undefined && { name }),\n };\n}\n\nexport function table(\n columns: Record<string, StorageColumn>,\n opts?: {\n pk?: PrimaryKey;\n uniques?: readonly UniqueConstraint[];\n indexes?: readonly Index[];\n fks?: readonly ForeignKey[];\n },\n): StorageTable {\n return {\n columns,\n ...(opts?.pk !== undefined && { primaryKey: opts.pk }),\n uniques: opts?.uniques ?? [],\n indexes: opts?.indexes ?? [],\n foreignKeys: opts?.fks ?? [],\n };\n}\n\nexport function model(\n table: string,\n fields: Record<string, ModelField>,\n relations: Record<string, unknown> = {},\n): ModelDefinition {\n const storage: ModelStorage = { table };\n return {\n storage,\n fields,\n relations,\n };\n}\n\nexport function storage(tables: Record<string, StorageTable>): SqlStorage {\n return { tables };\n}\n\nexport function contract<\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n>(opts: {\n target: string;\n storageHash: TStorageHash;\n executionHash?: TExecutionHash;\n storage: SqlStorage;\n models?: Record<string, ModelDefinition>;\n relations?: Record<string, unknown>;\n mappings?: Partial<SqlMappings>;\n schemaVersion?: '1';\n targetFamily?: 'sql';\n profileHash?: TProfileHash;\n capabilities?: Record<string, Record<string, boolean>>;\n extensionPacks?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n sources?: Record<string, unknown>;\n}): SqlContract<\n SqlStorage,\n Record<string, unknown>,\n Record<string, unknown>,\n SqlMappings,\n TStorageHash,\n TExecutionHash,\n TProfileHash\n> {\n return {\n schemaVersion: opts.schemaVersion ?? '1',\n target: opts.target,\n targetFamily: opts.targetFamily ?? 'sql',\n storageHash: opts.storageHash,\n ...(opts.executionHash !== undefined && { executionHash: opts.executionHash }),\n storage: opts.storage,\n models: opts.models ?? {},\n relations: opts.relations ?? {},\n mappings: (opts.mappings ?? {}) as SqlMappings,\n ...(opts.profileHash !== undefined && { profileHash: opts.profileHash }),\n ...(opts.capabilities !== undefined && { capabilities: opts.capabilities }),\n ...(opts.extensionPacks !== undefined && { extensionPacks: opts.extensionPacks }),\n ...(opts.meta !== undefined && { meta: opts.meta }),\n ...(opts.sources !== undefined && { sources: opts.sources as Record<string, unknown> }),\n } as SqlContract<\n SqlStorage,\n Record<string, unknown>,\n Record<string, unknown>,\n SqlMappings,\n TStorageHash,\n TExecutionHash,\n TProfileHash\n >;\n}\n"],"mappings":";;;;;;;;;AA6BA,SAAgB,IAAI,YAAoB,SAAiB,WAAW,OAAsB;AACxF,QAAO;EACL;EACA;EACA;EACD;;AAGH,SAAgB,GAAG,GAAG,SAAwC;AAC5D,QAAO,EACL,SACD;;AAGH,SAAgB,OAAO,GAAG,SAA8C;AACtE,QAAO,EACL,SACD;;AAGH,SAAgB,MAAM,GAAG,SAAmC;AAC1D,QAAO,EACL,SACD;;AAGH,SAAgB,GACd,SACA,UACA,YACA,MACY;AAKZ,QAAO;EACL;EACA,YANuC;GACvC,OAAO;GACP,SAAS;GACV;EAIC,GAAI,SAAS,UAAa,EAAE,MAAM;EACnC;;AAGH,SAAgB,MACd,SACA,MAMc;AACd,QAAO;EACL;EACA,GAAI,MAAM,OAAO,UAAa,EAAE,YAAY,KAAK,IAAI;EACrD,SAAS,MAAM,WAAW,EAAE;EAC5B,SAAS,MAAM,WAAW,EAAE;EAC5B,aAAa,MAAM,OAAO,EAAE;EAC7B;;AAGH,SAAgB,MACd,SACA,QACA,YAAqC,EAAE,EACtB;AAEjB,QAAO;EACL,SAF4B,EAAE,gBAAO;EAGrC;EACA;EACD;;AAGH,SAAgB,QAAQ,QAAkD;AACxE,QAAO,EAAE,QAAQ;;AAGnB,SAAgB,SAId,MAuBA;AACA,QAAO;EACL,eAAe,KAAK,iBAAiB;EACrC,QAAQ,KAAK;EACb,cAAc,KAAK,gBAAgB;EACnC,aAAa,KAAK;EAClB,GAAI,KAAK,kBAAkB,UAAa,EAAE,eAAe,KAAK,eAAe;EAC7E,SAAS,KAAK;EACd,QAAQ,KAAK,UAAU,EAAE;EACzB,WAAW,KAAK,aAAa,EAAE;EAC/B,UAAW,KAAK,YAAY,EAAE;EAC9B,GAAI,KAAK,gBAAgB,UAAa,EAAE,aAAa,KAAK,aAAa;EACvE,GAAI,KAAK,iBAAiB,UAAa,EAAE,cAAc,KAAK,cAAc;EAC1E,GAAI,KAAK,mBAAmB,UAAa,EAAE,gBAAgB,KAAK,gBAAgB;EAChF,GAAI,KAAK,SAAS,UAAa,EAAE,MAAM,KAAK,MAAM;EAClD,GAAI,KAAK,YAAY,UAAa,EAAE,SAAS,KAAK,SAAoC;EACvF"}
@@ -0,0 +1,13 @@
1
+ //#region src/pack-types.d.ts
2
+ /**
3
+ * Storage type metadata for pack refs.
4
+ */
5
+ interface StorageTypeMetadata {
6
+ readonly typeId: string;
7
+ readonly familyId: string;
8
+ readonly targetId: string;
9
+ readonly nativeType?: string;
10
+ }
11
+ //#endregion
12
+ export { type StorageTypeMetadata };
13
+ //# sourceMappingURL=pack-types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pack-types.d.mts","names":[],"sources":["../src/pack-types.ts"],"sourcesContent":[],"mappings":";;AAGA;;UAAiB,mBAAA"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,117 @@
1
+ import { ColumnDefault, ContractBase, ExecutionHashBase, ExecutionSection, ProfileHashBase, StorageHashBase } from "@prisma-next/contract/types";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * A column definition in storage.
7
+ *
8
+ * `typeParams` is optional because most columns use non-parameterized types.
9
+ * Columns with parameterized types can either inline `typeParams` or reference
10
+ * a named {@link StorageTypeInstance} via `typeRef`.
11
+ */
12
+ type StorageColumn = {
13
+ readonly nativeType: string;
14
+ readonly codecId: string;
15
+ readonly nullable: boolean;
16
+ /**
17
+ * Opaque, codec-owned JS/type parameters.
18
+ * The codec that owns `codecId` defines the shape and semantics.
19
+ * Mutually exclusive with `typeRef`.
20
+ */
21
+ readonly typeParams?: Record<string, unknown>;
22
+ /**
23
+ * Reference to a named type instance in `storage.types`.
24
+ * Mutually exclusive with `typeParams`.
25
+ */
26
+ readonly typeRef?: string;
27
+ /**
28
+ * Default value for the column.
29
+ * Can be a literal value or database function.
30
+ */
31
+ readonly default?: ColumnDefault;
32
+ };
33
+ type PrimaryKey = {
34
+ readonly columns: readonly string[];
35
+ readonly name?: string;
36
+ };
37
+ type UniqueConstraint = {
38
+ readonly columns: readonly string[];
39
+ readonly name?: string;
40
+ };
41
+ type Index = {
42
+ readonly columns: readonly string[];
43
+ readonly name?: string;
44
+ };
45
+ type ForeignKeyReferences = {
46
+ readonly table: string;
47
+ readonly columns: readonly string[];
48
+ };
49
+ type ForeignKey = {
50
+ readonly columns: readonly string[];
51
+ readonly references: ForeignKeyReferences;
52
+ readonly name?: string;
53
+ };
54
+ type StorageTable = {
55
+ readonly columns: Record<string, StorageColumn>;
56
+ readonly primaryKey?: PrimaryKey;
57
+ readonly uniques: ReadonlyArray<UniqueConstraint>;
58
+ readonly indexes: ReadonlyArray<Index>;
59
+ readonly foreignKeys: ReadonlyArray<ForeignKey>;
60
+ };
61
+ /**
62
+ * A named, parameterized type instance.
63
+ * These are registered in `storage.types` for reuse across columns
64
+ * and to enable ergonomic schema surfaces like `schema.types.MyType`.
65
+ *
66
+ * Unlike {@link StorageColumn}, `typeParams` is required here because
67
+ * `StorageTypeInstance` exists specifically to define reusable parameterized types.
68
+ * A type instance without parameters would be redundant—columns can reference
69
+ * the codec directly via `codecId`.
70
+ */
71
+ type StorageTypeInstance = {
72
+ readonly codecId: string;
73
+ readonly nativeType: string;
74
+ readonly typeParams: Record<string, unknown>;
75
+ };
76
+ type SqlStorage = {
77
+ readonly tables: Record<string, StorageTable>;
78
+ /**
79
+ * Named type instances for parameterized/custom types.
80
+ * Columns can reference these via `typeRef`.
81
+ */
82
+ readonly types?: Record<string, StorageTypeInstance>;
83
+ };
84
+ type ModelField = {
85
+ readonly column: string;
86
+ };
87
+ type ModelStorage = {
88
+ readonly table: string;
89
+ };
90
+ type ModelDefinition = {
91
+ readonly storage: ModelStorage;
92
+ readonly fields: Record<string, ModelField>;
93
+ readonly relations: Record<string, unknown>;
94
+ };
95
+ type SqlMappings = {
96
+ readonly modelToTable?: Record<string, string>;
97
+ readonly tableToModel?: Record<string, string>;
98
+ readonly fieldToColumn?: Record<string, Record<string, string>>;
99
+ readonly columnToField?: Record<string, Record<string, string>>;
100
+ readonly codecTypes: Record<string, {
101
+ readonly output: unknown;
102
+ }>;
103
+ readonly operationTypes: Record<string, Record<string, unknown>>;
104
+ };
105
+ type SqlContract<S extends SqlStorage = SqlStorage, M extends Record<string, unknown> = Record<string, unknown>, R extends Record<string, unknown> = Record<string, unknown>, Map extends SqlMappings = SqlMappings, TStorageHash extends StorageHashBase<string> = StorageHashBase<string>, TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>, TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>> = ContractBase<TStorageHash, TExecutionHash, TProfileHash> & {
106
+ readonly targetFamily: string;
107
+ readonly storage: S;
108
+ readonly models: M;
109
+ readonly relations: R;
110
+ readonly mappings: Map;
111
+ readonly execution?: ExecutionSection;
112
+ };
113
+ type ExtractCodecTypes<TContract extends SqlContract<SqlStorage>> = TContract['mappings']['codecTypes'];
114
+ type ExtractOperationTypes<TContract extends SqlContract<SqlStorage>> = TContract['mappings']['operationTypes'];
115
+ //#endregion
116
+ export { Index as a, ModelStorage as c, SqlMappings as d, SqlStorage as f, UniqueConstraint as g, StorageTypeInstance as h, ForeignKeyReferences as i, PrimaryKey as l, StorageTable as m, ExtractOperationTypes as n, ModelDefinition as o, StorageColumn as p, ForeignKey as r, ModelField as s, ExtractCodecTypes as t, SqlContract as u };
117
+ //# sourceMappingURL=types-D3AOQgwo.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-D3AOQgwo.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;AAgBA;AAsBA;AAKA;AAKA;AAKA;AAKY,KA1CA,aAAA,GA4CW;EAIX,SAAA,UAAY,EAAA,MAAA;EACW,SAAA,OAAA,EAAA,MAAA;EAAf,SAAA,QAAA,EAAA,OAAA;EACI;;;;;EAGc,SAAA,UAAA,CAAA,EA5Cd,MA4Cc,CAAA,MAAA,EAAA,OAAA,CAAA;EAAd;;AAaxB;AAMA;EACkC,SAAA,OAAA,CAAA,EAAA,MAAA;EAAf;;;;EAQP,SAAA,OAAU,CAAA,EA9DD,aA8DC;AAItB,CAAA;AAIY,KAnEA,UAAA,GAmEe;EACP,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;EACc,SAAA,IAAA,CAAA,EAAA,MAAA;CAAf;AACG,KAjEV,gBAAA,GAiEU;EAAM,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;EAGhB,SAAA,IAAA,CAAW,EAAA,MAAA;CACG;AACA,KAjEd,KAAA,GAiEc;EACgB,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;EAAf,SAAA,IAAA,CAAA,EAAA,MAAA;CACe;AAAf,KA9Df,oBAAA,GA8De;EACJ,SAAA,KAAA,EAAA,MAAA;EACmB,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;CAAf;AAAM,KA3DrB,UAAA,GA2DqB;EAGrB,SAAA,OAAW,EAAA,SAAA,MAAA,EAAA;EACX,SAAA,UAAA,EA7DW,oBA6DX;EAAa,SAAA,IAAA,CAAA,EAAA,MAAA;CACb;AAA0B,KA1D1B,YAAA,GA0D0B;EAC1B,SAAA,OAAA,EA1DQ,MA0DR,CAAA,MAAA,EA1DuB,aA0DvB,CAAA;EAA0B,SAAA,UAAA,CAAA,EAzDd,UAyDc;EACxB,SAAA,OAAA,EAzDM,aAyDN,CAzDoB,gBAyDpB,CAAA;EAAc,SAAA,OAAA,EAxDR,aAwDQ,CAxDM,KAwDN,CAAA;EACL,SAAA,WAAA,EAxDC,aAwDD,CAxDe,UAwDf,CAAA;CAA0B;;;;;;;;;;;AAO3B,KAlDV,mBAAA,GAkDU;EACD,SAAA,OAAA,EAAA,MAAA;EACE,SAAA,UAAA,EAAA,MAAA;EAAgB,SAAA,UAAA,EAjDhB,MAiDgB,CAAA,MAAA,EAAA,OAAA,CAAA;AAGvC,CAAA;AAA4D,KAjDhD,UAAA,GAiDgD;EAAZ,SAAA,MAAA,EAhD7B,MAgD6B,CAAA,MAAA,EAhDd,YAgDc,CAAA;EAC9C;;AAEF;;EAAoD,SAAA,KAAA,CAAA,EA9CjC,MA8CiC,CAAA,MAAA,EA9ClB,mBA8CkB,CAAA;CAClD;AAAS,KA5CC,UAAA,GA4CD;;;KAxCC,YAAA;;;KAIA,eAAA;oBACQ;mBACD,eAAe;sBACZ;;KAGV,WAAA;0BACc;0BACA;2BACC,eAAe;2BACf,eAAe;uBACnB;;;2BACI,eAAe;;KAG9B,sBACA,aAAa,sBACb,0BAA0B,mCAC1B,0BAA0B,qCACxB,cAAc,kCACL,0BAA0B,gDACxB,4BAA4B,gDAC9B,0BAA0B,2BAC7C,aAAa,cAAc,gBAAgB;;oBAE3B;mBACD;sBACG;qBACD;uBACE;;KAGX,oCAAoC,YAAY,eAC1D;KAEU,wCAAwC,YAAY,eAC9D"}
@@ -0,0 +1,2 @@
1
+ import { a as Index, c as ModelStorage, d as SqlMappings, f as SqlStorage, g as UniqueConstraint, h as StorageTypeInstance, i as ForeignKeyReferences, l as PrimaryKey, m as StorageTable, n as ExtractOperationTypes, o as ModelDefinition, p as StorageColumn, r as ForeignKey, s as ModelField, t as ExtractCodecTypes, u as SqlContract } from "./types-D3AOQgwo.mjs";
2
+ export { type ExtractCodecTypes, type ExtractOperationTypes, type ForeignKey, type ForeignKeyReferences, type Index, type ModelDefinition, type ModelField, type ModelStorage, type PrimaryKey, type SqlContract, type SqlMappings, type SqlStorage, type StorageColumn, type StorageTable, type StorageTypeInstance, type UniqueConstraint };
package/dist/types.mjs ADDED
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,7 @@
1
+ import { f as SqlStorage, u as SqlContract } from "./types-D3AOQgwo.mjs";
2
+
3
+ //#region src/validate.d.ts
4
+ declare function validateContract<TContract extends SqlContract<SqlStorage>>(value: unknown): TContract;
5
+ //#endregion
6
+ export { validateContract };
7
+ //# sourceMappingURL=validate.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.mts","names":[],"sources":["../src/validate.ts"],"sourcesContent":[],"mappings":";;;iBAkTgB,mCAAmC,YAAY,8BAE5D"}
@@ -0,0 +1,171 @@
1
+ import { a as validateSqlContract } from "./validators-DY_87pfS.mjs";
2
+
3
+ //#region src/validate.ts
4
+ function computeDefaultMappings(models) {
5
+ const modelToTable = {};
6
+ const tableToModel = {};
7
+ const fieldToColumn = {};
8
+ const columnToField = {};
9
+ for (const [modelName, model] of Object.entries(models)) {
10
+ const tableName = model.storage.table;
11
+ modelToTable[modelName] = tableName;
12
+ tableToModel[tableName] = modelName;
13
+ const modelFieldToColumn = {};
14
+ for (const [fieldName, field] of Object.entries(model.fields)) {
15
+ const columnName = field.column;
16
+ modelFieldToColumn[fieldName] = columnName;
17
+ if (!columnToField[tableName]) columnToField[tableName] = {};
18
+ columnToField[tableName][columnName] = fieldName;
19
+ }
20
+ fieldToColumn[modelName] = modelFieldToColumn;
21
+ }
22
+ return {
23
+ modelToTable,
24
+ tableToModel,
25
+ fieldToColumn,
26
+ columnToField,
27
+ codecTypes: {},
28
+ operationTypes: {}
29
+ };
30
+ }
31
+ function assertInverseModelMappings(modelToTable, tableToModel) {
32
+ for (const [model, table] of Object.entries(modelToTable)) if (tableToModel[table] !== model) throw new Error(`Mappings override mismatch: modelToTable.${model}="${table}" is not mirrored in tableToModel`);
33
+ for (const [table, model] of Object.entries(tableToModel)) if (modelToTable[model] !== table) throw new Error(`Mappings override mismatch: tableToModel.${table}="${model}" is not mirrored in modelToTable`);
34
+ }
35
+ function assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel) {
36
+ for (const [model, fields] of Object.entries(fieldToColumn)) {
37
+ const table = modelToTable[model];
38
+ if (!table) throw new Error(`Mappings override mismatch: fieldToColumn references unknown model "${model}"`);
39
+ const reverseFields = columnToField[table];
40
+ if (!reverseFields) throw new Error(`Mappings override mismatch: columnToField is missing table "${table}" for model "${model}"`);
41
+ for (const [field, column] of Object.entries(fields)) if (reverseFields[column] !== field) throw new Error(`Mappings override mismatch: fieldToColumn.${model}.${field}="${column}" is not mirrored in columnToField.${table}`);
42
+ }
43
+ for (const [table, columns] of Object.entries(columnToField)) {
44
+ const model = tableToModel[table];
45
+ if (!model) throw new Error(`Mappings override mismatch: columnToField references unknown table "${table}"`);
46
+ const forwardFields = fieldToColumn[model];
47
+ if (!forwardFields) throw new Error(`Mappings override mismatch: fieldToColumn is missing model "${model}" for table "${table}"`);
48
+ for (const [column, field] of Object.entries(columns)) if (forwardFields[field] !== column) throw new Error(`Mappings override mismatch: columnToField.${table}.${column}="${field}" is not mirrored in fieldToColumn.${model}`);
49
+ }
50
+ }
51
+ function mergeMappings(defaults, existingMappings) {
52
+ const hasModelToTable = existingMappings?.modelToTable !== void 0;
53
+ const hasTableToModel = existingMappings?.tableToModel !== void 0;
54
+ if (hasModelToTable !== hasTableToModel) throw new Error("Mappings override mismatch: modelToTable and tableToModel must be provided together");
55
+ const hasFieldToColumn = existingMappings?.fieldToColumn !== void 0;
56
+ const hasColumnToField = existingMappings?.columnToField !== void 0;
57
+ if (hasFieldToColumn !== hasColumnToField) throw new Error("Mappings override mismatch: fieldToColumn and columnToField must be provided together");
58
+ const modelToTable = hasModelToTable ? existingMappings?.modelToTable ?? {} : defaults.modelToTable;
59
+ const tableToModel = hasTableToModel ? existingMappings?.tableToModel ?? {} : defaults.tableToModel;
60
+ assertInverseModelMappings(modelToTable, tableToModel);
61
+ const fieldToColumn = hasFieldToColumn ? existingMappings?.fieldToColumn ?? {} : defaults.fieldToColumn;
62
+ const columnToField = hasColumnToField ? existingMappings?.columnToField ?? {} : defaults.columnToField;
63
+ assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel);
64
+ return {
65
+ modelToTable,
66
+ tableToModel,
67
+ fieldToColumn,
68
+ columnToField,
69
+ codecTypes: {
70
+ ...defaults.codecTypes,
71
+ ...existingMappings?.codecTypes ?? {}
72
+ },
73
+ operationTypes: {
74
+ ...defaults.operationTypes,
75
+ ...existingMappings?.operationTypes ?? {}
76
+ }
77
+ };
78
+ }
79
+ function validateContractLogic(contract) {
80
+ const tableNames = new Set(Object.keys(contract.storage.tables));
81
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) {
82
+ const columnNames = new Set(Object.keys(table.columns));
83
+ if (table.primaryKey) {
84
+ for (const colName of table.primaryKey.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" primaryKey references non-existent column "${colName}"`);
85
+ }
86
+ for (const unique of table.uniques) for (const colName of unique.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" unique constraint references non-existent column "${colName}"`);
87
+ for (const index of table.indexes) for (const colName of index.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
88
+ for (const fk of table.foreignKeys) {
89
+ for (const colName of fk.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}"`);
90
+ if (!tableNames.has(fk.references.table)) throw new Error(`Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`);
91
+ const referencedTable = contract.storage.tables[fk.references.table];
92
+ const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
93
+ for (const colName of fk.references.columns) if (!referencedColumnNames.has(colName)) throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`);
94
+ if (fk.columns.length !== fk.references.columns.length) throw new Error(`Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`);
95
+ }
96
+ }
97
+ }
98
+ function normalizeContract(contract) {
99
+ if (typeof contract !== "object" || contract === null) return contract;
100
+ const contractObj = contract;
101
+ let normalizedStorage = contractObj["storage"];
102
+ if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) {
103
+ const storage = normalizedStorage;
104
+ const tables = storage["tables"];
105
+ if (tables) {
106
+ const normalizedTables = {};
107
+ for (const [tableName, table] of Object.entries(tables)) {
108
+ const tableObj = table;
109
+ const columns = tableObj["columns"];
110
+ if (columns) {
111
+ const normalizedColumns = {};
112
+ for (const [columnName, column] of Object.entries(columns)) {
113
+ const columnObj = column;
114
+ normalizedColumns[columnName] = {
115
+ ...columnObj,
116
+ nullable: columnObj["nullable"] ?? false
117
+ };
118
+ }
119
+ normalizedTables[tableName] = {
120
+ ...tableObj,
121
+ columns: normalizedColumns,
122
+ uniques: tableObj["uniques"] ?? [],
123
+ indexes: tableObj["indexes"] ?? [],
124
+ foreignKeys: tableObj["foreignKeys"] ?? []
125
+ };
126
+ } else normalizedTables[tableName] = tableObj;
127
+ }
128
+ normalizedStorage = {
129
+ ...storage,
130
+ tables: normalizedTables
131
+ };
132
+ }
133
+ }
134
+ let normalizedModels = contractObj["models"];
135
+ if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) {
136
+ const models = normalizedModels;
137
+ const normalizedModelsObj = {};
138
+ for (const [modelName, model] of Object.entries(models)) {
139
+ const modelObj = model;
140
+ normalizedModelsObj[modelName] = {
141
+ ...modelObj,
142
+ relations: modelObj["relations"] ?? {}
143
+ };
144
+ }
145
+ normalizedModels = normalizedModelsObj;
146
+ }
147
+ return {
148
+ ...contractObj,
149
+ models: normalizedModels,
150
+ relations: contractObj["relations"] ?? {},
151
+ storage: normalizedStorage,
152
+ extensionPacks: contractObj["extensionPacks"] ?? {},
153
+ capabilities: contractObj["capabilities"] ?? {},
154
+ meta: contractObj["meta"] ?? {},
155
+ sources: contractObj["sources"] ?? {}
156
+ };
157
+ }
158
+ function validateContract(value) {
159
+ const structurallyValid = validateSqlContract(normalizeContract(value));
160
+ validateContractLogic(structurallyValid);
161
+ const existingMappings = structurallyValid.mappings;
162
+ const mappings = mergeMappings(computeDefaultMappings(structurallyValid.models), existingMappings);
163
+ return {
164
+ ...structurallyValid,
165
+ mappings
166
+ };
167
+ }
168
+
169
+ //#endregion
170
+ export { validateContract };
171
+ //# sourceMappingURL=validate.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.mjs","names":["modelToTable: Record<string, string>","tableToModel: Record<string, string>","fieldToColumn: Record<string, Record<string, string>>","columnToField: Record<string, Record<string, string>>","modelFieldToColumn: Record<string, string>","normalizedTables: Record<string, unknown>","normalizedColumns: Record<string, unknown>","normalizedModelsObj: Record<string, unknown>"],"sources":["../src/validate.ts"],"sourcesContent":["import type { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from './types';\nimport { validateSqlContract } from './validators';\n\ntype ResolvedMappings = {\n modelToTable: Record<string, string>;\n tableToModel: Record<string, string>;\n fieldToColumn: Record<string, Record<string, string>>;\n columnToField: Record<string, Record<string, string>>;\n codecTypes: Record<string, { readonly output: unknown }>;\n operationTypes: Record<string, Record<string, unknown>>;\n};\n\nfunction computeDefaultMappings(models: Record<string, ModelDefinition>): ResolvedMappings {\n const modelToTable: Record<string, string> = {};\n const tableToModel: Record<string, string> = {};\n const fieldToColumn: Record<string, Record<string, string>> = {};\n const columnToField: Record<string, Record<string, string>> = {};\n\n for (const [modelName, model] of Object.entries(models)) {\n const tableName = model.storage.table;\n modelToTable[modelName] = tableName;\n tableToModel[tableName] = modelName;\n\n const modelFieldToColumn: Record<string, string> = {};\n for (const [fieldName, field] of Object.entries(model.fields)) {\n const columnName = field.column;\n modelFieldToColumn[fieldName] = columnName;\n if (!columnToField[tableName]) {\n columnToField[tableName] = {};\n }\n columnToField[tableName][columnName] = fieldName;\n }\n\n fieldToColumn[modelName] = modelFieldToColumn;\n }\n\n return {\n modelToTable,\n tableToModel,\n fieldToColumn,\n columnToField,\n codecTypes: {},\n operationTypes: {},\n };\n}\n\nfunction assertInverseModelMappings(\n modelToTable: Record<string, string>,\n tableToModel: Record<string, string>,\n) {\n for (const [model, table] of Object.entries(modelToTable)) {\n if (tableToModel[table] !== model) {\n throw new Error(\n `Mappings override mismatch: modelToTable.${model}=\"${table}\" is not mirrored in tableToModel`,\n );\n }\n }\n for (const [table, model] of Object.entries(tableToModel)) {\n if (modelToTable[model] !== table) {\n throw new Error(\n `Mappings override mismatch: tableToModel.${table}=\"${model}\" is not mirrored in modelToTable`,\n );\n }\n }\n}\n\nfunction assertInverseFieldMappings(\n fieldToColumn: Record<string, Record<string, string>>,\n columnToField: Record<string, Record<string, string>>,\n modelToTable: Record<string, string>,\n tableToModel: Record<string, string>,\n) {\n for (const [model, fields] of Object.entries(fieldToColumn)) {\n const table = modelToTable[model];\n if (!table) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn references unknown model \"${model}\"`,\n );\n }\n const reverseFields = columnToField[table];\n if (!reverseFields) {\n throw new Error(\n `Mappings override mismatch: columnToField is missing table \"${table}\" for model \"${model}\"`,\n );\n }\n for (const [field, column] of Object.entries(fields)) {\n if (reverseFields[column] !== field) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn.${model}.${field}=\"${column}\" is not mirrored in columnToField.${table}`,\n );\n }\n }\n }\n\n for (const [table, columns] of Object.entries(columnToField)) {\n const model = tableToModel[table];\n if (!model) {\n throw new Error(\n `Mappings override mismatch: columnToField references unknown table \"${table}\"`,\n );\n }\n const forwardFields = fieldToColumn[model];\n if (!forwardFields) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn is missing model \"${model}\" for table \"${table}\"`,\n );\n }\n for (const [column, field] of Object.entries(columns)) {\n if (forwardFields[field] !== column) {\n throw new Error(\n `Mappings override mismatch: columnToField.${table}.${column}=\"${field}\" is not mirrored in fieldToColumn.${model}`,\n );\n }\n }\n }\n}\n\nfunction mergeMappings(\n defaults: ResolvedMappings,\n existingMappings?: Partial<SqlMappings>,\n): ResolvedMappings {\n const hasModelToTable = existingMappings?.modelToTable !== undefined;\n const hasTableToModel = existingMappings?.tableToModel !== undefined;\n if (hasModelToTable !== hasTableToModel) {\n throw new Error(\n 'Mappings override mismatch: modelToTable and tableToModel must be provided together',\n );\n }\n\n const hasFieldToColumn = existingMappings?.fieldToColumn !== undefined;\n const hasColumnToField = existingMappings?.columnToField !== undefined;\n if (hasFieldToColumn !== hasColumnToField) {\n throw new Error(\n 'Mappings override mismatch: fieldToColumn and columnToField must be provided together',\n );\n }\n\n const modelToTable: Record<string, string> = hasModelToTable\n ? (existingMappings?.modelToTable ?? {})\n : defaults.modelToTable;\n const tableToModel: Record<string, string> = hasTableToModel\n ? (existingMappings?.tableToModel ?? {})\n : defaults.tableToModel;\n assertInverseModelMappings(modelToTable, tableToModel);\n\n const fieldToColumn: Record<string, Record<string, string>> = hasFieldToColumn\n ? (existingMappings?.fieldToColumn ?? {})\n : defaults.fieldToColumn;\n const columnToField: Record<string, Record<string, string>> = hasColumnToField\n ? (existingMappings?.columnToField ?? {})\n : defaults.columnToField;\n assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel);\n\n return {\n modelToTable,\n tableToModel,\n fieldToColumn,\n columnToField,\n codecTypes: { ...defaults.codecTypes, ...(existingMappings?.codecTypes ?? {}) },\n operationTypes: { ...defaults.operationTypes, ...(existingMappings?.operationTypes ?? {}) },\n };\n}\n\nfunction validateContractLogic(contract: SqlContract<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 Error(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\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 Error(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\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 Error(`Table \"${tableName}\" index references non-existent column \"${colName}\"`);\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 Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n );\n }\n }\n\n if (!tableNames.has(fk.references.table)) {\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n\n const referencedTable = contract.storage.tables[\n fk.references.table\n ] as (typeof contract.storage.tables)[string];\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 Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n throw new Error(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n );\n }\n }\n }\n}\n\nfunction normalizeContract(contract: unknown): SqlContract<SqlStorage> {\n if (typeof contract !== 'object' || contract === null) {\n return contract as SqlContract<SqlStorage>;\n }\n\n const contractObj = contract as Record<string, unknown>;\n\n let normalizedStorage = contractObj['storage'];\n if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {\n const storage = normalizedStorage as Record<string, unknown>;\n const tables = storage['tables'] as Record<string, unknown> | undefined;\n\n if (tables) {\n const normalizedTables: Record<string, unknown> = {};\n for (const [tableName, table] of Object.entries(tables)) {\n const tableObj = table as Record<string, unknown>;\n const columns = tableObj['columns'] as Record<string, unknown> | undefined;\n\n if (columns) {\n const normalizedColumns: Record<string, unknown> = {};\n for (const [columnName, column] of Object.entries(columns)) {\n const columnObj = column as Record<string, unknown>;\n normalizedColumns[columnName] = {\n ...columnObj,\n nullable: columnObj['nullable'] ?? false,\n };\n }\n\n normalizedTables[tableName] = {\n ...tableObj,\n columns: normalizedColumns,\n uniques: tableObj['uniques'] ?? [],\n indexes: tableObj['indexes'] ?? [],\n foreignKeys: tableObj['foreignKeys'] ?? [],\n };\n } else {\n normalizedTables[tableName] = tableObj;\n }\n }\n\n normalizedStorage = {\n ...storage,\n tables: normalizedTables,\n };\n }\n }\n\n let normalizedModels = contractObj['models'];\n if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {\n const models = normalizedModels as Record<string, unknown>;\n const normalizedModelsObj: Record<string, unknown> = {};\n for (const [modelName, model] of Object.entries(models)) {\n const modelObj = model as Record<string, unknown>;\n normalizedModelsObj[modelName] = {\n ...modelObj,\n relations: modelObj['relations'] ?? {},\n };\n }\n normalizedModels = normalizedModelsObj;\n }\n\n return {\n ...contractObj,\n models: normalizedModels,\n relations: contractObj['relations'] ?? {},\n storage: normalizedStorage,\n extensionPacks: contractObj['extensionPacks'] ?? {},\n capabilities: contractObj['capabilities'] ?? {},\n meta: contractObj['meta'] ?? {},\n sources: contractObj['sources'] ?? {},\n } as SqlContract<SqlStorage>;\n}\n\nexport function validateContract<TContract extends SqlContract<SqlStorage>>(\n value: unknown,\n): TContract {\n const normalized = normalizeContract(value);\n const structurallyValid = validateSqlContract<SqlContract<SqlStorage>>(normalized);\n validateContractLogic(structurallyValid);\n\n const existingMappings = (structurallyValid as { mappings?: Partial<SqlMappings> }).mappings;\n const defaultMappings = computeDefaultMappings(\n structurallyValid.models as Record<string, ModelDefinition>,\n );\n const mappings = mergeMappings(defaultMappings, existingMappings);\n\n return {\n ...structurallyValid,\n mappings,\n } as TContract;\n}\n"],"mappings":";;;AAYA,SAAS,uBAAuB,QAA2D;CACzF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