@prisma-next/sql-contract 0.14.0 → 0.15.0-dev.10
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/dist/canonicalization-hooks.d.mts.map +1 -1
- package/dist/canonicalization-hooks.mjs +70 -50
- package/dist/canonicalization-hooks.mjs.map +1 -1
- package/dist/contract-view.d.mts +61 -0
- package/dist/contract-view.d.mts.map +1 -0
- package/dist/contract-view.mjs +39 -0
- package/dist/contract-view.mjs.map +1 -0
- package/dist/entity-handle-lowering-hook.d.mts +91 -0
- package/dist/entity-handle-lowering-hook.d.mts.map +1 -0
- package/dist/entity-handle-lowering-hook.mjs +11 -0
- package/dist/entity-handle-lowering-hook.mjs.map +1 -0
- package/dist/entity-kinds-CVg6HzG2.mjs +130 -0
- package/dist/entity-kinds-CVg6HzG2.mjs.map +1 -0
- package/dist/entity-kinds.d.mts +2 -1
- package/dist/entity-kinds.d.mts.map +1 -1
- package/dist/entity-kinds.mjs +1 -1
- package/dist/factories.d.mts +7 -6
- package/dist/factories.d.mts.map +1 -1
- package/dist/factories.mjs +5 -11
- package/dist/factories.mjs.map +1 -1
- package/dist/{foreign-key-BATxB95l.d.mts → foreign-key-DuCoGJCf.d.mts} +12 -48
- package/dist/foreign-key-DuCoGJCf.d.mts.map +1 -0
- package/dist/foreign-key-materialization.d.mts +64 -0
- package/dist/foreign-key-materialization.d.mts.map +1 -0
- package/dist/foreign-key-materialization.mjs +67 -0
- package/dist/foreign-key-materialization.mjs.map +1 -0
- package/dist/index-type-validation.d.mts +1 -1
- package/dist/referential-action-sql.d.mts +1 -1
- package/dist/resolve-storage-table.d.mts +2 -2
- package/dist/sql-node-V214WXQD.d.mts +42 -0
- package/dist/sql-node-V214WXQD.d.mts.map +1 -0
- package/dist/{sql-storage-Dga0jwP2.d.mts → sql-storage-p-Wzt_MO.d.mts} +63 -20
- package/dist/sql-storage-p-Wzt_MO.d.mts.map +1 -0
- package/dist/{storage-value-set-WnYsIFM8.d.mts → storage-table-CE-Ns6wa.d.mts} +17 -90
- package/dist/storage-table-CE-Ns6wa.d.mts.map +1 -0
- package/dist/{entity-kinds-Cl36zL5j.mjs → storage-table-DBpYBmty.mjs} +26 -162
- package/dist/storage-table-DBpYBmty.mjs.map +1 -0
- package/dist/storage-value-set-3BKuha5q.mjs +38 -0
- package/dist/storage-value-set-3BKuha5q.mjs.map +1 -0
- package/dist/storage-value-set-D-jww77l.d.mts +41 -0
- package/dist/storage-value-set-D-jww77l.d.mts.map +1 -0
- package/dist/{types-B1N8w0I2.d.mts → types-3vOIrnvp.d.mts} +25 -55
- package/dist/types-3vOIrnvp.d.mts.map +1 -0
- package/dist/types.d.mts +14 -5
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +115 -3
- package/dist/types.mjs.map +1 -0
- package/dist/unique-constraint-C0De4sLU.d.mts +55 -0
- package/dist/unique-constraint-C0De4sLU.d.mts.map +1 -0
- package/dist/validators.d.mts +10 -7
- package/dist/validators.d.mts.map +1 -1
- package/dist/validators.mjs +111 -21
- package/dist/validators.mjs.map +1 -1
- package/dist/value-set-derivation-hook.d.mts +35 -0
- package/dist/value-set-derivation-hook.d.mts.map +1 -0
- package/dist/value-set-derivation-hook.mjs +22 -0
- package/dist/value-set-derivation-hook.mjs.map +1 -0
- package/package.json +15 -10
- package/src/canonicalization-hooks.ts +31 -3
- package/src/column-type-resolution.ts +26 -0
- package/src/contract-view.ts +98 -0
- package/src/entity-handle-lowering-hook.ts +104 -0
- package/src/exports/contract-view.ts +11 -0
- package/src/exports/entity-handle-lowering-hook.ts +10 -0
- package/src/exports/foreign-key-materialization.ts +8 -0
- package/src/exports/types.ts +17 -4
- package/src/exports/value-set-derivation-hook.ts +2 -0
- package/src/factories.ts +13 -7
- package/src/foreign-key-materialization.ts +107 -0
- package/src/ir/foreign-key.ts +9 -9
- package/src/ir/sql-storage.ts +81 -17
- package/src/ir/storage-column.ts +3 -0
- package/src/ir/storage-entry-schemas.ts +1 -2
- package/src/ir/storage-table.ts +21 -0
- package/src/ir/storage-value-set.ts +5 -0
- package/src/types.ts +51 -8
- package/src/validators.ts +215 -42
- package/src/value-set-derivation-hook.ts +47 -0
- package/dist/entity-kinds-Cl36zL5j.mjs.map +0 -1
- package/dist/foreign-key-BATxB95l.d.mts.map +0 -1
- package/dist/sql-storage-Dga0jwP2.d.mts.map +0 -1
- package/dist/storage-value-set-WnYsIFM8.d.mts.map +0 -1
- package/dist/types-B-eiQXff.mjs +0 -191
- package/dist/types-B-eiQXff.mjs.map +0 -1
- package/dist/types-B1N8w0I2.d.mts.map +0 -1
- package/src/ir/build-sql-namespace.ts +0 -110
- package/src/ir/sql-unbound-namespace.ts +0 -74
package/dist/types.mjs
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { a as PrimaryKey, c as CheckConstraint, i as Index, l as SqlNode, n as UniqueConstraint, o as ForeignKey, r as StorageColumn, s as ForeignKeyReference, t as StorageTable } from "./storage-table-DBpYBmty.mjs";
|
|
2
|
+
import { n as isStorageValueSet, t as StorageValueSet } from "./storage-value-set-3BKuha5q.mjs";
|
|
3
|
+
import { NamespaceBase, freezeNode, isPlainRecord } from "@prisma-next/framework-components/ir";
|
|
4
|
+
//#region src/ir/storage-type-instance.ts
|
|
5
|
+
/**
|
|
6
|
+
* Sentinel kind for the legacy codec-triple shape persisted under
|
|
7
|
+
* `SqlStorage.types`. Plain JSON-clean object literals carry this
|
|
8
|
+
* discriminator so the polymorphic slot dispatch can route them down
|
|
9
|
+
* the codec path while target-specific IR class instances (e.g. the
|
|
10
|
+
* Postgres enum class) keep their own narrower `kind` literal.
|
|
11
|
+
*/
|
|
12
|
+
const CODEC_INSTANCE_KIND = "codec-instance";
|
|
13
|
+
/**
|
|
14
|
+
* Stamp the codec-instance `kind` discriminator on a caller-supplied
|
|
15
|
+
* codec triple. Idempotent: input that already carries the discriminator
|
|
16
|
+
* passes through unchanged. Missing `typeParams` is normalised to `{}`.
|
|
17
|
+
*/
|
|
18
|
+
function toStorageTypeInstance(input) {
|
|
19
|
+
return {
|
|
20
|
+
kind: CODEC_INSTANCE_KIND,
|
|
21
|
+
codecId: input.codecId,
|
|
22
|
+
nativeType: input.nativeType,
|
|
23
|
+
typeParams: input.typeParams ?? {}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Type-guard for codec-typed entries on the polymorphic
|
|
28
|
+
* `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from
|
|
29
|
+
* any class-instance kinds a target pack contributes.
|
|
30
|
+
*/
|
|
31
|
+
function isStorageTypeInstance(value) {
|
|
32
|
+
if (typeof value !== "object" || value === null) return false;
|
|
33
|
+
return value.kind === CODEC_INSTANCE_KIND;
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/ir/sql-storage.ts
|
|
37
|
+
/**
|
|
38
|
+
* Narrows framework `AuthoringContributions` to the SQL-family shape by testing
|
|
39
|
+
* for the SQL-specific `createNamespace` capability.
|
|
40
|
+
*/
|
|
41
|
+
function isSqlAuthoringContributions(authoring) {
|
|
42
|
+
if (authoring === void 0 || !Object.hasOwn(authoring, "createNamespace")) return false;
|
|
43
|
+
return typeof Reflect.get(authoring, "createNamespace") === "function";
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Abstract SQL family namespace base class. Target concretions (`PostgresSchema`,
|
|
47
|
+
* `SqliteDatabase`, …) extend this — it is never instantiated directly.
|
|
48
|
+
* `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]`
|
|
49
|
+
* addresses any entity.
|
|
50
|
+
*/
|
|
51
|
+
var SqlNamespaceBase = class extends NamespaceBase {};
|
|
52
|
+
/**
|
|
53
|
+
* Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks
|
|
54
|
+
* `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it
|
|
55
|
+
* survives duplicate-module boundaries (e.g. dist e2e where the target and
|
|
56
|
+
* the family carry separate copies of `@prisma-next/framework-components`).
|
|
57
|
+
*
|
|
58
|
+
* Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`,
|
|
59
|
+
* `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput`
|
|
60
|
+
* objects (`{ id, entries }`) do not.
|
|
61
|
+
*/
|
|
62
|
+
function isMaterializedSqlNamespace(x) {
|
|
63
|
+
if (typeof x !== "object" || x === null || !("qualifyTable" in x)) return false;
|
|
64
|
+
return typeof x.qualifyTable === "function";
|
|
65
|
+
}
|
|
66
|
+
var SqlStorage = class extends SqlNode {
|
|
67
|
+
storageHash;
|
|
68
|
+
namespaces;
|
|
69
|
+
constructor(input) {
|
|
70
|
+
super();
|
|
71
|
+
this.storageHash = input.storageHash;
|
|
72
|
+
this.namespaces = Object.freeze(input.namespaces);
|
|
73
|
+
if (input.types !== void 0) this.types = Object.freeze(Object.fromEntries(Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)])));
|
|
74
|
+
freezeNode(this);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Strict polymorphic-slot dispatch for `SqlStorage.types` entries.
|
|
79
|
+
* Every entry must carry a `kind: 'codec-instance'` discriminator or
|
|
80
|
+
* be an already-constructed `StorageTypeInstance`. Untagged or
|
|
81
|
+
* unrecognised inputs throw a diagnostic naming the entry and its
|
|
82
|
+
* `kind`, so format drift surfaces loudly at the deserializer
|
|
83
|
+
* boundary instead of slipping past the seam and corrupting
|
|
84
|
+
* downstream IR walks.
|
|
85
|
+
*
|
|
86
|
+
* Codec-triple authors that have an untagged shape on hand can call
|
|
87
|
+
* `toStorageTypeInstance(...)` (which stamps the `'codec-instance'`
|
|
88
|
+
* discriminator) before constructing `SqlStorage`. On-disk reads
|
|
89
|
+
* cross `familyInstance.deserializeContract` first; the structural
|
|
90
|
+
* arktype schema rejects untagged entries earlier, so this throw
|
|
91
|
+
* only fires for in-memory authoring bugs.
|
|
92
|
+
*/
|
|
93
|
+
function normaliseTypeEntry(name, entry) {
|
|
94
|
+
if (isStorageTypeInstance(entry)) {
|
|
95
|
+
if ("typeParams" in entry) return entry;
|
|
96
|
+
return toStorageTypeInstance(entry);
|
|
97
|
+
}
|
|
98
|
+
const rawKind = isPlainRecord(entry) ? entry["kind"] : void 0;
|
|
99
|
+
const kindDescription = rawKind === void 0 ? "missing `kind` discriminator" : `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`;
|
|
100
|
+
throw new Error(`storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify("codec-instance")}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`);
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/types.ts
|
|
104
|
+
const DEFAULT_FK_CONSTRAINT = true;
|
|
105
|
+
const DEFAULT_FK_INDEX = true;
|
|
106
|
+
function applyFkDefaults(fk, overrideDefaults) {
|
|
107
|
+
return {
|
|
108
|
+
constraint: fk.constraint ?? overrideDefaults?.constraint ?? true,
|
|
109
|
+
index: fk.index ?? overrideDefaults?.index ?? true
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { CODEC_INSTANCE_KIND, CheckConstraint, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, ForeignKey, ForeignKeyReference, Index, PrimaryKey, SqlNamespaceBase, SqlNode, SqlStorage, StorageColumn, StorageTable, StorageValueSet, UniqueConstraint, applyFkDefaults, isMaterializedSqlNamespace, isSqlAuthoringContributions, isStorageTypeInstance, isStorageValueSet, toStorageTypeInstance };
|
|
114
|
+
|
|
115
|
+
//# sourceMappingURL=types.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts","../src/types.ts"],"sourcesContent":["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 any class-instance\n * kinds a target pack contributes to 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 * `typeParams` may be omitted on input; the constructor normalises a\n * missing value to `{}` so the in-memory shape is always present.\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. Missing `typeParams` is normalised to `{}`.\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 * any class-instance kinds a target pack contributes.\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 type { AuthoringContributions } from '@prisma-next/framework-components/authoring';\nimport {\n freezeNode,\n isPlainRecord,\n type Namespace,\n NamespaceBase,\n type Storage,\n} from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\nimport type { StorageTable } from './storage-table';\nimport {\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n toStorageTypeInstance,\n} from './storage-type-instance';\nimport type { StorageValueSet } from './storage-value-set';\n\n/**\n * Polymorphic value type for document-scoped `SqlStorage.types` entries\n * (codec aliases / parameterised native type registrations).\n *\n * Postgres native enum registrations live under the postgres-specific\n * `entries.type` slot on `PostgresSchema` (target layer), not here.\n */\nexport type SqlStorageTypeEntry = StorageTypeInstance | StorageTypeInstanceInput;\n\nexport interface SqlNamespaceInput {\n readonly id: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\n/**\n * Target-supplied factory that materializes a `Namespace` from a SQL\n * `SqlNamespaceInput` (used to populate `SqlStorage.namespaces`).\n */\nexport type SqlNamespaceFactory = (input: SqlNamespaceInput) => Namespace;\n\n/**\n * SQL-family extension of the framework `AuthoringContributions`. SQL target\n * packs add a `createNamespace` factory so the PSL/TS authoring paths can\n * materialize namespaces (and merge lowered extension-block entities) without\n * each consumer re-specifying it. The factory is SQL-specific, so it lives here\n * rather than on the framework `AuthoringContributions` base.\n */\nexport interface SqlAuthoringContributions extends AuthoringContributions {\n readonly createNamespace?: SqlNamespaceFactory;\n}\n\n/**\n * Narrows framework `AuthoringContributions` to the SQL-family shape by testing\n * for the SQL-specific `createNamespace` capability.\n */\nexport function isSqlAuthoringContributions(\n authoring: AuthoringContributions | undefined,\n): authoring is SqlAuthoringContributions {\n if (authoring === undefined || !Object.hasOwn(authoring, 'createNamespace')) {\n return false;\n }\n return typeof Reflect.get(authoring, 'createNamespace') === 'function';\n}\n\nexport interface SqlStorageInput<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n readonly types?: Record<string, SqlStorageTypeEntry>;\n readonly namespaces: Readonly<Record<string, SqlNamespaceBase>>;\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 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. Callers must supply fully\n * constructed `Namespace` instances — construction discipline lives\n * in the authoring builders and deserializer hydration paths.\n *\n * The constructor normalises optional `types` into class instances.\n * `types` is polymorphic per Decision 18 Option B: codec-triple inputs\n * are stamped with `kind: 'codec-instance'`; hydration of raw JSON\n * class-instance entries (carrying their narrower `kind` literal) is\n * the per-target serializer's responsibility (so the family base does\n * not import target-specific subclasses).\n */\n/**\n * The typed `entries` shape for SQL family namespaces. The open dictionary\n * is intersected with optional known-kind maps so that `ns.entries.table`\n * and `ns.entries.valueSet` resolve without a cast, while unknown pack-\n * contributed kinds remain valid (the `Record` part allows any string key).\n */\nexport type SqlNamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>> & {\n readonly table?: Readonly<Record<string, StorageTable>>;\n readonly valueSet?: Readonly<Record<string, StorageValueSet>>;\n};\n\n/**\n * Structural interface for SQL family namespaces. Generated `.d.ts` contract\n * types satisfy this structurally (no prototype methods). The runtime\n * abstract class `SqlNamespaceBase` extends this.\n *\n * `qualifyTable` and `isUnbound` are optional so JSON-shaped contract types\n * (which carry no methods) are accepted where `SqlNamespace` is required.\n * Hydrated `SqlNamespaceBase` instances always have both.\n */\nexport interface SqlNamespace {\n readonly kind: string;\n readonly id: string;\n readonly entries: SqlNamespaceEntries;\n readonly isUnbound?: boolean;\n qualifyTable?(tableName: string): string;\n}\n\n/**\n * Abstract SQL family namespace base class. Target concretions (`PostgresSchema`,\n * `SqliteDatabase`, …) extend this — it is never instantiated directly.\n * `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]`\n * addresses any entity.\n */\nexport abstract class SqlNamespaceBase extends NamespaceBase implements SqlNamespace {\n abstract override readonly id: string;\n abstract override readonly entries: SqlNamespaceEntries;\n\n abstract qualifyTable(tableName: string): string;\n}\n\n/**\n * Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks\n * `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it\n * survives duplicate-module boundaries (e.g. dist e2e where the target and\n * the family carry separate copies of `@prisma-next/framework-components`).\n *\n * Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`,\n * `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput`\n * objects (`{ id, entries }`) do not.\n */\nexport function isMaterializedSqlNamespace(x: unknown): x is SqlNamespaceBase {\n if (typeof x !== 'object' || x === null || !('qualifyTable' in x)) return false;\n return typeof x.qualifyTable === 'function';\n}\n\nexport class SqlStorage<THash extends string = string> extends SqlNode implements Storage {\n readonly storageHash: StorageHashBase<THash>;\n readonly namespaces: Readonly<Record<string, SqlNamespace>>;\n declare readonly types?: Readonly<Record<string, StorageTypeInstance>>;\n\n constructor(input: SqlStorageInput<THash>) {\n super();\n this.storageHash = input.storageHash;\n this.namespaces = Object.freeze(input.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 * Every entry must carry a `kind: 'codec-instance'` discriminator or\n * be an already-constructed `StorageTypeInstance`. 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(name: string, entry: SqlStorageTypeEntry): StorageTypeInstance {\n if (isStorageTypeInstance(entry)) {\n // Normalise on-disk objects that omit `typeParams` (the canonical on-disk\n // form strips empty typeParams to keep JSON compact). The in-memory invariant\n // is always `typeParams: {}` when empty — never `undefined`. Only create a\n // new object when necessary to preserve identity-equality for callers that\n // hold a reference to an already-correct in-memory entry.\n if ('typeParams' in entry) {\n return entry;\n }\n return toStorageTypeInstance(entry);\n }\n const rawKind = isPlainRecord(entry) ? entry['kind'] : undefined;\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')}. Untagged codec triples should be wrapped with toStorageTypeInstance(...) before construction.`,\n );\n}\n","import type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport type { ReferentialAction } from './ir/foreign-key';\n\nexport interface SqlControlDriverInstance<T extends string = string>\n extends ControlDriverInstance<'sql', T> {\n query<Row = Record<string, unknown>>(\n sql: string,\n params?: readonly unknown[],\n ): Promise<{ readonly rows: Row[] }>;\n}\n\nexport { CheckConstraint, type CheckConstraintInput } from './ir/check-constraint';\nexport {\n ForeignKey,\n type ForeignKeyInput,\n type ReferentialAction,\n} from './ir/foreign-key';\nexport {\n ForeignKeyReference,\n type ForeignKeyReferenceInput,\n} from './ir/foreign-key-reference';\nexport { PrimaryKey, type PrimaryKeyInput } from './ir/primary-key';\nexport { Index, type IndexInput } from './ir/sql-index';\nexport { SqlNode } from './ir/sql-node';\nexport {\n isMaterializedSqlNamespace,\n isSqlAuthoringContributions,\n type SqlAuthoringContributions,\n type SqlNamespace,\n SqlNamespaceBase,\n type SqlNamespaceEntries,\n type SqlNamespaceFactory,\n type SqlNamespaceInput,\n SqlStorage,\n type SqlStorageInput,\n type SqlStorageTypeEntry,\n} from './ir/sql-storage';\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 isStorageValueSet,\n StorageValueSet,\n type StorageValueSetInput,\n} from './ir/storage-value-set';\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 namespaceId: 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\n// Field-type maps nested by namespace coordinate: `[namespaceId][model][field]`.\n// Shared by the output and input field-type maps and their extractors.\nexport type NamespacedFieldTypeMap = Record<string, Record<string, Record<string, unknown>>>;\n\nexport type NamespacedStorageColumnTypeMap = Record<\n string,\n Record<string, Record<string, unknown>>\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 NamespacedFieldTypeMap = Record<string, never>,\n TFieldInputTypes extends NamespacedFieldTypeMap = Record<string, never>,\n TStorageColumnTypes extends NamespacedStorageColumnTypeMap = Record<string, never>,\n TStorageColumnInputTypes extends NamespacedStorageColumnTypeMap = Record<string, never>,\n> = {\n readonly codecTypes: TCodecTypes;\n readonly queryOperationTypes: TQueryOperationTypes;\n readonly fieldOutputTypes: TFieldOutputTypes;\n readonly fieldInputTypes: TFieldInputTypes;\n readonly storageColumnTypes: TStorageColumnTypes;\n readonly storageColumnInputTypes: TStorageColumnInputTypes;\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. Names a concrete codec identity, a set of capability traits the\n * field's codec must carry, or targets list-typed (`many`) fields. Element\n * capability gating for list ops travels in `elementTraits`.\n */\nexport type QueryOperationSelfSpec =\n | { readonly codecId: string; readonly traits?: never; readonly many?: never }\n | { readonly traits: readonly CodecTrait[]; readonly codecId?: never; readonly many?: never }\n | {\n readonly many: true;\n readonly elementTraits?: readonly CodecTrait[];\n readonly codecId?: never;\n readonly traits?: never;\n };\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 NamespacedFieldTypeMap\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 NamespacedFieldTypeMap\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type StorageColumnTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly storageColumnTypes: infer F }\n ? F extends NamespacedStorageColumnTypeMap\n ? F\n : Record<string, never>\n : Record<string, never>;\n\nexport type StorageColumnInputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly storageColumnInputTypes: infer F }\n ? F extends NamespacedStorageColumnTypeMap\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>>;\nexport type ExtractStorageColumnTypes<T> = StorageColumnTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractStorageColumnInputTypes<T> = StorageColumnInputTypesOf<\n ExtractTypeMapsFromContract<T>\n>;\n\nexport type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never]\n ? ExtractCodecTypes<TContract>\n : CodecTypesOf<TTypeMaps>;\n"],"mappings":";;;;;;;;;;;AASA,MAAa,sBAAsB;;;;;;AAmCnC,SAAgB,sBAAsB,OAAsD;CAC1F,OAAO;EACL,MAAM;EACN,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,YAAY,MAAM,cAAc,CAAC;CACnC;AACF;;;;;;AAOA,SAAgB,sBAAsB,OAA8C;CAClF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAQ,MAA6B,SAAS;AAChD;;;;;;;ACPA,SAAgB,4BACd,WACwC;CACxC,IAAI,cAAc,KAAA,KAAa,CAAC,OAAO,OAAO,WAAW,iBAAiB,GACxE,OAAO;CAET,OAAO,OAAO,QAAQ,IAAI,WAAW,iBAAiB,MAAM;AAC9D;;;;;;;AA+DA,IAAsB,mBAAtB,cAA+C,cAAsC,CAKrF;;;;;;;;;;;AAYA,SAAgB,2BAA2B,GAAmC;CAC5E,IAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,EAAE,kBAAkB,IAAI,OAAO;CAC1E,OAAO,OAAO,EAAE,iBAAiB;AACnC;AAEA,IAAa,aAAb,cAA+D,QAA2B;CACxF;CACA;CAGA,YAAY,OAA+B;EACzC,MAAM;EACN,KAAK,cAAc,MAAM;EACzB,KAAK,aAAa,OAAO,OAAO,MAAM,UAAU;EAChD,IAAI,MAAM,UAAU,KAAA,GAClB,KAAK,QAAQ,OAAO,OAClB,OAAO,YACL,OAAO,QAAQ,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,MAAM,mBAAmB,MAAM,EAAE,CAAC,CAAC,CACtF,CACF;EAEF,WAAW,IAAI;CACjB;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAS,mBAAmB,MAAc,OAAiD;CACzF,IAAI,sBAAsB,KAAK,GAAG;EAMhC,IAAI,gBAAgB,OAClB,OAAO;EAET,OAAO,sBAAsB,KAAK;CACpC;CACA,MAAM,UAAU,cAAc,KAAK,IAAI,MAAM,UAAU,KAAA;CACvD,MAAM,kBACJ,YAAY,KAAA,IACR,iCACA,uCAAuC,KAAK,UAAU,OAAO;CACnE,MAAM,IAAI,MACR,iBAAiB,KAAK,UAAU,IAAI,EAAE,QAAQ,gBAAgB,aAAa,KAAK,UAAU,gBAAgB,EAAE,gGAC9G;AACF;;;AC/HA,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;CACvC;AACF"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { t as SqlNode } from "./sql-node-V214WXQD.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/ir/primary-key.d.ts
|
|
4
|
+
interface PrimaryKeyInput {
|
|
5
|
+
readonly columns: readonly string[];
|
|
6
|
+
readonly name?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* SQL Contract IR node for a table's primary-key constraint.
|
|
10
|
+
*/
|
|
11
|
+
declare class PrimaryKey extends SqlNode {
|
|
12
|
+
readonly columns: readonly string[];
|
|
13
|
+
readonly name?: string;
|
|
14
|
+
constructor(input: PrimaryKeyInput);
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/ir/sql-index.d.ts
|
|
18
|
+
interface IndexInput {
|
|
19
|
+
readonly columns: readonly string[];
|
|
20
|
+
readonly name?: string;
|
|
21
|
+
readonly type?: string;
|
|
22
|
+
readonly options?: Record<string, unknown>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* SQL Contract IR node for a table-level secondary index.
|
|
26
|
+
*
|
|
27
|
+
* Note that this class shadows the global TypeScript `Index` lib type
|
|
28
|
+
* at the family-shared name; consumer files that need both should
|
|
29
|
+
* alias one (e.g.
|
|
30
|
+
* `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).
|
|
31
|
+
*/
|
|
32
|
+
declare class Index extends SqlNode {
|
|
33
|
+
readonly columns: readonly string[];
|
|
34
|
+
readonly name?: string;
|
|
35
|
+
readonly type?: string;
|
|
36
|
+
readonly options?: Record<string, unknown>;
|
|
37
|
+
constructor(input: IndexInput);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/ir/unique-constraint.d.ts
|
|
41
|
+
interface UniqueConstraintInput {
|
|
42
|
+
readonly columns: readonly string[];
|
|
43
|
+
readonly name?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* SQL Contract IR node for a table-level unique constraint.
|
|
47
|
+
*/
|
|
48
|
+
declare class UniqueConstraint extends SqlNode {
|
|
49
|
+
readonly columns: readonly string[];
|
|
50
|
+
readonly name?: string;
|
|
51
|
+
constructor(input: UniqueConstraintInput);
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { PrimaryKey as a, IndexInput as i, UniqueConstraintInput as n, PrimaryKeyInput as o, Index as r, UniqueConstraint as t };
|
|
55
|
+
//# sourceMappingURL=unique-constraint-C0De4sLU.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unique-constraint-C0De4sLU.d.mts","names":[],"sources":["../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/unique-constraint.ts"],"mappings":";;;UAGiB,eAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;;;AAAA;cAMF,UAAA,SAAmB,OAAO;EAAA,SAC5B,OAAA;EAAA,SACQ,IAAA;cAEL,KAAA,EAAO,eAAA;AAAA;;;UCZJ,UAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAA;EAAA,SACA,IAAA;EAAA,SACA,OAAA,GAAU,MAAM;AAAA;ADFZ;AAMf;;;;;;;AANe,cCaF,KAAA,SAAc,OAAA;EAAA,SAChB,OAAA;EAAA,SACQ,IAAA;EAAA,SACA,IAAA;EAAA,SACA,OAAA,GAAU,MAAA;cAEf,KAAA,EAAO,UAAA;AAAA;;;UCrBJ,qBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;;;AFAA;cEMF,gBAAA,SAAyB,OAAO;EAAA,SAClC,OAAA;EAAA,SACQ,IAAA;cAEL,KAAA,EAAO,qBAAA;AAAA"}
|
package/dist/validators.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as ForeignKeyInput, r as ReferentialAction } from "./foreign-key-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { Type } from "arktype";
|
|
1
|
+
import { n as ForeignKeyInput, r as ReferentialAction } from "./foreign-key-DuCoGJCf.mjs";
|
|
2
|
+
import { n as UniqueConstraintInput, o as PrimaryKeyInput } from "./unique-constraint-C0De4sLU.mjs";
|
|
3
|
+
import { s as SqlStorage } from "./sql-storage-p-Wzt_MO.mjs";
|
|
5
4
|
import { AnyEntityKindDescriptor } from "@prisma-next/framework-components/ir";
|
|
5
|
+
import { Type } from "arktype";
|
|
6
6
|
import { Contract } from "@prisma-next/contract/types";
|
|
7
7
|
|
|
8
8
|
//#region src/ir/storage-entry-schemas.d.ts
|
|
@@ -62,6 +62,7 @@ declare const StorageTableSchema: import("arktype/internal/variants/object.ts").
|
|
|
62
62
|
nativeType: string;
|
|
63
63
|
codecId: string;
|
|
64
64
|
nullable: boolean;
|
|
65
|
+
many?: boolean;
|
|
65
66
|
typeParams?: Record<string, unknown>;
|
|
66
67
|
typeRef?: string;
|
|
67
68
|
default?: ColumnDefaultLiteral | ColumnDefaultFunction;
|
|
@@ -133,13 +134,15 @@ declare function createSqlStorageSchema(kinds: ReadonlyMap<string, AnyEntityKind
|
|
|
133
134
|
*/
|
|
134
135
|
declare function createSqlContractSchema(kinds: ReadonlyMap<string, AnyEntityKindDescriptor>): Type<unknown>;
|
|
135
136
|
/**
|
|
136
|
-
* Validates the structural shape of SqlStorage using Arktype.
|
|
137
|
+
* Validates the structural shape of SqlStorage using Arktype. Pure
|
|
138
|
+
* structural check: namespace IR is never materialized here (that needs
|
|
139
|
+
* a target concretion via the serializer hydration path), so this throws
|
|
140
|
+
* on invalid input and constructs nothing.
|
|
137
141
|
*
|
|
138
142
|
* @param value - The storage value to validate
|
|
139
|
-
* @returns The validated storage if structure is valid
|
|
140
143
|
* @throws Error if the storage structure is invalid
|
|
141
144
|
*/
|
|
142
|
-
declare function validateStorage(value: unknown):
|
|
145
|
+
declare function validateStorage(value: unknown): void;
|
|
143
146
|
declare function validateModel(value: unknown): unknown;
|
|
144
147
|
/**
|
|
145
148
|
* Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/ir/storage-entry-schemas.ts","../src/validators.ts"],"mappings":";;;;;;;;KAMK,oBAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,8BAAmC,MAAM;AAAA;AAAA,KAE/C,qBAAA;EAAA,SAAmC,IAAA;EAAA,SAA2B,UAAU;AAAA;AAAA,cAMhE,0BAAA,gDAA0B,UAAA,CAAA,oBAAA;AAAA,cAK1B,2BAAA,gDAA2B,UAAA,CAAA,qBAAA;AAAA,cAK3B,mBAAA,gDAAmB,UAAA,CAAA,oBAAA,GAAA,qBAAA;;;;AAlBoB;AAAA;
|
|
1
|
+
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/ir/storage-entry-schemas.ts","../src/validators.ts"],"mappings":";;;;;;;;KAMK,oBAAA;EAAA,SACM,IAAA;EAAA,SACA,KAAA,8BAAmC,MAAM;AAAA;AAAA,KAE/C,qBAAA;EAAA,SAAmC,IAAA;EAAA,SAA2B,UAAU;AAAA;AAAA,cAMhE,0BAAA,gDAA0B,UAAA,CAAA,oBAAA;AAAA,cAK1B,2BAAA,gDAA2B,UAAA,CAAA,qBAAA;AAAA,cAK3B,mBAAA,gDAAmB,UAAA,CAAA,oBAAA,GAAA,qBAAA;;;;AAlBoB;AAAA;cAmDvC,qBAAA,gDAAqB,UAAA;;gDAKhC,MAAA;AAAA;AAAA,cAYW,WAAA,gDAAW,UAAA;;;;YAKtB,MAAA;AAAA;AAAA,cAEW,yBAAA,gDAAyB,UAAA;;;;;;cAQzB,sBAAA,gDAAsB,UAAA;;;;;cAOtB,uBAAA,gDAAuB,UAAA,CAAA,iBAAA;AAAA,cAIvB,gBAAA,gDAAgB,UAAA,CAAA,eAAA;AAAA,cAQhB,qBAAA,gDAAqB,UAAA;;;;;;;;;;;cAOrB,kBAAA,gDAAkB,UAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cCblB,kBAAA,gDAAkB,UAAA;;;;mDAS7B,MAAA;EAAA;AAAA;;ADzGkD;AAAA;;;;AAEyB;AAM7E;iBCuHgB,0BAAA,CACd,KAAA,EAAO,WAAA,SAAoB,uBAAA,IAC1B,IAAA;;;ADzHoC;AAKvC;;;iBCgKgB,sBAAA,CACd,KAAA,EAAO,WAAA,SAAoB,uBAAA,IAC1B,IAAA;ADlKqC;AAKxC;;;;AALwC,iBC0TxB,uBAAA,CACd,KAAA,EAAO,WAAA,SAAoB,uBAAA,IAC1B,IAAA;;;;ADvT6B;AAiChC;;;;;iBC4TgB,eAAA,CAAgB,KAAc;AAAA,iBAQ9B,aAAA,CAAc,KAAc;;;;ADnT5C;;;;;;;;;;iBCiXgB,wBAAA,CAAyB,OAAmB,EAAV,UAAU;;AD1W5D;;;;;iBC6gBgB,8BAAA,CAA+B,QAAA,EAAU,QAAQ,CAAC,UAAA;;;;;;ADrgBlE;iBCikBgB,6BAAA,CAA8B,QAAA,EAAU,QAAQ,CAAC,UAAA;AAAA,UAwGhD,+BAAA;EDpqB0B;;;;;;;AAE3C;EAF2C,SC6qBhC,cAAA,GAAiB,IAAI;AAAA;;AD3qBI;AAIpC;;;;AAA6B;AAQ7B;iBC0qBgB,wBAAA,WAAmC,QAAA,CAAS,UAAA,GAC1D,KAAA,WACA,OAAA,GAAU,+BAAA,GACT,CAAA"}
|
package/dist/validators.mjs
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { a as ColumnDefaultFunctionSchema, c as ForeignKeyReferenceSchema, d as IndexSchema, f as ReferentialActionSchema, i as CheckConstraintSchema, l as ForeignKeySchema, m as StorageValueSetSchema, o as ColumnDefaultLiteralSchema, p as StorageTableSchema, s as ColumnDefaultSchema, t as composeSqlEntityKinds, u as ForeignKeySourceSchema } from "./entity-kinds-CVg6HzG2.mjs";
|
|
2
|
+
import { isPlainRecord } from "@prisma-next/framework-components/ir";
|
|
3
3
|
import { type } from "arktype";
|
|
4
|
-
import { UNBOUND_NAMESPACE_ID, isPlainRecord } from "@prisma-next/framework-components/ir";
|
|
5
4
|
import { CrossReferenceSchema } from "@prisma-next/contract/types";
|
|
6
|
-
import { blindCast } from "@prisma-next/utils/casts";
|
|
7
5
|
import { ContractValidationError } from "@prisma-next/contract/contract-validation-error";
|
|
8
6
|
import { validateContractDomain } from "@prisma-next/contract/validate-domain";
|
|
7
|
+
import { blindCast } from "@prisma-next/utils/casts";
|
|
9
8
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
9
|
//#region src/validators.ts
|
|
11
10
|
const generatorKindSchema = type("'generator'");
|
|
@@ -236,10 +235,12 @@ function createSqlContractSchema(kinds) {
|
|
|
236
235
|
}
|
|
237
236
|
const SqlContractSchema = createSqlContractSchema(DEFAULT_SQL_KINDS);
|
|
238
237
|
/**
|
|
239
|
-
* Validates the structural shape of SqlStorage using Arktype.
|
|
238
|
+
* Validates the structural shape of SqlStorage using Arktype. Pure
|
|
239
|
+
* structural check: namespace IR is never materialized here (that needs
|
|
240
|
+
* a target concretion via the serializer hydration path), so this throws
|
|
241
|
+
* on invalid input and constructs nothing.
|
|
240
242
|
*
|
|
241
243
|
* @param value - The storage value to validate
|
|
242
|
-
* @returns The validated storage if structure is valid
|
|
243
244
|
* @throws Error if the storage structure is invalid
|
|
244
245
|
*/
|
|
245
246
|
function validateStorage(value) {
|
|
@@ -248,17 +249,6 @@ function validateStorage(value) {
|
|
|
248
249
|
const messages = result.map((p) => p.message).join("; ");
|
|
249
250
|
throw new Error(`Storage validation failed: ${messages}`);
|
|
250
251
|
}
|
|
251
|
-
const validated = blindCast(result);
|
|
252
|
-
const namespaces = buildSqlNamespaceMap(validated.namespaces ?? {});
|
|
253
|
-
const unbound = namespaces[UNBOUND_NAMESPACE_ID] ?? SqlUnboundNamespace.instance;
|
|
254
|
-
return new SqlStorage({
|
|
255
|
-
storageHash: validated.storageHash,
|
|
256
|
-
...ifDefined("types", validated.types),
|
|
257
|
-
namespaces: {
|
|
258
|
-
...namespaces,
|
|
259
|
-
[UNBOUND_NAMESPACE_ID]: unbound
|
|
260
|
-
}
|
|
261
|
-
});
|
|
262
252
|
}
|
|
263
253
|
function validateModel(value) {
|
|
264
254
|
const result = ModelSchema(value);
|
|
@@ -348,9 +338,7 @@ function validateStorageSemantics(storage) {
|
|
|
348
338
|
source: fk.source,
|
|
349
339
|
target: fk.target,
|
|
350
340
|
onDelete: fk.onDelete ?? null,
|
|
351
|
-
onUpdate: fk.onUpdate ?? null
|
|
352
|
-
constraint: fk.constraint,
|
|
353
|
-
index: fk.index
|
|
341
|
+
onUpdate: fk.onUpdate ?? null
|
|
354
342
|
});
|
|
355
343
|
if (seenForeignKeyDefinitions.has(signature)) {
|
|
356
344
|
errors.push(`Namespace "${namespaceId}" table "${tableName}": duplicate foreign key definition on columns [${fk.source.columns.join(", ")}]`);
|
|
@@ -400,7 +388,7 @@ function validateModelStorageReferences(contract) {
|
|
|
400
388
|
const table = rawTable;
|
|
401
389
|
const columnNames = new Set(Object.keys(table.columns));
|
|
402
390
|
for (const [fieldName, field] of Object.entries(model.storage.fields)) if (!columnNames.has(field.column)) throw new ContractValidationError(`Model "${qualifiedName}" field "${fieldName}" references non-existent column "${field.column}" in table "${storageTable}"`, "storage");
|
|
403
|
-
const JSON_NATIVE_TYPES = new Set(["json", "jsonb"]);
|
|
391
|
+
const JSON_NATIVE_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]);
|
|
404
392
|
for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) {
|
|
405
393
|
if (domainField.type?.kind !== "valueObject") continue;
|
|
406
394
|
const storageField = model.storage.fields[fieldName];
|
|
@@ -463,8 +451,110 @@ function validateSqlContractFully(value, options) {
|
|
|
463
451
|
const semanticErrors = validateStorageSemantics(validated.storage);
|
|
464
452
|
if (semanticErrors.length > 0) throw new ContractValidationError(`Contract semantic validation failed: ${semanticErrors.join("; ")}`, "storage");
|
|
465
453
|
validateModelStorageReferences(validated);
|
|
454
|
+
validateRelationThroughConsistency(validated);
|
|
466
455
|
return validated;
|
|
467
456
|
}
|
|
457
|
+
/** Storage column lookup for through-consistency validation. */
|
|
458
|
+
function lookupStorageColumn(contract, namespaceId, tableName, columnName) {
|
|
459
|
+
const rawTable = contract.storage.namespaces[namespaceId]?.entries.table?.[tableName];
|
|
460
|
+
if (rawTable === void 0) return;
|
|
461
|
+
return blindCast(rawTable).columns[columnName];
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Two storage columns share a type when their `nativeType` and `typeParams`
|
|
465
|
+
* match. The contract is canonicalized, so `typeParams` key order is stable and
|
|
466
|
+
* a JSON comparison is exact. `codecId` and `nullable` are intentionally not
|
|
467
|
+
* compared: they do not change the database-level type that governs a join.
|
|
468
|
+
*/
|
|
469
|
+
function sameStorageType(a, b) {
|
|
470
|
+
return a.nativeType === b.nativeType && JSON.stringify(a.typeParams ?? null) === JSON.stringify(b.typeParams ?? null);
|
|
471
|
+
}
|
|
472
|
+
function describeColumnType(column) {
|
|
473
|
+
return column.typeParams === void 0 ? column.nativeType : `${column.nativeType} ${JSON.stringify(column.typeParams)}`;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Validates one side of an N:M join: the junction columns and the model
|
|
477
|
+
* columns they pair against positionally must be equal in number, exist in
|
|
478
|
+
* their tables, and share the same storage type (`nativeType` + `typeParams`).
|
|
479
|
+
* The junction's storage foreign keys already guarantee this for user-declared
|
|
480
|
+
* FK constraints, but `through` is a logical descriptor never tied to them by
|
|
481
|
+
* the rest of validation — and the TS builder accepts explicit join columns
|
|
482
|
+
* without requiring a junction FK at all — so this checks the columns directly
|
|
483
|
+
* against storage, one path regardless of how the junction was authored.
|
|
484
|
+
*
|
|
485
|
+
* Joined columns must be the *same* storage type, not merely compatible:
|
|
486
|
+
* relying on implicit conversion (e.g. `text`↔`character`) is unsafe on writes
|
|
487
|
+
* — `character(n)` space-padding makes such coercions non-associative — and no
|
|
488
|
+
* ADR sanctions heterogeneous junction columns. Equality is the conservative
|
|
489
|
+
* default; it can be relaxed deliberately if a real use case ever appears.
|
|
490
|
+
*/
|
|
491
|
+
function validateThroughJoinSide(input) {
|
|
492
|
+
const fail = (detail) => new ContractValidationError(`Many-to-many relation "${input.qualifiedName}" ${detail}`, "storage");
|
|
493
|
+
if (input.junctionColumns.length !== input.modelColumns.length) throw fail(`pairs ${input.junctionColumnsLabel} (${input.junctionColumns.length}) with ${input.modelColumnsLabel} (${input.modelColumns.length}) of differing length; they join positionally and must match.`);
|
|
494
|
+
for (const [index, junctionColumnName] of input.junctionColumns.entries()) {
|
|
495
|
+
const modelColumnRef = input.modelColumns[index];
|
|
496
|
+
if (modelColumnRef === void 0) continue;
|
|
497
|
+
const junctionColumn = lookupStorageColumn(input.contract, input.junctionNamespaceId, input.junctionTable, junctionColumnName);
|
|
498
|
+
if (junctionColumn === void 0) throw fail(`${input.junctionColumnsLabel} references column "${junctionColumnName}" absent from junction table "${input.junctionNamespaceId}.${input.junctionTable}".`);
|
|
499
|
+
const model = input.model;
|
|
500
|
+
if (model === void 0) continue;
|
|
501
|
+
let modelColumnName = modelColumnRef;
|
|
502
|
+
if (model.fieldToColumn !== void 0) {
|
|
503
|
+
const mapped = model.fieldToColumn[modelColumnRef];
|
|
504
|
+
if (mapped === void 0) throw fail(`${input.modelColumnsLabel} references field "${modelColumnRef}" absent from model on table "${model.namespaceId}.${model.table}".`);
|
|
505
|
+
modelColumnName = mapped.column;
|
|
506
|
+
}
|
|
507
|
+
const modelColumn = lookupStorageColumn(input.contract, model.namespaceId, model.table, modelColumnName);
|
|
508
|
+
if (modelColumn === void 0) throw fail(`${input.modelColumnsLabel} references column "${modelColumnName}" absent from table "${model.namespaceId}.${model.table}".`);
|
|
509
|
+
if (!sameStorageType(junctionColumn, modelColumn)) throw fail(`joins "${input.junctionTable}.${junctionColumnName}" (${describeColumnType(junctionColumn)}) with "${model.table}.${modelColumnName}" (${describeColumnType(modelColumn)}) of differing storage type; junction columns must match the type of the column they reference.`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Validates that every N:M relation's `through` descriptor is consistent with
|
|
514
|
+
* the storage columns it joins: both join sides match in column count,
|
|
515
|
+
* reference columns that exist in their tables, and pair columns of the same
|
|
516
|
+
* storage type. Without this, a `through` that disagrees with storage surfaces
|
|
517
|
+
* as a silently wrong JOIN at query time rather than a validation error here.
|
|
518
|
+
*/
|
|
519
|
+
function validateRelationThroughConsistency(contract) {
|
|
520
|
+
for (const [namespaceId, namespace] of Object.entries(contract.domain.namespaces)) for (const [modelName, model] of Object.entries(namespace.models)) for (const [relationName, relation] of Object.entries(model.relations)) {
|
|
521
|
+
if (relation.cardinality !== "N:M") continue;
|
|
522
|
+
const qualifiedName = `${namespaceId}.${modelName}.${relationName}`;
|
|
523
|
+
const { on, through } = relation;
|
|
524
|
+
const modelStorage = blindCast(model.storage);
|
|
525
|
+
validateThroughJoinSide({
|
|
526
|
+
contract,
|
|
527
|
+
qualifiedName,
|
|
528
|
+
modelColumns: on.localFields,
|
|
529
|
+
modelColumnsLabel: "on.localFields",
|
|
530
|
+
model: {
|
|
531
|
+
namespaceId,
|
|
532
|
+
table: modelStorage.table,
|
|
533
|
+
fieldToColumn: modelStorage.fields
|
|
534
|
+
},
|
|
535
|
+
junctionColumns: through.parentColumns,
|
|
536
|
+
junctionColumnsLabel: "through.parentColumns",
|
|
537
|
+
junctionNamespaceId: through.namespaceId,
|
|
538
|
+
junctionTable: through.table
|
|
539
|
+
});
|
|
540
|
+
const targetModel = relation.to.space === void 0 ? contract.domain.namespaces[relation.to.namespace]?.models[relation.to.model] : void 0;
|
|
541
|
+
const targetModelSide = targetModel === void 0 ? void 0 : {
|
|
542
|
+
namespaceId: relation.to.namespace,
|
|
543
|
+
table: blindCast(targetModel.storage).table
|
|
544
|
+
};
|
|
545
|
+
validateThroughJoinSide({
|
|
546
|
+
contract,
|
|
547
|
+
qualifiedName,
|
|
548
|
+
modelColumns: through.targetColumns,
|
|
549
|
+
modelColumnsLabel: "through.targetColumns",
|
|
550
|
+
...ifDefined("model", targetModelSide),
|
|
551
|
+
junctionColumns: through.childColumns,
|
|
552
|
+
junctionColumnsLabel: "through.childColumns",
|
|
553
|
+
junctionNamespaceId: through.namespaceId,
|
|
554
|
+
junctionTable: through.table
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
}
|
|
468
558
|
//#endregion
|
|
469
559
|
export { CheckConstraintSchema, ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ContractEnumSchema, ForeignKeyReferenceSchema, ForeignKeySchema, ForeignKeySourceSchema, IndexSchema, ReferentialActionSchema, StorageTableSchema, StorageValueSetSchema, createNamespaceEntrySchema, createSqlContractSchema, createSqlStorageSchema, validateModel, validateModelStorageReferences, validateSqlContractFully, validateSqlStorageConsistency, validateStorage, validateStorageSemantics };
|
|
470
560
|
|