@prisma-next/sql-contract
Advanced tools
| import { s as SqlStorage } from "./sql-storage-Dt5ipcRl.mjs"; | ||
| import { DefaultNamespaceEntries, NamespacedEntities, SingleNamespaceView } from "@prisma-next/framework-components/ir"; | ||
| import { Contract } from "@prisma-next/contract/types"; | ||
| //#region src/contract-view.d.ts | ||
| /** | ||
| * The SQL family's statically-named built-in entity kinds. `table` and | ||
| * `valueSet` are promoted to top-level view accessors; pack-contributed kinds | ||
| * (e.g. `policy`) stay under `.entries`. | ||
| */ | ||
| declare const SQL_BUILTIN_KINDS: readonly ["table", "valueSet"]; | ||
| type SqlBuiltinKind = (typeof SQL_BUILTIN_KINDS)[number]; | ||
| type SqlEntries<TContract extends Contract<SqlStorage>> = DefaultNamespaceEntries<TContract['storage']>; | ||
| /** | ||
| * The single-namespace SQL accessors: `table`/`valueSet` top-level, pack kinds | ||
| * under `entries`. A target that never emits a built-in kind (SQLite has | ||
| * `sql.enums: false`, so it emits no `valueSet`) resolves that slot to an empty | ||
| * map. | ||
| */ | ||
| type SqlSingleNamespaceAccessors<TContract extends Contract<SqlStorage>> = SingleNamespaceView<SqlEntries<TContract>, SqlBuiltinKind>; | ||
| /** | ||
| * Single-namespace SQL view: the deserialized contract intersected with the | ||
| * by-name accessors, so the value is substitutable for `Contract` while also | ||
| * exposing: | ||
| * - `view.table.<name>` / `view.valueSet.<name>` — built-in kinds, sole | ||
| * namespace unwrapped to the root; pack kinds under `view.entries.<kind>`. | ||
| * - `view.namespace.<id>` — the namespace-keyed entity map (SQLite's sole | ||
| * namespace is `__unbound__`). Mirrors the runtime `db.enums` pattern. | ||
| */ | ||
| type SqlSingleNamespaceView<TContract extends Contract<SqlStorage>> = TContract & SqlSingleNamespaceAccessors<TContract> & { | ||
| readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>; | ||
| }; | ||
| /** | ||
| * Builds the single-namespace SQL view: unwraps the sole namespace's SQL | ||
| * built-in kinds (`table`, `valueSet`) to the root, attaches the namespace-keyed | ||
| * `namespace` map, and layers both over the deserialized contract. Targets with | ||
| * one default namespace (SQLite) call this directly; Postgres qualifies by | ||
| * schema. | ||
| */ | ||
| declare function buildSqlSingleNamespaceView<TContract extends Contract<SqlStorage>>(contract: TContract): SqlSingleNamespaceView<TContract>; | ||
| /** | ||
| * Schema-qualified SQL view: the deserialized contract intersected with a single | ||
| * `view.namespace.<id>` member — every schema reached by raw id | ||
| * (`view.namespace.public.table.users`), mirroring the runtime `db.enums.<ns>` | ||
| * keying exactly (the default schema keeps its literal `__unbound__` id). There | ||
| * is NO root schema-name promotion, so there is no collision with contract | ||
| * envelope fields — `view.storage` is always the contract's `storage`. Postgres | ||
| * uses this; SQLite (single default namespace) uses | ||
| * {@link buildSqlSingleNamespaceView}. | ||
| */ | ||
| type SqlSchemaQualifiedView<TContract extends Contract<SqlStorage>> = TContract & { | ||
| readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>; | ||
| }; | ||
| /** | ||
| * Builds the schema-qualified SQL view: attaches the namespace-keyed `namespace` | ||
| * map over the deserialized contract. Postgres uses this. | ||
| */ | ||
| declare function buildSqlSchemaQualifiedView<TContract extends Contract<SqlStorage>>(contract: TContract): SqlSchemaQualifiedView<TContract>; | ||
| //#endregion | ||
| export { SQL_BUILTIN_KINDS, type SqlBuiltinKind, type SqlSchemaQualifiedView, type SqlSingleNamespaceAccessors, type SqlSingleNamespaceView, buildSqlSchemaQualifiedView, buildSqlSingleNamespaceView }; | ||
| //# sourceMappingURL=contract-view.d.mts.map |
| {"version":3,"file":"contract-view.d.mts","names":[],"sources":["../src/contract-view.ts"],"mappings":";;;;;;;AAeA;;;cAAa,iBAAA;AAAA,KACD,cAAA,WAAyB,iBAAiB;AAAA,KAEjD,UAAA,mBAA6B,QAAA,CAAS,UAAA,KAAe,uBAAA,CACxD,SAAA;;;;AAHoD;AAAU;;KAYpD,2BAAA,mBAA8C,QAAA,CAAS,UAAA,KACjE,mBAAA,CAAoB,UAAA,CAAW,SAAA,GAAY,cAAA;;;;;;;;;;KAWjC,sBAAA,mBAAyC,QAAA,CAAS,UAAA,KAAe,SAAA,GAC3E,2BAAA,CAA4B,SAAA;EAAA,SACjB,SAAA,EAAW,kBAAA,CAAmB,SAAA,aAAsB,cAAA;AAAA;AAvBtD;AASX;;;;;;AATW,iBAiCK,2BAAA,mBAA8C,QAAA,CAAS,UAAA,GACrE,QAAA,EAAU,SAAA,GACT,sBAAA,CAAuB,SAAA;;;;;;;;;;;KAyBd,sBAAA,mBAAyC,QAAA,CAAS,UAAA,KAAe,SAAA;EAAA,SAClE,SAAA,EAAW,kBAAA,CAAmB,SAAA,aAAsB,cAAA;AAAA;AAxC/D;;;;AAAA,iBA+CgB,2BAAA,mBAA8C,QAAA,CAAS,UAAA,GACrE,QAAA,EAAU,SAAA,GACT,sBAAA,CAAuB,SAAA"} |
| import { buildNamespacedEntities, buildSingleNamespaceView } from "@prisma-next/framework-components/ir"; | ||
| //#region src/contract-view.ts | ||
| /** | ||
| * The SQL family's statically-named built-in entity kinds. `table` and | ||
| * `valueSet` are promoted to top-level view accessors; pack-contributed kinds | ||
| * (e.g. `policy`) stay under `.entries`. | ||
| */ | ||
| const SQL_BUILTIN_KINDS = ["table", "valueSet"]; | ||
| /** | ||
| * Builds the single-namespace SQL view: unwraps the sole namespace's SQL | ||
| * built-in kinds (`table`, `valueSet`) to the root, attaches the namespace-keyed | ||
| * `namespace` map, and layers both over the deserialized contract. Targets with | ||
| * one default namespace (SQLite) call this directly; Postgres qualifies by | ||
| * schema. | ||
| */ | ||
| function buildSqlSingleNamespaceView(contract) { | ||
| const rootAccessors = buildSingleNamespaceView(contract.storage, SQL_BUILTIN_KINDS); | ||
| const namespace = buildNamespacedEntities(contract.storage, SQL_BUILTIN_KINDS); | ||
| return { | ||
| ...contract, | ||
| ...rootAccessors, | ||
| namespace | ||
| }; | ||
| } | ||
| /** | ||
| * Builds the schema-qualified SQL view: attaches the namespace-keyed `namespace` | ||
| * map over the deserialized contract. Postgres uses this. | ||
| */ | ||
| function buildSqlSchemaQualifiedView(contract) { | ||
| const namespace = buildNamespacedEntities(contract.storage, SQL_BUILTIN_KINDS); | ||
| return { | ||
| ...contract, | ||
| namespace | ||
| }; | ||
| } | ||
| //#endregion | ||
| export { SQL_BUILTIN_KINDS, buildSqlSchemaQualifiedView, buildSqlSingleNamespaceView }; | ||
| //# sourceMappingURL=contract-view.mjs.map |
| {"version":3,"file":"contract-view.mjs","names":[],"sources":["../src/contract-view.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n buildNamespacedEntities,\n buildSingleNamespaceView,\n type DefaultNamespaceEntries,\n type NamespacedEntities,\n type SingleNamespaceView,\n} from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from './ir/sql-storage';\n\n/**\n * The SQL family's statically-named built-in entity kinds. `table` and\n * `valueSet` are promoted to top-level view accessors; pack-contributed kinds\n * (e.g. `policy`) stay under `.entries`.\n */\nexport const SQL_BUILTIN_KINDS = ['table', 'valueSet'] as const;\nexport type SqlBuiltinKind = (typeof SQL_BUILTIN_KINDS)[number];\n\ntype SqlEntries<TContract extends Contract<SqlStorage>> = DefaultNamespaceEntries<\n TContract['storage']\n>;\n\n/**\n * The single-namespace SQL accessors: `table`/`valueSet` top-level, pack kinds\n * under `entries`. A target that never emits a built-in kind (SQLite has\n * `sql.enums: false`, so it emits no `valueSet`) resolves that slot to an empty\n * map.\n */\nexport type SqlSingleNamespaceAccessors<TContract extends Contract<SqlStorage>> =\n SingleNamespaceView<SqlEntries<TContract>, SqlBuiltinKind>;\n\n/**\n * Single-namespace SQL view: the deserialized contract intersected with the\n * by-name accessors, so the value is substitutable for `Contract` while also\n * exposing:\n * - `view.table.<name>` / `view.valueSet.<name>` — built-in kinds, sole\n * namespace unwrapped to the root; pack kinds under `view.entries.<kind>`.\n * - `view.namespace.<id>` — the namespace-keyed entity map (SQLite's sole\n * namespace is `__unbound__`). Mirrors the runtime `db.enums` pattern.\n */\nexport type SqlSingleNamespaceView<TContract extends Contract<SqlStorage>> = TContract &\n SqlSingleNamespaceAccessors<TContract> & {\n readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>;\n };\n\n/**\n * Builds the single-namespace SQL view: unwraps the sole namespace's SQL\n * built-in kinds (`table`, `valueSet`) to the root, attaches the namespace-keyed\n * `namespace` map, and layers both over the deserialized contract. Targets with\n * one default namespace (SQLite) call this directly; Postgres qualifies by\n * schema.\n */\nexport function buildSqlSingleNamespaceView<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n): SqlSingleNamespaceView<TContract> {\n const rootAccessors = buildSingleNamespaceView<SqlSingleNamespaceAccessors<TContract>>(\n contract.storage,\n SQL_BUILTIN_KINDS,\n );\n const namespace = buildNamespacedEntities<\n NamespacedEntities<TContract['storage'], SqlBuiltinKind>\n >(contract.storage, SQL_BUILTIN_KINDS);\n return {\n ...contract,\n ...rootAccessors,\n namespace,\n };\n}\n\n/**\n * Schema-qualified SQL view: the deserialized contract intersected with a single\n * `view.namespace.<id>` member — every schema reached by raw id\n * (`view.namespace.public.table.users`), mirroring the runtime `db.enums.<ns>`\n * keying exactly (the default schema keeps its literal `__unbound__` id). There\n * is NO root schema-name promotion, so there is no collision with contract\n * envelope fields — `view.storage` is always the contract's `storage`. Postgres\n * uses this; SQLite (single default namespace) uses\n * {@link buildSqlSingleNamespaceView}.\n */\nexport type SqlSchemaQualifiedView<TContract extends Contract<SqlStorage>> = TContract & {\n readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>;\n};\n\n/**\n * Builds the schema-qualified SQL view: attaches the namespace-keyed `namespace`\n * map over the deserialized contract. Postgres uses this.\n */\nexport function buildSqlSchemaQualifiedView<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n): SqlSchemaQualifiedView<TContract> {\n const namespace = buildNamespacedEntities<\n NamespacedEntities<TContract['storage'], SqlBuiltinKind>\n >(contract.storage, SQL_BUILTIN_KINDS);\n return {\n ...contract,\n namespace,\n };\n}\n"],"mappings":";;;;;;;AAeA,MAAa,oBAAoB,CAAC,SAAS,UAAU;;;;;;;;AAqCrD,SAAgB,4BACd,UACmC;CACnC,MAAM,gBAAgB,yBACpB,SAAS,SACT,iBACF;CACA,MAAM,YAAY,wBAEhB,SAAS,SAAS,iBAAiB;CACrC,OAAO;EACL,GAAG;EACH,GAAG;EACH;CACF;AACF;;;;;AAoBA,SAAgB,4BACd,UACmC;CACnC,MAAM,YAAY,wBAEhB,SAAS,SAAS,iBAAiB;CACrC,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| //#region src/entity-handle-lowering-hook.d.ts | ||
| /** | ||
| * SQL-family extension to the pack authoring contributions: a pack whose | ||
| * `entityTypes` registers entity kinds may implement a batch lowering hook | ||
| * that turns author-declared pack-entity handles (the generic `entities` | ||
| * list on the TS contract input) into `entries` rows. | ||
| * | ||
| * The generic contract build (`contract-ts`) owns the kind-agnostic walk: it | ||
| * groups handles by the pack that registered each `entityKind`, resolves | ||
| * each handle's declared model refs to storage table coordinates using the | ||
| * same model→table maps the relation lowering uses, and calls the owning | ||
| * pack's hook once with all of its claimed handles — batch, so the hook's | ||
| * diagnostics can see sibling handles. Neither the walk nor these types name | ||
| * any specific entity kind. | ||
| * | ||
| * SQL-family concept — the resolved-ref shape is a table coordinate, so the | ||
| * hook lives here beside {@link ../value-set-derivation-hook} instead of on | ||
| * the framework contributions type. | ||
| */ | ||
| /** | ||
| * An authored pack-entity handle: branded by the `entityKind` its owning | ||
| * pack registered, optionally declaring model refs under `refs` (actual | ||
| * model-handle objects, resolved by the generic walk before lowering). | ||
| */ | ||
| interface PackEntityHandle { | ||
| readonly entityKind: string; | ||
| readonly refs?: Readonly<Record<string, unknown>>; | ||
| } | ||
| /** | ||
| * A declared model ref after the generic walk resolved it: a storage table | ||
| * coordinate for a model of this contract, the coordinate plus `spaceId` for | ||
| * a cross-space (extensionModel) handle, or `unresolved` when the handle | ||
| * does not correspond to any model in the contract. `modelName` is carried | ||
| * for diagnostics where the handle declares one. | ||
| */ | ||
| type ResolvedEntityHandleRef = { | ||
| readonly kind: 'resolved'; | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly modelName?: string; | ||
| } | { | ||
| readonly kind: 'cross-space'; | ||
| readonly spaceId: string; | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly modelName?: string; | ||
| } | { | ||
| readonly kind: 'unresolved'; | ||
| readonly modelName?: string; | ||
| }; | ||
| /** One claimed handle paired with its resolved declared refs. */ | ||
| interface ResolvedPackEntityHandle { | ||
| readonly handle: PackEntityHandle; | ||
| readonly refs: Readonly<Record<string, ResolvedEntityHandleRef>>; | ||
| } | ||
| interface EntityHandleLoweringInput { | ||
| /** Every handle in the `entities` list whose `entityKind` this pack registered, in authored order. */ | ||
| readonly handles: readonly ResolvedPackEntityHandle[]; | ||
| readonly defaultNamespaceId: string; | ||
| } | ||
| /** One lowered entity row: filed into `storage.namespaces[namespaceId].entries[entityKind][key]`. */ | ||
| interface LoweredPackEntity { | ||
| readonly namespaceId: string; | ||
| readonly entityKind: string; | ||
| readonly key: string; | ||
| readonly entity: unknown; | ||
| } | ||
| interface SqlEntityHandleLoweringContribution { | ||
| /** | ||
| * Method syntax keeps the declaration bivariant, so a pack's concretely | ||
| * typed implementation stays structurally compatible (the same convention | ||
| * as `SqlValueSetDerivingEntityTypeOutput.deriveValueSet`). | ||
| */ | ||
| lowerEntityHandles(input: EntityHandleLoweringInput): readonly LoweredPackEntity[]; | ||
| } | ||
| /** Structural check for {@link SqlEntityHandleLoweringContribution}: no casts. */ | ||
| declare function providesEntityHandleLowering(authoring: unknown): authoring is SqlEntityHandleLoweringContribution; | ||
| /** | ||
| * PSL-side twin of {@link ResolvedEntityHandleRef}: the family interpreter | ||
| * resolves an extension block's descriptor-declared model ref parameters | ||
| * (`{ kind: 'ref', refKind: 'model' }`) to storage table names and annotates | ||
| * the block with this map (keyed by parameter name) before invoking the | ||
| * entity factory. An unresolved required ref is the interpreter's | ||
| * diagnostic; a factory never sees one. | ||
| */ | ||
| type ResolvedPslModelRefs = Readonly<Record<string, { | ||
| readonly tableName: string; | ||
| }>>; | ||
| //#endregion | ||
| export { type EntityHandleLoweringInput, type LoweredPackEntity, type PackEntityHandle, type ResolvedEntityHandleRef, type ResolvedPackEntityHandle, type ResolvedPslModelRefs, type SqlEntityHandleLoweringContribution, providesEntityHandleLowering }; | ||
| //# sourceMappingURL=entity-handle-lowering-hook.d.mts.map |
| {"version":3,"file":"entity-handle-lowering-hook.d.mts","names":[],"sources":["../src/entity-handle-lowering-hook.ts"],"mappings":";;AAwBA;;;;;;;;;AAEiC;AAUjC;;;;;;;;;;;;UAZiB,gBAAA;EAAA,SACN,UAAA;EAAA,SACA,IAAA,GAAO,QAAQ,CAAC,MAAA;AAAA;AA0BH;AAIxB;;;;;;AAJwB,KAhBZ,uBAAA;EAAA,SAEG,IAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;EAAA,SACA,SAAA;AAAA;EAAA,SAGA,IAAA;EAAA,SACA,OAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;EAAA,SACA,SAAA;AAAA;EAAA,SAGA,IAAA;EAAA,SACA,SAAA;AAAA;;UAIE,wBAAA;EAAA,SACN,MAAA,EAAQ,gBAAA;EAAA,SACR,IAAA,EAAM,QAAA,CAAS,MAAA,SAAe,uBAAA;AAAA;AAAA,UAGxB,yBAAA;EAOiB;EAAA,SALvB,OAAA,WAAkB,wBAAwB;EAAA,SAC1C,kBAAA;AAAA;;UAIM,iBAAA;EAAA,SACN,WAAA;EAAA,SACA,UAAA;EAAA,SACA,GAAA;EAAA,SACA,MAAA;AAAA;AAAA,UAGM,mCAAA;EAMiE;;;;;EAAhF,kBAAA,CAAmB,KAAA,EAAO,yBAAA,YAAqC,iBAAiB;AAAA;AAIlF;AAAA,iBAAgB,4BAAA,CACd,SAAA,YACC,SAAA,IAAa,mCAAmC;;;;;;;AAAA;AAgBnD;KAAY,oBAAA,GAAuB,QAAQ,CAAC,MAAA;EAAA,SAA0B,SAAA;AAAA"} |
| //#region src/entity-handle-lowering-hook.ts | ||
| /** Structural check for {@link SqlEntityHandleLoweringContribution}: no casts. */ | ||
| function providesEntityHandleLowering(authoring) { | ||
| if (typeof authoring !== "object" || authoring === null || !("lowerEntityHandles" in authoring)) return false; | ||
| const { lowerEntityHandles } = authoring; | ||
| return typeof lowerEntityHandles === "function"; | ||
| } | ||
| //#endregion | ||
| export { providesEntityHandleLowering }; | ||
| //# sourceMappingURL=entity-handle-lowering-hook.mjs.map |
| {"version":3,"file":"entity-handle-lowering-hook.mjs","names":[],"sources":["../src/entity-handle-lowering-hook.ts"],"sourcesContent":["/**\n * SQL-family extension to the pack authoring contributions: a pack whose\n * `entityTypes` registers entity kinds may implement a batch lowering hook\n * that turns author-declared pack-entity handles (the generic `entities`\n * list on the TS contract input) into `entries` rows.\n *\n * The generic contract build (`contract-ts`) owns the kind-agnostic walk: it\n * groups handles by the pack that registered each `entityKind`, resolves\n * each handle's declared model refs to storage table coordinates using the\n * same model→table maps the relation lowering uses, and calls the owning\n * pack's hook once with all of its claimed handles — batch, so the hook's\n * diagnostics can see sibling handles. Neither the walk nor these types name\n * any specific entity kind.\n *\n * SQL-family concept — the resolved-ref shape is a table coordinate, so the\n * hook lives here beside {@link ../value-set-derivation-hook} instead of on\n * the framework contributions type.\n */\n\n/**\n * An authored pack-entity handle: branded by the `entityKind` its owning\n * pack registered, optionally declaring model refs under `refs` (actual\n * model-handle objects, resolved by the generic walk before lowering).\n */\nexport interface PackEntityHandle {\n readonly entityKind: string;\n readonly refs?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * A declared model ref after the generic walk resolved it: a storage table\n * coordinate for a model of this contract, the coordinate plus `spaceId` for\n * a cross-space (extensionModel) handle, or `unresolved` when the handle\n * does not correspond to any model in the contract. `modelName` is carried\n * for diagnostics where the handle declares one.\n */\nexport type ResolvedEntityHandleRef =\n | {\n readonly kind: 'resolved';\n readonly namespaceId: string;\n readonly tableName: string;\n readonly modelName?: string;\n }\n | {\n readonly kind: 'cross-space';\n readonly spaceId: string;\n readonly namespaceId: string;\n readonly tableName: string;\n readonly modelName?: string;\n }\n | {\n readonly kind: 'unresolved';\n readonly modelName?: string;\n };\n\n/** One claimed handle paired with its resolved declared refs. */\nexport interface ResolvedPackEntityHandle {\n readonly handle: PackEntityHandle;\n readonly refs: Readonly<Record<string, ResolvedEntityHandleRef>>;\n}\n\nexport interface EntityHandleLoweringInput {\n /** Every handle in the `entities` list whose `entityKind` this pack registered, in authored order. */\n readonly handles: readonly ResolvedPackEntityHandle[];\n readonly defaultNamespaceId: string;\n}\n\n/** One lowered entity row: filed into `storage.namespaces[namespaceId].entries[entityKind][key]`. */\nexport interface LoweredPackEntity {\n readonly namespaceId: string;\n readonly entityKind: string;\n readonly key: string;\n readonly entity: unknown;\n}\n\nexport interface SqlEntityHandleLoweringContribution {\n /**\n * Method syntax keeps the declaration bivariant, so a pack's concretely\n * typed implementation stays structurally compatible (the same convention\n * as `SqlValueSetDerivingEntityTypeOutput.deriveValueSet`).\n */\n lowerEntityHandles(input: EntityHandleLoweringInput): readonly LoweredPackEntity[];\n}\n\n/** Structural check for {@link SqlEntityHandleLoweringContribution}: no casts. */\nexport function providesEntityHandleLowering(\n authoring: unknown,\n): authoring is SqlEntityHandleLoweringContribution {\n if (typeof authoring !== 'object' || authoring === null || !('lowerEntityHandles' in authoring)) {\n return false;\n }\n const { lowerEntityHandles } = authoring;\n return typeof lowerEntityHandles === 'function';\n}\n\n/**\n * PSL-side twin of {@link ResolvedEntityHandleRef}: the family interpreter\n * resolves an extension block's descriptor-declared model ref parameters\n * (`{ kind: 'ref', refKind: 'model' }`) to storage table names and annotates\n * the block with this map (keyed by parameter name) before invoking the\n * entity factory. An unresolved required ref is the interpreter's\n * diagnostic; a factory never sees one.\n */\nexport type ResolvedPslModelRefs = Readonly<Record<string, { readonly tableName: string }>>;\n"],"mappings":";;AAqFA,SAAgB,6BACd,WACkD;CAClD,IAAI,OAAO,cAAc,YAAY,cAAc,QAAQ,EAAE,wBAAwB,YACnF,OAAO;CAET,MAAM,EAAE,uBAAuB;CAC/B,OAAO,OAAO,uBAAuB;AACvC"} |
| import { t as StorageTable } from "./storage-table-y6R6pxyI.mjs"; | ||
| import { t as StorageValueSet } from "./storage-value-set-Tx3CFoS_.mjs"; | ||
| import { type } from "arktype"; | ||
| //#region src/ir/storage-entry-schemas.ts | ||
| const literalKindSchema = type("'literal'"); | ||
| const functionKindSchema = type("'function'"); | ||
| const ControlPolicySchema = type("'managed' | 'tolerated' | 'external' | 'observed'"); | ||
| const ColumnDefaultLiteralSchema = type.declare().type({ | ||
| kind: literalKindSchema, | ||
| value: "string | number | boolean | null | unknown[] | Record<string, unknown>" | ||
| }); | ||
| const ColumnDefaultFunctionSchema = type.declare().type({ | ||
| kind: functionKindSchema, | ||
| expression: "string" | ||
| }); | ||
| const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema); | ||
| const StorageValueSetRefSchema = type({ | ||
| plane: "'storage'", | ||
| namespaceId: "string", | ||
| entityKind: "'valueSet'", | ||
| entityName: "string", | ||
| "spaceId?": "string" | ||
| }); | ||
| const StorageColumnSchema = type({ | ||
| "+": "reject", | ||
| nativeType: "string", | ||
| codecId: "string", | ||
| nullable: "boolean", | ||
| "many?": "boolean", | ||
| "typeParams?": "Record<string, unknown>", | ||
| "typeRef?": "string", | ||
| "default?": ColumnDefaultSchema, | ||
| "control?": ControlPolicySchema, | ||
| "valueSet?": StorageValueSetRefSchema | ||
| }).narrow((col, ctx) => { | ||
| if (col.typeParams !== void 0 && col.typeRef !== void 0) return ctx.mustBe("a column with either typeParams or typeRef, not both"); | ||
| return true; | ||
| }); | ||
| /** | ||
| * Storage value-set entry under `storage.namespaces[id].entries.valueSet[name]`. | ||
| * Carries a `kind: 'valueSet'` discriminator (enumerable, survives JSON) and an | ||
| * ordered `values` array of codec-encoded permitted values. | ||
| */ | ||
| const StorageValueSetSchema = type({ | ||
| kind: "'valueSet'", | ||
| values: type("string | number | boolean | null | unknown[] | Record<string, unknown>").array().readonly() | ||
| }); | ||
| const PrimaryKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| const UniqueConstraintSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| const IndexSchema = type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string", | ||
| "type?": "string", | ||
| "options?": "Record<string, unknown>" | ||
| }); | ||
| const ForeignKeyReferenceSchema = type({ | ||
| "+": "reject", | ||
| namespaceId: "string", | ||
| tableName: "string", | ||
| columns: type.string.array().readonly(), | ||
| "spaceId?": "string" | ||
| }); | ||
| const ForeignKeySourceSchema = type({ | ||
| "+": "reject", | ||
| namespaceId: "string", | ||
| tableName: "string", | ||
| columns: type.string.array().readonly() | ||
| }); | ||
| const ReferentialActionSchema = type.declare().type("'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'"); | ||
| const ForeignKeySchema = type.declare().type({ | ||
| source: ForeignKeySourceSchema, | ||
| target: ForeignKeyReferenceSchema, | ||
| "name?": "string", | ||
| "onDelete?": ReferentialActionSchema, | ||
| "onUpdate?": ReferentialActionSchema, | ||
| constraint: "boolean", | ||
| index: "boolean" | ||
| }); | ||
| const CheckConstraintSchema = type({ | ||
| "+": "reject", | ||
| name: "string", | ||
| column: "string", | ||
| valueSet: StorageValueSetRefSchema | ||
| }); | ||
| const StorageTableSchema = type({ | ||
| "+": "reject", | ||
| columns: type({ "[string]": StorageColumnSchema }), | ||
| "primaryKey?": PrimaryKeySchema, | ||
| uniques: UniqueConstraintSchema.array().readonly(), | ||
| indexes: IndexSchema.array().readonly(), | ||
| foreignKeys: ForeignKeySchema.array().readonly(), | ||
| "control?": ControlPolicySchema, | ||
| "checks?": CheckConstraintSchema.array().readonly() | ||
| }); | ||
| //#endregion | ||
| //#region src/entity-kinds.ts | ||
| const tableEntityKind = { | ||
| kind: "table", | ||
| schema: StorageTableSchema, | ||
| construct: (input) => new StorageTable(input) | ||
| }; | ||
| const valueSetEntityKind = { | ||
| kind: "valueSet", | ||
| schema: StorageValueSetSchema, | ||
| construct: (input) => new StorageValueSet(input) | ||
| }; | ||
| /** | ||
| * Assembles the `kind → descriptor` registry for SQL namespaces: the built-in | ||
| * `table` and `valueSet` kinds plus any target `packKinds`. This builds the | ||
| * lookup table — it does not touch contract data. `hydrateNamespaceEntities` | ||
| * later consumes this registry to turn a namespace's raw entries into IR | ||
| * instances, and `createSqlContractSchema` derives validation from the same | ||
| * registry. Throws on a duplicate kind. | ||
| */ | ||
| function composeSqlEntityKinds(packKinds = []) { | ||
| const kinds = /* @__PURE__ */ new Map([["table", tableEntityKind], ["valueSet", valueSetEntityKind]]); | ||
| for (const descriptor of packKinds) { | ||
| if (kinds.has(descriptor.kind)) throw new Error(`composeSqlEntityKinds: duplicate entity kind "${descriptor.kind}" — each kind may be registered only once`); | ||
| kinds.set(descriptor.kind, descriptor); | ||
| } | ||
| return kinds; | ||
| } | ||
| //#endregion | ||
| export { ColumnDefaultFunctionSchema as a, ForeignKeyReferenceSchema as c, IndexSchema as d, ReferentialActionSchema as f, CheckConstraintSchema as i, ForeignKeySchema as l, StorageValueSetSchema as m, tableEntityKind as n, ColumnDefaultLiteralSchema as o, StorageTableSchema as p, valueSetEntityKind as r, ColumnDefaultSchema as s, composeSqlEntityKinds as t, ForeignKeySourceSchema as u }; | ||
| //# sourceMappingURL=entity-kinds-BEPZdFBN.mjs.map |
| {"version":3,"file":"entity-kinds-BEPZdFBN.mjs","names":[],"sources":["../src/ir/storage-entry-schemas.ts","../src/entity-kinds.ts"],"sourcesContent":["import { type Type, type } from 'arktype';\nimport type { ForeignKeyInput, ReferentialAction } from './foreign-key';\nimport type { ForeignKeyReferenceInput } from './foreign-key-reference';\nimport type { PrimaryKeyInput } from './primary-key';\nimport type { UniqueConstraintInput } from './unique-constraint';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\n\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst ControlPolicySchema = type(\"'managed' | 'tolerated' | 'external' | 'observed'\");\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst StorageValueSetRefSchema = type({\n plane: \"'storage'\",\n namespaceId: 'string',\n entityKind: \"'valueSet'\",\n entityName: 'string',\n 'spaceId?': 'string',\n});\n\nconst StorageColumnSchema = type({\n '+': 'reject',\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'many?': 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n 'control?': ControlPolicySchema,\n 'valueSet?': StorageValueSetRefSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\n});\n\n/**\n * Storage value-set entry under `storage.namespaces[id].entries.valueSet[name]`.\n * Carries a `kind: 'valueSet'` discriminator (enumerable, survives JSON) and an\n * ordered `values` array of codec-encoded permitted values.\n */\nexport const StorageValueSetSchema = type({\n kind: \"'valueSet'\",\n values: type('string | number | boolean | null | unknown[] | Record<string, unknown>')\n .array()\n .readonly(),\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKeyInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraintInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nexport const IndexSchema = type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n 'type?': 'string',\n 'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferenceSchema = type({\n '+': 'reject',\n namespaceId: 'string',\n tableName: 'string',\n columns: type.string.array().readonly(),\n 'spaceId?': 'string',\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ForeignKeySourceSchema = type({\n '+': 'reject',\n namespaceId: 'string',\n tableName: 'string',\n columns: type.string.array().readonly(),\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKeyInput>().type({\n source: ForeignKeySourceSchema,\n target: ForeignKeyReferenceSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nexport const CheckConstraintSchema = type({\n '+': 'reject',\n name: 'string',\n column: 'string',\n valueSet: StorageValueSetRefSchema,\n});\n\nexport const StorageTableSchema = type({\n '+': 'reject',\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n 'control?': ControlPolicySchema,\n 'checks?': CheckConstraintSchema.array().readonly(),\n});\n","import type {\n AnyEntityKindDescriptor,\n EntityKindDescriptor,\n} from '@prisma-next/framework-components/ir';\nimport { StorageTableSchema, StorageValueSetSchema } from './ir/storage-entry-schemas';\nimport { StorageTable, type StorageTableInput } from './ir/storage-table';\nimport { StorageValueSet, type StorageValueSetInput } from './ir/storage-value-set';\n\nexport const tableEntityKind: EntityKindDescriptor<StorageTableInput, StorageTable> = {\n kind: 'table',\n schema: StorageTableSchema,\n construct: (input) => new StorageTable(input),\n};\n\nexport const valueSetEntityKind: EntityKindDescriptor<StorageValueSetInput, StorageValueSet> = {\n kind: 'valueSet',\n schema: StorageValueSetSchema,\n construct: (input) => new StorageValueSet(input),\n};\n\n/**\n * Assembles the `kind → descriptor` registry for SQL namespaces: the built-in\n * `table` and `valueSet` kinds plus any target `packKinds`. This builds the\n * lookup table — it does not touch contract data. `hydrateNamespaceEntities`\n * later consumes this registry to turn a namespace's raw entries into IR\n * instances, and `createSqlContractSchema` derives validation from the same\n * registry. Throws on a duplicate kind.\n */\nexport function composeSqlEntityKinds(\n packKinds: readonly AnyEntityKindDescriptor[] = [],\n): ReadonlyMap<string, AnyEntityKindDescriptor> {\n const kinds = new Map<string, AnyEntityKindDescriptor>([\n ['table', tableEntityKind],\n ['valueSet', valueSetEntityKind],\n ]);\n for (const descriptor of packKinds) {\n if (kinds.has(descriptor.kind)) {\n throw new Error(\n `composeSqlEntityKinds: duplicate entity kind \"${descriptor.kind}\" — each kind may be registered only once`,\n );\n }\n kinds.set(descriptor.kind, descriptor);\n }\n return kinds;\n}\n"],"mappings":";;;;AAYA,MAAM,oBAAoB,KAAK,WAAW;AAC1C,MAAM,qBAAqB,KAAK,YAAY;AAC5C,MAAM,sBAAsB,KAAK,mDAAmD;AAEpF,MAAa,6BAA6B,KAAK,QAA8B,CAAC,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;AACT,CAAC;AAED,MAAa,8BAA8B,KAAK,QAA+B,CAAC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;AACd,CAAC;AAED,MAAa,sBAAsB,2BAA2B,GAAG,2BAA2B;AAE5F,MAAM,2BAA2B,KAAK;CACpC,OAAO;CACP,aAAa;CACb,YAAY;CACZ,YAAY;CACZ,YAAY;AACd,CAAC;AAED,MAAM,sBAAsB,KAAK;CAC/B,KAAK;CACL,YAAY;CACZ,SAAS;CACT,UAAU;CACV,SAAS;CACT,eAAe;CACf,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;AACf,CAAC,CAAC,CA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,eAAe;CACf,SAAS,uBAAuB,MAAM,CAAC,CAAC,SAAS;CACjD,SAAS,YAAY,MAAM,CAAC,CAAC,SAAS;CACtC,aAAa,iBAAiB,MAAM,CAAC,CAAC,SAAS;CAC/C,YAAY;CACZ,WAAW,sBAAsB,MAAM,CAAC,CAAC,SAAS;AACpD,CAAC;;;ACxHD,MAAa,kBAAyE;CACpF,MAAM;CACN,QAAQ;CACR,YAAY,UAAU,IAAI,aAAa,KAAK;AAC9C;AAEA,MAAa,qBAAkF;CAC7F,MAAM;CACN,QAAQ;CACR,YAAY,UAAU,IAAI,gBAAgB,KAAK;AACjD;;;;;;;;;AAUA,SAAgB,sBACd,YAAgD,CAAC,GACH;CAC9C,MAAM,wBAAQ,IAAI,IAAqC,CACrD,CAAC,SAAS,eAAe,GACzB,CAAC,YAAY,kBAAkB,CACjC,CAAC;CACD,KAAK,MAAM,cAAc,WAAW;EAClC,IAAI,MAAM,IAAI,WAAW,IAAI,GAC3B,MAAM,IAAI,MACR,iDAAiD,WAAW,KAAK,0CACnE;EAEF,MAAM,IAAI,WAAW,MAAM,UAAU;CACvC;CACA,OAAO;AACT"} |
| import { t as SqlNode } from "./sql-node-V214WXQD.mjs"; | ||
| import { NamespaceId } from "@prisma-next/contract/types"; | ||
| //#region src/ir/foreign-key-reference.d.ts | ||
| /** | ||
| * Input for a foreign-key reference (one side of a foreign-key declaration). | ||
| * | ||
| * When `spaceId` is absent the reference is local — the referenced table lives | ||
| * in the same contract-space. When `spaceId` is present the reference is | ||
| * cross-space — the referenced table lives in a different contract-space | ||
| * identified by `spaceId`. | ||
| * | ||
| * Presence-based discrimination keeps local FK JSON byte-identical to | ||
| * contracts authored before cross-space support was added. | ||
| */ | ||
| interface ForeignKeyReferenceInput { | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly columns: readonly string[]; | ||
| readonly spaceId?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for one side (source or target) of a foreign-key | ||
| * declaration. Carries the full coordinate: namespace, table, and columns. | ||
| * | ||
| * Cross-space discrimination is based on `spaceId` presence: absent means | ||
| * local (same contract-space); present means cross-space (the referenced | ||
| * table lives in the contract-space identified by `spaceId`). | ||
| * | ||
| * For local references `spaceId` is absent from JSON, keeping the serialized | ||
| * shape byte-identical to contracts authored before cross-space support was | ||
| * added. For cross-space references `spaceId` appears in JSON so round-trips | ||
| * are lossless. | ||
| * | ||
| * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir` | ||
| * as the sentinel `namespaceId` for single-namespace (unbound) references. | ||
| */ | ||
| declare class ForeignKeyReference extends SqlNode { | ||
| readonly namespaceId: NamespaceId; | ||
| readonly tableName: string; | ||
| readonly columns: readonly string[]; | ||
| readonly spaceId?: string; | ||
| constructor(input: ForeignKeyReferenceInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/foreign-key.d.ts | ||
| type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'; | ||
| interface ForeignKeyInput { | ||
| readonly source: ForeignKeyReference | ForeignKeyReferenceInput; | ||
| readonly target: ForeignKeyReference | ForeignKeyReferenceInput; | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */ | ||
| readonly constraint: boolean; | ||
| /** Whether to emit a backing index for the FK columns. */ | ||
| readonly index: boolean; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level foreign-key declaration. | ||
| * | ||
| * Each FK carries explicit `source` and `target` {@link ForeignKeyReference} | ||
| * coordinates (namespace, table, columns). For single-namespace contracts the | ||
| * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides. | ||
| * | ||
| * The nested references are normalised to {@link ForeignKeyReference} | ||
| * instances inside the constructor so downstream walks see a uniform AST | ||
| * regardless of whether the input was a JSON literal or an already-constructed | ||
| * class instance. | ||
| */ | ||
| declare class ForeignKey extends SqlNode { | ||
| readonly source: ForeignKeyReference; | ||
| readonly target: ForeignKeyReference; | ||
| readonly constraint: boolean; | ||
| readonly index: boolean; | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| constructor(input: ForeignKeyInput); | ||
| } | ||
| //#endregion | ||
| export { ForeignKeyReferenceInput as a, ForeignKeyReference as i, ForeignKeyInput as n, ReferentialAction as r, ForeignKey as t }; | ||
| //# sourceMappingURL=foreign-key-DM1UTydh.d.mts.map |
| {"version":3,"file":"foreign-key-DM1UTydh.d.mts","names":[],"sources":["../src/ir/foreign-key-reference.ts","../src/ir/foreign-key.ts"],"mappings":";;;;;;AAeA;;;;;;;;;UAAiB,wBAAA;EAAA,SACN,WAAA;EAAA,SACA,SAAA;EAAA,SACA,OAAA;EAAA,SACA,OAAA;AAAA;;;;;;;;;;;;;;AAyBkC;;;cANhC,mBAAA,SAA4B,OAAA;EAAA,SAC9B,WAAA,EAAa,WAAA;EAAA,SACb,SAAA;EAAA,SACA,OAAA;EAAA,SACQ,OAAA;cAEL,KAAA,EAAO,wBAAA;AAAA;;;KCxCT,iBAAA;AAAA,UAEK,eAAA;EAAA,SACN,MAAA,EAAQ,mBAAA,GAAsB,wBAAA;EAAA,SAC9B,MAAA,EAAQ,mBAAA,GAAsB,wBAAA;EAAA,SAC9B,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAA;EDMX;EAAA,SCJA,UAAA;EDMA;EAAA,SCJA,KAAA;AAAA;ADuBX;;;;;;;;;;;;AAAA,cCRa,UAAA,SAAmB,OAAA;EAAA,SACrB,MAAA,EAAQ,mBAAA;EAAA,SACR,MAAA,EAAQ,mBAAA;EAAA,SACR,UAAA;EAAA,SACA,KAAA;EAAA,SACQ,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAA;cAEhB,KAAA,EAAO,eAAA;AAAA"} |
| import { IRNodeBase } from "@prisma-next/framework-components/ir"; | ||
| //#region src/ir/sql-node.d.ts | ||
| /** | ||
| * SQL family IR node base. Carries the family-level `kind` discriminator | ||
| * `'sql'` and inherits the framework's `freezeNode` affordance. | ||
| * | ||
| * Single family-level discriminator (not per-leaf) reflects the fact that | ||
| * SQL IR has no polymorphic dispatch today — verifiers and serializers | ||
| * walk by structural position (`storage.tables[name].columns[name]`), | ||
| * not by inspecting `kind`. The abstract bar for per-leaf discriminators | ||
| * isn't earned until a future polymorphic consumer arrives. | ||
| * | ||
| * `kind` is installed as a non-enumerable own property on every instance, | ||
| * which keeps three things clean simultaneously: | ||
| * | ||
| * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope | ||
| * shape (no `kind` field), so emitted contract.json files and the | ||
| * `validateSqlContractFully` arktype schemas stay unchanged. | ||
| * - Test assertions that use `toEqual({...})` against the pre-lift flat | ||
| * shape continue to pass — only enumerable own properties are | ||
| * compared. | ||
| * - Direct access (`node.kind`) and runtime narrowing | ||
| * (`if (node.kind === 'sql')`) still work, so future polymorphic | ||
| * dispatch can begin reading `kind` without a runtime change. | ||
| * | ||
| * Future per-leaf overrides land cleanly: a class that gains a | ||
| * polymorphic-dispatch consumer (e.g. an enum type instance walked | ||
| * alongside other types) overrides `kind` with its narrower literal | ||
| * at that leaf level. Per-leaf overrides will use enumerable kind | ||
| * (matching the Mongo per-class-discriminator precedent) because they | ||
| * encode dispatch-relevant information that callers need to see in | ||
| * JSON envelopes; the family-level `'sql'` is uniform across all SQL | ||
| * IR and carries no dispatch-relevant information. | ||
| */ | ||
| declare abstract class SqlNode extends IRNodeBase { | ||
| readonly kind?: string; | ||
| constructor(); | ||
| } | ||
| //#endregion | ||
| export { SqlNode as t }; | ||
| //# sourceMappingURL=sql-node-V214WXQD.d.mts.map |
| {"version":3,"file":"sql-node-V214WXQD.d.mts","names":[],"sources":["../src/ir/sql-node.ts"],"mappings":";;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAAsB,OAAA,SAAgB,UAAU;EAAA,SACrC,IAAA"} |
| import { t as SqlNode } from "./sql-node-V214WXQD.mjs"; | ||
| import { t as StorageTable } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { t as StorageValueSet } from "./storage-value-set-D-jww77l.mjs"; | ||
| import { Namespace, NamespaceBase, Storage, StorageType } from "@prisma-next/framework-components/ir"; | ||
| import { StorageHashBase } from "@prisma-next/contract/types"; | ||
| import { AuthoringContributions } from "@prisma-next/framework-components/authoring"; | ||
| //#region src/ir/storage-type-instance.d.ts | ||
| /** | ||
| * Sentinel kind for the legacy codec-triple shape persisted under | ||
| * `SqlStorage.types`. Plain JSON-clean object literals carry this | ||
| * discriminator so the polymorphic slot dispatch can route them down | ||
| * the codec path while target-specific IR class instances (e.g. the | ||
| * Postgres enum class) keep their own narrower `kind` literal. | ||
| */ | ||
| declare const CODEC_INSTANCE_KIND: "codec-instance"; | ||
| /** | ||
| * Structural sub-interface of {@link StorageType} for codec-typed entries | ||
| * in `SqlStorage.types`. These are plain object literals — there is no | ||
| * runtime IR class, the JSON envelope round-trips through the slot | ||
| * unchanged. The `kind: 'codec-instance'` discriminator is the dispatch | ||
| * key that distinguishes codec-typed entries from any class-instance | ||
| * kinds a target pack contributes to the polymorphic slot. | ||
| */ | ||
| interface StorageTypeInstance extends StorageType { | ||
| readonly kind: typeof CODEC_INSTANCE_KIND; | ||
| readonly codecId: string; | ||
| readonly nativeType: string; | ||
| readonly typeParams: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * Construction-time input for a codec-triple entry. Symmetric with the | ||
| * structural runtime shape minus the `kind` discriminator — callers may | ||
| * omit `kind`; the helper {@link toStorageTypeInstance} stamps it on. | ||
| * `typeParams` may be omitted on input; the constructor normalises a | ||
| * missing value to `{}` so the in-memory shape is always present. | ||
| */ | ||
| interface StorageTypeInstanceInput { | ||
| readonly codecId: string; | ||
| readonly nativeType: string; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * Stamp the codec-instance `kind` discriminator on a caller-supplied | ||
| * codec triple. Idempotent: input that already carries the discriminator | ||
| * passes through unchanged. Missing `typeParams` is normalised to `{}`. | ||
| */ | ||
| declare function toStorageTypeInstance(input: StorageTypeInstanceInput): StorageTypeInstance; | ||
| /** | ||
| * Type-guard for codec-typed entries on the polymorphic | ||
| * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from | ||
| * any class-instance kinds a target pack contributes. | ||
| */ | ||
| declare function isStorageTypeInstance(value: unknown): value is StorageTypeInstance; | ||
| //#endregion | ||
| //#region src/ir/sql-storage.d.ts | ||
| /** | ||
| * Polymorphic value type for document-scoped `SqlStorage.types` entries | ||
| * (codec aliases / parameterised native type registrations). | ||
| * | ||
| * Postgres native enum registrations live under the postgres-specific | ||
| * `entries.type` slot on `PostgresSchema` (target layer), not here. | ||
| */ | ||
| type SqlStorageTypeEntry = StorageTypeInstance | StorageTypeInstanceInput; | ||
| interface SqlNamespaceInput { | ||
| readonly id: string; | ||
| readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>; | ||
| } | ||
| /** | ||
| * Target-supplied factory that materializes a `Namespace` from a SQL | ||
| * `SqlNamespaceInput` (used to populate `SqlStorage.namespaces`). | ||
| */ | ||
| type SqlNamespaceFactory = (input: SqlNamespaceInput) => Namespace; | ||
| /** | ||
| * SQL-family extension of the framework `AuthoringContributions`. SQL target | ||
| * packs add a `createNamespace` factory so the PSL/TS authoring paths can | ||
| * materialize namespaces (and merge lowered extension-block entities) without | ||
| * each consumer re-specifying it. The factory is SQL-specific, so it lives here | ||
| * rather than on the framework `AuthoringContributions` base. | ||
| */ | ||
| interface SqlAuthoringContributions extends AuthoringContributions { | ||
| readonly createNamespace?: SqlNamespaceFactory; | ||
| } | ||
| /** | ||
| * Narrows framework `AuthoringContributions` to the SQL-family shape by testing | ||
| * for the SQL-specific `createNamespace` capability. | ||
| */ | ||
| declare function isSqlAuthoringContributions(authoring: AuthoringContributions | undefined): authoring is SqlAuthoringContributions; | ||
| interface SqlStorageInput<THash extends string = string> { | ||
| readonly storageHash: StorageHashBase<THash>; | ||
| readonly types?: Record<string, SqlStorageTypeEntry>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespaceBase>>; | ||
| } | ||
| /** | ||
| * SQL Contract IR root node for the `storage` field. | ||
| * | ||
| * Single concrete family-shared class — both Postgres and SQLite | ||
| * consume this class today. Per-target storage subclasses are | ||
| * introduced when each target's namespace shape earns its | ||
| * target-specific concretion (target-specific derived fields, | ||
| * target-specific storage extensions). | ||
| * | ||
| * Honours the framework `Storage` interface: every SQL IR carries a | ||
| * `namespaces` map keyed by namespace id. Callers must supply fully | ||
| * constructed `Namespace` instances — construction discipline lives | ||
| * in the authoring builders and deserializer hydration paths. | ||
| * | ||
| * The constructor normalises optional `types` into class instances. | ||
| * `types` is polymorphic per Decision 18 Option B: codec-triple inputs | ||
| * are stamped with `kind: 'codec-instance'`; hydration of raw JSON | ||
| * class-instance entries (carrying their narrower `kind` literal) is | ||
| * the per-target serializer's responsibility (so the family base does | ||
| * not import target-specific subclasses). | ||
| */ | ||
| /** | ||
| * The typed `entries` shape for SQL family namespaces. The open dictionary | ||
| * is intersected with optional known-kind maps so that `ns.entries.table` | ||
| * and `ns.entries.valueSet` resolve without a cast, while unknown pack- | ||
| * contributed kinds remain valid (the `Record` part allows any string key). | ||
| */ | ||
| type SqlNamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>> & { | ||
| readonly table?: Readonly<Record<string, StorageTable>>; | ||
| readonly valueSet?: Readonly<Record<string, StorageValueSet>>; | ||
| }; | ||
| /** | ||
| * Structural interface for SQL family namespaces. Generated `.d.ts` contract | ||
| * types satisfy this structurally (no prototype methods). The runtime | ||
| * abstract class `SqlNamespaceBase` extends this. | ||
| * | ||
| * `qualifyTable` and `isUnbound` are optional so JSON-shaped contract types | ||
| * (which carry no methods) are accepted where `SqlNamespace` is required. | ||
| * Hydrated `SqlNamespaceBase` instances always have both. | ||
| */ | ||
| interface SqlNamespace { | ||
| readonly kind: string; | ||
| readonly id: string; | ||
| readonly entries: SqlNamespaceEntries; | ||
| readonly isUnbound?: boolean; | ||
| qualifyTable?(tableName: string): string; | ||
| } | ||
| /** | ||
| * Abstract SQL family namespace base class. Target concretions (`PostgresSchema`, | ||
| * `SqliteDatabase`, …) extend this — it is never instantiated directly. | ||
| * `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]` | ||
| * addresses any entity. | ||
| */ | ||
| declare abstract class SqlNamespaceBase extends NamespaceBase implements SqlNamespace { | ||
| abstract readonly id: string; | ||
| abstract readonly entries: SqlNamespaceEntries; | ||
| abstract qualifyTable(tableName: string): string; | ||
| } | ||
| /** | ||
| * Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks | ||
| * `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it | ||
| * survives duplicate-module boundaries (e.g. dist e2e where the target and | ||
| * the family carry separate copies of `@prisma-next/framework-components`). | ||
| * | ||
| * Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`, | ||
| * `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput` | ||
| * objects (`{ id, entries }`) do not. | ||
| */ | ||
| declare function isMaterializedSqlNamespace(x: unknown): x is SqlNamespaceBase; | ||
| declare class SqlStorage<THash extends string = string> extends SqlNode implements Storage { | ||
| readonly storageHash: StorageHashBase<THash>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespace>>; | ||
| readonly types?: Readonly<Record<string, StorageTypeInstance>>; | ||
| constructor(input: SqlStorageInput<THash>); | ||
| } | ||
| //#endregion | ||
| export { SqlNamespaceFactory as a, SqlStorageInput as c, isSqlAuthoringContributions as d, CODEC_INSTANCE_KIND as f, toStorageTypeInstance as g, isStorageTypeInstance as h, SqlNamespaceEntries as i, SqlStorageTypeEntry as l, StorageTypeInstanceInput as m, SqlNamespace as n, SqlNamespaceInput as o, StorageTypeInstance as p, SqlNamespaceBase as r, SqlStorage as s, SqlAuthoringContributions as t, isMaterializedSqlNamespace as u }; | ||
| //# sourceMappingURL=sql-storage-Dt5ipcRl.d.mts.map |
| {"version":3,"file":"sql-storage-Dt5ipcRl.d.mts","names":[],"sources":["../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts"],"mappings":";;;;;;;;;;;;;;;cASa,mBAAA;;;;AAA+C;AAU5D;;;;UAAiB,mBAAA,SAA4B,WAAA;EAAA,SAClC,IAAA,SAAa,mBAAA;EAAA,SACb,OAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA,EAAY,MAAA;AAAA;;;;;;;AAAM;UAUZ,wBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA,GAAa,MAAM;AAAA;;;;;AAAA;iBAQd,qBAAA,CAAsB,KAAA,EAAO,wBAAA,GAA2B,mBAAmB;;;;;;iBAc3E,qBAAA,CAAsB,KAAA,YAAiB,KAAA,IAAS,mBAAmB;;;;AAjDnF;;;;AAA4D;AAU5D;KCOY,mBAAA,GAAsB,mBAAA,GAAsB,wBAAwB;AAAA,UAE/D,iBAAA;EAAA,SACN,EAAA;EAAA,SACA,OAAA,EAAS,QAAA,CAAS,MAAA,SAAe,QAAA,CAAS,MAAA;AAAA;;;;;KAOzC,mBAAA,IAAuB,KAAA,EAAO,iBAAA,KAAsB,SAAS;;;;;;ADd5C;AAU7B;UCaiB,yBAAA,SAAkC,sBAAsB;EAAA,SAC9D,eAAA,GAAkB,mBAAA;AAAA;;;;;iBAOb,2BAAA,CACd,SAAA,EAAW,sBAAA,eACV,SAAA,IAAa,yBAAyB;AAAA,UAOxB,eAAA;EAAA,SACN,WAAA,EAAa,eAAA,CAAgB,KAAA;EAAA,SAC7B,KAAA,GAAQ,MAAA,SAAe,mBAAA;EAAA,SACvB,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,gBAAA;AAAA;;;;;ADtB4C;AAc3F;;;;;;;;AAAmF;;;;AChCnF;;;;AAAgF;AAEhF;;;;;AAFgF,KAsEpE,mBAAA,GAAsB,QAAA,CAAS,MAAA,SAAe,QAAA,CAAS,MAAA;EAAA,SACxD,KAAA,GAAQ,QAAA,CAAS,MAAA,SAAe,YAAA;EAAA,SAChC,QAAA,GAAW,QAAA,CAAS,MAAA,SAAe,eAAA;AAAA;;;;;;;;AApEa;AAO3D;UAyEiB,YAAA;EAAA,SACN,IAAA;EAAA,SACA,EAAA;EAAA,SACA,OAAA,EAAS,mBAAmB;EAAA,SAC5B,SAAA;EACT,YAAA,EAAc,SAAA;AAAA;AA9EyD;AASzE;;;;;AATyE,uBAuFnD,gBAAA,SAAyB,aAAA,YAAyB,YAAA;EAAA,kBAC3C,EAAA;EAAA,kBACA,OAAA,EAAS,mBAAA;EAAA,SAE3B,YAAA,CAAa,SAAA;AAAA;;;;;;;;;AAxEiB;AAOzC;iBA8EgB,0BAAA,CAA2B,CAAA,YAAa,CAAA,IAAK,gBAAgB;AAAA,cAKhE,UAAA,wCAAkD,OAAA,YAAmB,OAAA;EAAA,SACvE,WAAA,EAAa,eAAA,CAAgB,KAAA;EAAA,SAC7B,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,YAAA;EAAA,SAC5B,KAAA,GAAQ,QAAA,CAAS,MAAA,SAAe,mBAAA;cAErC,KAAA,EAAO,eAAA,CAAgB,KAAA;AAAA"} |
| import { t as SqlNode } from "./sql-node-V214WXQD.mjs"; | ||
| import { n as ForeignKeyInput, t as ForeignKey } from "./foreign-key-DM1UTydh.mjs"; | ||
| import { ColumnDefault, ControlPolicy, ValueSetRef } from "@prisma-next/contract/types"; | ||
| //#region src/ir/check-constraint.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link CheckConstraint}. | ||
| * Mirrors the on-disk storage JSON envelope so the serializer hydration | ||
| * walker can hand a validated literal straight to `new`. | ||
| */ | ||
| interface CheckConstraintInput { | ||
| readonly name: string; | ||
| readonly column: string; | ||
| readonly valueSet: ValueSetRef; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level check constraint that restricts | ||
| * a column to the permitted values of a value-set. | ||
| * | ||
| * The constraint is **structured** (names a column and a value-set | ||
| * reference), not a raw SQL expression. Each target renders its own DDL | ||
| * from the structured form, keeping the contract target-agnostic. | ||
| * | ||
| * Construction is idempotent: passing an existing `CheckConstraint` | ||
| * instance as input produces a new instance with identical fields. | ||
| * The constructor does not use `instanceof` for input discrimination — | ||
| * it reads plain named properties, which is sufficient since | ||
| * `CheckConstraintInput` is a structural type. | ||
| */ | ||
| declare class CheckConstraint extends SqlNode { | ||
| readonly name: string; | ||
| readonly column: string; | ||
| readonly valueSet: ValueSetRef; | ||
| constructor(input: CheckConstraintInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/primary-key.d.ts | ||
| interface PrimaryKeyInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table's primary-key constraint. | ||
| */ | ||
| declare class PrimaryKey extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| constructor(input: PrimaryKeyInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/sql-index.d.ts | ||
| interface IndexInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| readonly type?: string; | ||
| readonly options?: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level secondary index. | ||
| * | ||
| * Note that this class shadows the global TypeScript `Index` lib type | ||
| * at the family-shared name; consumer files that need both should | ||
| * alias one (e.g. | ||
| * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`). | ||
| */ | ||
| declare class Index extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| readonly type?: string; | ||
| readonly options?: Record<string, unknown>; | ||
| constructor(input: IndexInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-column.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link StorageColumn}. Mirrors | ||
| * the on-disk storage JSON envelope exactly so the family-base | ||
| * serializer's hydration walker can hand an arktype-validated literal | ||
| * straight to `new`. | ||
| * | ||
| * `typeParams` and `typeRef` remain mutually exclusive (one or the | ||
| * other, not both); the constructor preserves whichever caller-side | ||
| * choice the input encodes. | ||
| */ | ||
| interface StorageColumnInput { | ||
| readonly nativeType: string; | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| readonly many?: boolean; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| readonly typeRef?: string; | ||
| readonly default?: ColumnDefault; | ||
| readonly control?: ControlPolicy; | ||
| readonly valueSet?: ValueSetRef; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a single column entry in `StorageTable.columns`. | ||
| * | ||
| * Single concrete family-shared class — every SQL target reads the | ||
| * same column shape today, so there is no per-target subclass. The | ||
| * class type accepts any caller that constructs via | ||
| * `new StorageColumn(input)`; literal construction sites must pass | ||
| * through the constructor or the family-base hydration walker. | ||
| * | ||
| * The column's `name` is not on the class — columns are keyed by name | ||
| * in the parent `StorageTable.columns: Record<string, StorageColumn>` | ||
| * map, so a `name` field would be redundant with the key. | ||
| */ | ||
| declare class StorageColumn extends SqlNode { | ||
| readonly nativeType: string; | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| readonly many?: boolean; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| readonly typeRef?: string; | ||
| readonly default?: ColumnDefault; | ||
| readonly control?: ControlPolicy; | ||
| readonly valueSet?: ValueSetRef; | ||
| constructor(input: StorageColumnInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/unique-constraint.d.ts | ||
| interface UniqueConstraintInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level unique constraint. | ||
| */ | ||
| declare class UniqueConstraint extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| constructor(input: UniqueConstraintInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-table.d.ts | ||
| interface StorageTableInput { | ||
| readonly columns: Record<string, StorageColumn | StorageColumnInput>; | ||
| readonly primaryKey?: PrimaryKey | PrimaryKeyInput; | ||
| readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>; | ||
| readonly indexes: ReadonlyArray<Index | IndexInput>; | ||
| readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>; | ||
| readonly control?: ControlPolicy; | ||
| readonly checks?: ReadonlyArray<CheckConstraint | CheckConstraintInput>; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a single table entry in a namespace's | ||
| * `tables` map. | ||
| * | ||
| * The constructor normalises nested IR-class fields (columns, primary | ||
| * key, uniques, indexes, foreign keys) into the appropriate class | ||
| * instances so downstream walks see a uniform AST regardless of whether | ||
| * the input was a JSON literal or an already-constructed class. | ||
| * | ||
| * The table's `name` is not on the class — tables are keyed by name in | ||
| * the parent namespace's `tables: Record<string, StorageTable>` map. | ||
| */ | ||
| declare class StorageTable extends SqlNode { | ||
| readonly columns: Readonly<Record<string, StorageColumn>>; | ||
| readonly uniques: ReadonlyArray<UniqueConstraint>; | ||
| readonly indexes: ReadonlyArray<Index>; | ||
| readonly foreignKeys: ReadonlyArray<ForeignKey>; | ||
| readonly primaryKey?: PrimaryKey; | ||
| readonly control?: ControlPolicy; | ||
| readonly checks?: ReadonlyArray<CheckConstraint>; | ||
| constructor(input: StorageTableInput); | ||
| /** | ||
| * Runtime guard that a namespace `table` entry is really a `StorageTable`. | ||
| * The compiler already types the entry as `StorageTable`, but a | ||
| * freshly-deserialized contract may carry plain JSON at that slot until | ||
| * hydration; this duck-types the structural shape. Accepts `undefined` so | ||
| * optional-chained entry lookups pass straight through. | ||
| */ | ||
| static is(value: StorageTable | undefined): value is StorageTable; | ||
| static assert(value: StorageTable | undefined, coordinate: string): asserts value is StorageTable; | ||
| } | ||
| //#endregion | ||
| export { StorageColumn as a, IndexInput as c, CheckConstraint as d, CheckConstraintInput as f, UniqueConstraintInput as i, PrimaryKey as l, StorageTableInput as n, StorageColumnInput as o, UniqueConstraint as r, Index as s, StorageTable as t, PrimaryKeyInput as u }; | ||
| //# sourceMappingURL=storage-table-Bj1ZN1P7.d.mts.map |
| {"version":3,"file":"storage-table-Bj1ZN1P7.d.mts","names":[],"sources":["../src/ir/check-constraint.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts"],"mappings":";;;;;;;;AASA;;UAAiB,oBAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA;EAAA,SACA,QAAA,EAAU,WAAW;AAAA;;;AAAA;AAiBhC;;;;;;;;;;;cAAa,eAAA,SAAwB,OAAA;EAAA,SAC1B,IAAA;EAAA,SACA,MAAA;EAAA,SACA,QAAA,EAAU,WAAA;cAEP,KAAA,EAAO,oBAAA;AAAA;;;UC/BJ,eAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;ADIf;;;AAAA,cCEa,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;;;;;;;;AFKK;cEMnB,KAAA,SAAc,OAAA;EAAA,SAChB,OAAA;EAAA,SACQ,IAAA;EAAA,SACA,IAAA;EAAA,SACA,OAAA,GAAU,MAAA;cAEf,KAAA,EAAO,UAAA;AAAA;;;;;;AFfrB;;;;;;;UGKiB,kBAAA;EAAA,SACN,UAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;EAAA,SACA,IAAA;EAAA,SACA,UAAA,GAAa,MAAA;EAAA,SACb,OAAA;EAAA,SACA,OAAA,GAAU,aAAA;EAAA,SACV,OAAA,GAAU,aAAA;EAAA,SACV,QAAA,GAAW,WAAA;AAAA;;;;;;;;;;AHWmB;;;;cGK5B,aAAA,SAAsB,OAAA;EAAA,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O,YAAA,cACP,UAAA,mBACS,KAAA,IAAS,YAAA;AAAA"} |
| import { IRNodeBase, freezeNode } from "@prisma-next/framework-components/ir"; | ||
| import { asNamespaceId } from "@prisma-next/contract/types"; | ||
| //#region src/ir/sql-node.ts | ||
| /** | ||
| * SQL family IR node base. Carries the family-level `kind` discriminator | ||
| * `'sql'` and inherits the framework's `freezeNode` affordance. | ||
| * | ||
| * Single family-level discriminator (not per-leaf) reflects the fact that | ||
| * SQL IR has no polymorphic dispatch today — verifiers and serializers | ||
| * walk by structural position (`storage.tables[name].columns[name]`), | ||
| * not by inspecting `kind`. The abstract bar for per-leaf discriminators | ||
| * isn't earned until a future polymorphic consumer arrives. | ||
| * | ||
| * `kind` is installed as a non-enumerable own property on every instance, | ||
| * which keeps three things clean simultaneously: | ||
| * | ||
| * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope | ||
| * shape (no `kind` field), so emitted contract.json files and the | ||
| * `validateSqlContractFully` arktype schemas stay unchanged. | ||
| * - Test assertions that use `toEqual({...})` against the pre-lift flat | ||
| * shape continue to pass — only enumerable own properties are | ||
| * compared. | ||
| * - Direct access (`node.kind`) and runtime narrowing | ||
| * (`if (node.kind === 'sql')`) still work, so future polymorphic | ||
| * dispatch can begin reading `kind` without a runtime change. | ||
| * | ||
| * Future per-leaf overrides land cleanly: a class that gains a | ||
| * polymorphic-dispatch consumer (e.g. an enum type instance walked | ||
| * alongside other types) overrides `kind` with its narrower literal | ||
| * at that leaf level. Per-leaf overrides will use enumerable kind | ||
| * (matching the Mongo per-class-discriminator precedent) because they | ||
| * encode dispatch-relevant information that callers need to see in | ||
| * JSON envelopes; the family-level `'sql'` is uniform across all SQL | ||
| * IR and carries no dispatch-relevant information. | ||
| */ | ||
| var SqlNode = class extends IRNodeBase { | ||
| kind; | ||
| constructor() { | ||
| super(); | ||
| Object.defineProperty(this, "kind", { | ||
| value: "sql", | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/check-constraint.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level check constraint that restricts | ||
| * a column to the permitted values of a value-set. | ||
| * | ||
| * The constraint is **structured** (names a column and a value-set | ||
| * reference), not a raw SQL expression. Each target renders its own DDL | ||
| * from the structured form, keeping the contract target-agnostic. | ||
| * | ||
| * Construction is idempotent: passing an existing `CheckConstraint` | ||
| * instance as input produces a new instance with identical fields. | ||
| * The constructor does not use `instanceof` for input discrimination — | ||
| * it reads plain named properties, which is sufficient since | ||
| * `CheckConstraintInput` is a structural type. | ||
| */ | ||
| var CheckConstraint = class extends SqlNode { | ||
| name; | ||
| column; | ||
| valueSet; | ||
| constructor(input) { | ||
| super(); | ||
| this.name = input.name; | ||
| this.column = input.column; | ||
| this.valueSet = input.valueSet; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/foreign-key-reference.ts | ||
| /** | ||
| * SQL Contract IR node for one side (source or target) of a foreign-key | ||
| * declaration. Carries the full coordinate: namespace, table, and columns. | ||
| * | ||
| * Cross-space discrimination is based on `spaceId` presence: absent means | ||
| * local (same contract-space); present means cross-space (the referenced | ||
| * table lives in the contract-space identified by `spaceId`). | ||
| * | ||
| * For local references `spaceId` is absent from JSON, keeping the serialized | ||
| * shape byte-identical to contracts authored before cross-space support was | ||
| * added. For cross-space references `spaceId` appears in JSON so round-trips | ||
| * are lossless. | ||
| * | ||
| * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir` | ||
| * as the sentinel `namespaceId` for single-namespace (unbound) references. | ||
| */ | ||
| var ForeignKeyReference = class extends SqlNode { | ||
| namespaceId; | ||
| tableName; | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.namespaceId = asNamespaceId(input.namespaceId); | ||
| this.tableName = input.tableName; | ||
| this.columns = input.columns; | ||
| if (input.spaceId !== void 0) this.spaceId = input.spaceId; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/foreign-key.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level foreign-key declaration. | ||
| * | ||
| * Each FK carries explicit `source` and `target` {@link ForeignKeyReference} | ||
| * coordinates (namespace, table, columns). For single-namespace contracts the | ||
| * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides. | ||
| * | ||
| * The nested references are normalised to {@link ForeignKeyReference} | ||
| * instances inside the constructor so downstream walks see a uniform AST | ||
| * regardless of whether the input was a JSON literal or an already-constructed | ||
| * class instance. | ||
| */ | ||
| var ForeignKey = class extends SqlNode { | ||
| source; | ||
| target; | ||
| constraint; | ||
| index; | ||
| constructor(input) { | ||
| super(); | ||
| this.source = input.source instanceof ForeignKeyReference ? input.source : new ForeignKeyReference(input.source); | ||
| this.target = input.target instanceof ForeignKeyReference ? input.target : new ForeignKeyReference(input.target); | ||
| this.constraint = input.constraint; | ||
| this.index = input.index; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| if (input.onDelete !== void 0) this.onDelete = input.onDelete; | ||
| if (input.onUpdate !== void 0) this.onUpdate = input.onUpdate; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/primary-key.ts | ||
| /** | ||
| * SQL Contract IR node for a table's primary-key constraint. | ||
| */ | ||
| var PrimaryKey = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/sql-index.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level secondary index. | ||
| * | ||
| * Note that this class shadows the global TypeScript `Index` lib type | ||
| * at the family-shared name; consumer files that need both should | ||
| * alias one (e.g. | ||
| * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`). | ||
| */ | ||
| var Index = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| if (input.type !== void 0) this.type = input.type; | ||
| if (input.options !== void 0) this.options = input.options; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/storage-column.ts | ||
| /** | ||
| * SQL Contract IR node for a single column entry in `StorageTable.columns`. | ||
| * | ||
| * Single concrete family-shared class — every SQL target reads the | ||
| * same column shape today, so there is no per-target subclass. The | ||
| * class type accepts any caller that constructs via | ||
| * `new StorageColumn(input)`; literal construction sites must pass | ||
| * through the constructor or the family-base hydration walker. | ||
| * | ||
| * The column's `name` is not on the class — columns are keyed by name | ||
| * in the parent `StorageTable.columns: Record<string, StorageColumn>` | ||
| * map, so a `name` field would be redundant with the key. | ||
| */ | ||
| var StorageColumn = class extends SqlNode { | ||
| nativeType; | ||
| codecId; | ||
| nullable; | ||
| constructor(input) { | ||
| super(); | ||
| this.nativeType = input.nativeType; | ||
| this.codecId = input.codecId; | ||
| this.nullable = input.nullable; | ||
| if (input.many !== void 0) this.many = input.many; | ||
| if (input.typeParams !== void 0) this.typeParams = input.typeParams; | ||
| if (input.typeRef !== void 0) this.typeRef = input.typeRef; | ||
| if (input.default !== void 0) this.default = input.default; | ||
| if (input.control !== void 0) this.control = input.control; | ||
| if (input.valueSet !== void 0) this.valueSet = input.valueSet; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/unique-constraint.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level unique constraint. | ||
| */ | ||
| var UniqueConstraint = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/storage-table.ts | ||
| /** | ||
| * SQL Contract IR node for a single table entry in a namespace's | ||
| * `tables` map. | ||
| * | ||
| * The constructor normalises nested IR-class fields (columns, primary | ||
| * key, uniques, indexes, foreign keys) into the appropriate class | ||
| * instances so downstream walks see a uniform AST regardless of whether | ||
| * the input was a JSON literal or an already-constructed class. | ||
| * | ||
| * The table's `name` is not on the class — tables are keyed by name in | ||
| * the parent namespace's `tables: Record<string, StorageTable>` map. | ||
| */ | ||
| var StorageTable = class StorageTable extends SqlNode { | ||
| columns; | ||
| uniques; | ||
| indexes; | ||
| foreignKeys; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = Object.freeze(Object.fromEntries(Object.entries(input.columns).map(([name, col]) => [name, col instanceof StorageColumn ? col : new StorageColumn(col)]))); | ||
| if (input.primaryKey !== void 0) this.primaryKey = input.primaryKey instanceof PrimaryKey ? input.primaryKey : new PrimaryKey(input.primaryKey); | ||
| this.uniques = Object.freeze(input.uniques.map((u) => u instanceof UniqueConstraint ? u : new UniqueConstraint(u))); | ||
| this.indexes = Object.freeze(input.indexes.map((i) => i instanceof Index ? i : new Index(i))); | ||
| this.foreignKeys = Object.freeze(input.foreignKeys.map((fk) => fk instanceof ForeignKey ? fk : new ForeignKey(fk))); | ||
| if (input.control !== void 0) this.control = input.control; | ||
| if (input.checks !== void 0 && input.checks.length > 0) this.checks = Object.freeze(input.checks.map((cc) => new CheckConstraint(cc))); | ||
| freezeNode(this); | ||
| } | ||
| /** | ||
| * Runtime guard that a namespace `table` entry is really a `StorageTable`. | ||
| * The compiler already types the entry as `StorageTable`, but a | ||
| * freshly-deserialized contract may carry plain JSON at that slot until | ||
| * hydration; this duck-types the structural shape. Accepts `undefined` so | ||
| * optional-chained entry lookups pass straight through. | ||
| */ | ||
| static is(value) { | ||
| if (typeof value !== "object" || value === null) return false; | ||
| return "columns" in value && "uniques" in value && "indexes" in value && "foreignKeys" in value; | ||
| } | ||
| static assert(value, coordinate) { | ||
| if (!StorageTable.is(value)) throw new Error(`Expected a StorageTable at ${coordinate}`); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { PrimaryKey as a, CheckConstraint as c, Index as i, SqlNode as l, UniqueConstraint as n, ForeignKey as o, StorageColumn as r, ForeignKeyReference as s, StorageTable as t }; | ||
| //# sourceMappingURL=storage-table-y6R6pxyI.mjs.map |
| {"version":3,"file":"storage-table-y6R6pxyI.mjs","names":[],"sources":["../src/ir/sql-node.ts","../src/ir/check-constraint.ts","../src/ir/foreign-key-reference.ts","../src/ir/foreign-key.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts"],"sourcesContent":["import { IRNodeBase } from '@prisma-next/framework-components/ir';\n\n/**\n * SQL family IR node base. Carries the family-level `kind` discriminator\n * `'sql'` and inherits the framework's `freezeNode` affordance.\n *\n * Single family-level discriminator (not per-leaf) reflects the fact that\n * SQL IR has no polymorphic dispatch today — verifiers and serializers\n * walk by structural position (`storage.tables[name].columns[name]`),\n * not by inspecting `kind`. The abstract bar for per-leaf discriminators\n * isn't earned until a future polymorphic consumer arrives.\n *\n * `kind` is installed as a non-enumerable own property on every instance,\n * which keeps three things clean simultaneously:\n *\n * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope\n * shape (no `kind` field), so emitted contract.json files and the\n * `validateSqlContractFully` arktype schemas stay unchanged.\n * - Test assertions that use `toEqual({...})` against the pre-lift flat\n * shape continue to pass — only enumerable own properties are\n * compared.\n * - Direct access (`node.kind`) and runtime narrowing\n * (`if (node.kind === 'sql')`) still work, so future polymorphic\n * dispatch can begin reading `kind` without a runtime change.\n *\n * Future per-leaf overrides land cleanly: a class that gains a\n * polymorphic-dispatch consumer (e.g. an enum type instance walked\n * alongside other types) overrides `kind` with its narrower literal\n * at that leaf level. Per-leaf overrides will use enumerable kind\n * (matching the Mongo per-class-discriminator precedent) because they\n * encode dispatch-relevant information that callers need to see in\n * JSON envelopes; the family-level `'sql'` is uniform across all SQL\n * IR and carries no dispatch-relevant information.\n */\nexport abstract class SqlNode extends IRNodeBase {\n readonly kind?: string;\n\n constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql',\n writable: false,\n enumerable: false,\n // configurable so per-leaf subclasses (e.g. StorageValueSet)\n // can override `kind` with their narrower\n // enumerable literal via a class-field initializer. SqlNode\n // itself never needs to mutate the property again, so\n // configurability has no surface impact at this layer.\n configurable: true,\n });\n }\n}\n","import type { ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link CheckConstraint}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface CheckConstraintInput {\n readonly name: string;\n readonly column: string;\n readonly valueSet: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a table-level check constraint that restricts\n * a column to the permitted values of a value-set.\n *\n * The constraint is **structured** (names a column and a value-set\n * reference), not a raw SQL expression. Each target renders its own DDL\n * from the structured form, keeping the contract target-agnostic.\n *\n * Construction is idempotent: passing an existing `CheckConstraint`\n * instance as input produces a new instance with identical fields.\n * The constructor does not use `instanceof` for input discrimination —\n * it reads plain named properties, which is sufficient since\n * `CheckConstraintInput` is a structural type.\n */\nexport class CheckConstraint extends SqlNode {\n readonly name: string;\n readonly column: string;\n readonly valueSet: ValueSetRef;\n\n constructor(input: CheckConstraintInput) {\n super();\n this.name = input.name;\n this.column = input.column;\n this.valueSet = input.valueSet;\n freezeNode(this);\n }\n}\n","import { asNamespaceId, type NamespaceId } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Input for a foreign-key reference (one side of a foreign-key declaration).\n *\n * When `spaceId` is absent the reference is local — the referenced table lives\n * in the same contract-space. When `spaceId` is present the reference is\n * cross-space — the referenced table lives in a different contract-space\n * identified by `spaceId`.\n *\n * Presence-based discrimination keeps local FK JSON byte-identical to\n * contracts authored before cross-space support was added.\n */\nexport interface ForeignKeyReferenceInput {\n readonly namespaceId: string;\n readonly tableName: string;\n readonly columns: readonly string[];\n readonly spaceId?: string;\n}\n\n/**\n * SQL Contract IR node for one side (source or target) of a foreign-key\n * declaration. Carries the full coordinate: namespace, table, and columns.\n *\n * Cross-space discrimination is based on `spaceId` presence: absent means\n * local (same contract-space); present means cross-space (the referenced\n * table lives in the contract-space identified by `spaceId`).\n *\n * For local references `spaceId` is absent from JSON, keeping the serialized\n * shape byte-identical to contracts authored before cross-space support was\n * added. For cross-space references `spaceId` appears in JSON so round-trips\n * are lossless.\n *\n * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir`\n * as the sentinel `namespaceId` for single-namespace (unbound) references.\n */\nexport class ForeignKeyReference extends SqlNode {\n readonly namespaceId: NamespaceId;\n readonly tableName: string;\n readonly columns: readonly string[];\n declare readonly spaceId?: string;\n\n constructor(input: ForeignKeyReferenceInput) {\n super();\n this.namespaceId = asNamespaceId(input.namespaceId);\n this.tableName = input.tableName;\n this.columns = input.columns;\n if (input.spaceId !== undefined) this.spaceId = input.spaceId;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKeyReference, type ForeignKeyReferenceInput } from './foreign-key-reference';\nimport { SqlNode } from './sql-node';\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport interface ForeignKeyInput {\n readonly source: ForeignKeyReference | ForeignKeyReferenceInput;\n readonly target: ForeignKeyReference | ForeignKeyReferenceInput;\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n}\n\n/**\n * SQL Contract IR node for a table-level foreign-key declaration.\n *\n * Each FK carries explicit `source` and `target` {@link ForeignKeyReference}\n * coordinates (namespace, table, columns). For single-namespace contracts the\n * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides.\n *\n * The nested references are normalised to {@link ForeignKeyReference}\n * instances inside the constructor so downstream walks see a uniform AST\n * regardless of whether the input was a JSON literal or an already-constructed\n * class instance.\n */\nexport class ForeignKey extends SqlNode {\n readonly source: ForeignKeyReference;\n readonly target: ForeignKeyReference;\n readonly constraint: boolean;\n readonly index: boolean;\n declare readonly name?: string;\n declare readonly onDelete?: ReferentialAction;\n declare readonly onUpdate?: ReferentialAction;\n\n constructor(input: ForeignKeyInput) {\n super();\n this.source =\n input.source instanceof ForeignKeyReference\n ? input.source\n : new ForeignKeyReference(input.source);\n this.target =\n input.target instanceof ForeignKeyReference\n ? input.target\n : new ForeignKeyReference(input.target);\n this.constraint = input.constraint;\n this.index = input.index;\n if (input.name !== undefined) this.name = input.name;\n if (input.onDelete !== undefined) this.onDelete = input.onDelete;\n if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface PrimaryKeyInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table's primary-key constraint.\n */\nexport class PrimaryKey extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: PrimaryKeyInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface IndexInput {\n readonly columns: readonly string[];\n readonly name?: string;\n readonly type?: string;\n readonly options?: Record<string, unknown>;\n}\n\n/**\n * SQL Contract IR node for a table-level secondary index.\n *\n * Note that this class shadows the global TypeScript `Index` lib type\n * at the family-shared name; consumer files that need both should\n * alias one (e.g.\n * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).\n */\nexport class Index extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n declare readonly type?: string;\n declare readonly options?: Record<string, unknown>;\n\n constructor(input: IndexInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n if (input.type !== undefined) this.type = input.type;\n if (input.options !== undefined) this.options = input.options;\n freezeNode(this);\n }\n}\n","import type { ColumnDefault, ControlPolicy, ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageColumn}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n *\n * `typeParams` and `typeRef` remain mutually exclusive (one or the\n * other, not both); the constructor preserves whichever caller-side\n * choice the input encodes.\n */\nexport interface StorageColumnInput {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n readonly many?: boolean;\n readonly typeParams?: Record<string, unknown>;\n readonly typeRef?: string;\n readonly default?: ColumnDefault;\n readonly control?: ControlPolicy;\n readonly valueSet?: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a single column entry in `StorageTable.columns`.\n *\n * Single concrete family-shared class — every SQL target reads the\n * same column shape today, so there is no per-target subclass. The\n * class type accepts any caller that constructs via\n * `new StorageColumn(input)`; literal construction sites must pass\n * through the constructor or the family-base hydration walker.\n *\n * The column's `name` is not on the class — columns are keyed by name\n * in the parent `StorageTable.columns: Record<string, StorageColumn>`\n * map, so a `name` field would be redundant with the key.\n */\nexport class StorageColumn extends SqlNode {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n declare readonly many?: boolean;\n declare readonly typeParams?: Record<string, unknown>;\n declare readonly typeRef?: string;\n declare readonly default?: ColumnDefault;\n declare readonly control?: ControlPolicy;\n declare readonly valueSet?: ValueSetRef;\n\n constructor(input: StorageColumnInput) {\n super();\n this.nativeType = input.nativeType;\n this.codecId = input.codecId;\n this.nullable = input.nullable;\n if (input.many !== undefined) this.many = input.many;\n if (input.typeParams !== undefined) this.typeParams = input.typeParams;\n if (input.typeRef !== undefined) this.typeRef = input.typeRef;\n if (input.default !== undefined) this.default = input.default;\n if (input.control !== undefined) this.control = input.control;\n if (input.valueSet !== undefined) this.valueSet = input.valueSet;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface UniqueConstraintInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table-level unique constraint.\n */\nexport class UniqueConstraint extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: UniqueConstraintInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import type { ControlPolicy } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { CheckConstraint, type CheckConstraintInput } from './check-constraint';\nimport { ForeignKey, type ForeignKeyInput } from './foreign-key';\nimport { PrimaryKey, type PrimaryKeyInput } from './primary-key';\nimport { Index, type IndexInput } from './sql-index';\nimport { SqlNode } from './sql-node';\nimport { StorageColumn, type StorageColumnInput } from './storage-column';\nimport { UniqueConstraint, type UniqueConstraintInput } from './unique-constraint';\n\nexport interface StorageTableInput {\n readonly columns: Record<string, StorageColumn | StorageColumnInput>;\n readonly primaryKey?: PrimaryKey | PrimaryKeyInput;\n readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>;\n readonly indexes: ReadonlyArray<Index | IndexInput>;\n readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>;\n readonly control?: ControlPolicy;\n readonly checks?: ReadonlyArray<CheckConstraint | CheckConstraintInput>;\n}\n\n/**\n * SQL Contract IR node for a single table entry in a namespace's\n * `tables` map.\n *\n * The constructor normalises nested IR-class fields (columns, primary\n * key, uniques, indexes, foreign keys) into the appropriate class\n * instances so downstream walks see a uniform AST regardless of whether\n * the input was a JSON literal or an already-constructed class.\n *\n * The table's `name` is not on the class — tables are keyed by name in\n * the parent namespace's `tables: Record<string, StorageTable>` map.\n */\nexport class StorageTable extends SqlNode {\n readonly columns: Readonly<Record<string, StorageColumn>>;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n declare readonly primaryKey?: PrimaryKey;\n declare readonly control?: ControlPolicy;\n declare readonly checks?: ReadonlyArray<CheckConstraint>;\n\n constructor(input: StorageTableInput) {\n super();\n this.columns = Object.freeze(\n Object.fromEntries(\n Object.entries(input.columns).map(([name, col]) => [\n name,\n col instanceof StorageColumn ? col : new StorageColumn(col),\n ]),\n ),\n );\n if (input.primaryKey !== undefined) {\n this.primaryKey =\n input.primaryKey instanceof PrimaryKey\n ? input.primaryKey\n : new PrimaryKey(input.primaryKey);\n }\n this.uniques = Object.freeze(\n input.uniques.map((u) => (u instanceof UniqueConstraint ? u : new UniqueConstraint(u))),\n );\n this.indexes = Object.freeze(input.indexes.map((i) => (i instanceof Index ? i : new Index(i))));\n this.foreignKeys = Object.freeze(\n input.foreignKeys.map((fk) => (fk instanceof ForeignKey ? fk : new ForeignKey(fk))),\n );\n if (input.control !== undefined) this.control = input.control;\n if (input.checks !== undefined && input.checks.length > 0) {\n this.checks = Object.freeze(input.checks.map((cc) => new CheckConstraint(cc)));\n }\n freezeNode(this);\n }\n\n /**\n * Runtime guard that a namespace `table` entry is really a `StorageTable`.\n * The compiler already types the entry as `StorageTable`, but a\n * freshly-deserialized contract may carry plain JSON at that slot until\n * hydration; this duck-types the structural shape. Accepts `undefined` so\n * optional-chained entry lookups pass straight through.\n */\n static is(value: StorageTable | undefined): value is StorageTable {\n if (typeof value !== 'object' || value === null) return false;\n return 'columns' in value && 'uniques' in value && 'indexes' in value && 'foreignKeys' in value;\n }\n\n static assert(\n value: StorageTable | undefined,\n coordinate: string,\n ): asserts value is StorageTable {\n if (!StorageTable.is(value)) {\n throw new Error(`Expected a StorageTable at ${coordinate}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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,OACpB,OAAO,YACL,OAAO,QAAQ,MAAM,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,SAAS,CACjD,MACA,eAAe,gBAAgB,MAAM,IAAI,cAAc,GAAG,CAC5D,CAAC,CACH,CACF;EACA,IAAI,MAAM,eAAe,KAAA,GACvB,KAAK,aACH,MAAM,sBAAsB,aACxB,MAAM,aACN,IAAI,WAAW,MAAM,UAAU;EAEvC,KAAK,UAAU,OAAO,OACpB,MAAM,QAAQ,KAAK,MAAO,aAAa,mBAAmB,IAAI,IAAI,iBAAiB,CAAC,CAAE,CACxF;EACA,KAAK,UAAU,OAAO,OAAO,MAAM,QAAQ,KAAK,MAAO,aAAa,QAAQ,IAAI,IAAI,MAAM,CAAC,CAAE,CAAC;EAC9F,KAAK,cAAc,OAAO,OACxB,MAAM,YAAY,KAAK,OAAQ,cAAc,aAAa,KAAK,IAAI,WAAW,EAAE,CAAE,CACpF;EACA,IAAI,MAAM,YAAY,KAAA,GAAW,KAAK,UAAU,MAAM;EACtD,IAAI,MAAM,WAAW,KAAA,KAAa,MAAM,OAAO,SAAS,GACtD,KAAK,SAAS,OAAO,OAAO,MAAM,OAAO,KAAK,OAAO,IAAI,gBAAgB,EAAE,CAAC,CAAC;EAE/E,WAAW,IAAI;CACjB;;;;;;;;CASA,OAAO,GAAG,OAAwD;EAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;EACxD,OAAO,aAAa,SAAS,aAAa,SAAS,aAAa,SAAS,iBAAiB;CAC5F;CAEA,OAAO,OACL,OACA,YAC+B;EAC/B,IAAI,CAAC,aAAa,GAAG,KAAK,GACxB,MAAM,IAAI,MAAM,8BAA8B,YAAY;CAE9D;AACF"} |
| import { t as SqlNode } from "./sql-node-V214WXQD.mjs"; | ||
| import { JsonValue } from "@prisma-next/contract/types"; | ||
| //#region src/ir/storage-value-set.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link StorageValueSet}. | ||
| * Mirrors the on-disk storage JSON envelope so the serializer hydration | ||
| * walker can hand a validated literal straight to `new`. | ||
| */ | ||
| interface StorageValueSetInput { | ||
| readonly kind: 'valueSet'; | ||
| /** Ordered permitted values, codec-encoded. Declaration order is preserved. */ | ||
| readonly values: readonly JsonValue[]; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a value-set entry in a namespace's `valueSet` | ||
| * map (`SqlNamespace.entries.valueSet`). | ||
| * | ||
| * A value-set records the ordered set of permitted codec-encoded values for | ||
| * an enum-like column restriction. It does not carry a `codecId` — the | ||
| * column that references it already holds the codec; the value-set holds | ||
| * only the permitted values. | ||
| * | ||
| * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope | ||
| * carries the discriminator and the serializer hydration walker can | ||
| * dispatch on it. This follows the per-leaf enumerable-kind convention | ||
| * established in the SQL-node comment (future polymorphic dispatch on | ||
| * namespace entries needs the discriminator in JSON). | ||
| * | ||
| * The entry's name is not on the class — value-sets are keyed by name in | ||
| * the parent namespace's `valueSet: Record<string, StorageValueSet>` map. | ||
| */ | ||
| declare class StorageValueSet extends SqlNode { | ||
| readonly kind: "valueSet"; | ||
| readonly values: readonly JsonValue[]; | ||
| constructor(input: StorageValueSetInput); | ||
| } | ||
| declare function isStorageValueSet(value: unknown): value is StorageValueSet; | ||
| //#endregion | ||
| export { StorageValueSetInput as n, isStorageValueSet as r, StorageValueSet as t }; | ||
| //# sourceMappingURL=storage-value-set-D-jww77l.d.mts.map |
| {"version":3,"file":"storage-value-set-D-jww77l.d.mts","names":[],"sources":["../src/ir/storage-value-set.ts"],"mappings":";;;;;;AASA;;;UAAiB,oBAAA;EAAA,SACN,IAAA;EAEA;EAAA,SAAA,MAAA,WAAiB,SAAS;AAAA;AAAA;AAqBrC;;;;;;;;;;;;;;;;AAIyC;AAzBJ,cAqBxB,eAAA,SAAwB,OAAA;EAAA,SACjB,IAAA;EAAA,SACT,MAAA,WAAiB,SAAA;cAEd,KAAA,EAAO,oBAAA;AAAA;AAAA,iBAOL,iBAAA,CAAkB,KAAA,YAAiB,KAAA,IAAS,eAAe"} |
| import { l as SqlNode } from "./storage-table-y6R6pxyI.mjs"; | ||
| import { freezeNode } from "@prisma-next/framework-components/ir"; | ||
| //#region src/ir/storage-value-set.ts | ||
| /** | ||
| * SQL Contract IR node for a value-set entry in a namespace's `valueSet` | ||
| * map (`SqlNamespace.entries.valueSet`). | ||
| * | ||
| * A value-set records the ordered set of permitted codec-encoded values for | ||
| * an enum-like column restriction. It does not carry a `codecId` — the | ||
| * column that references it already holds the codec; the value-set holds | ||
| * only the permitted values. | ||
| * | ||
| * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope | ||
| * carries the discriminator and the serializer hydration walker can | ||
| * dispatch on it. This follows the per-leaf enumerable-kind convention | ||
| * established in the SQL-node comment (future polymorphic dispatch on | ||
| * namespace entries needs the discriminator in JSON). | ||
| * | ||
| * The entry's name is not on the class — value-sets are keyed by name in | ||
| * the parent namespace's `valueSet: Record<string, StorageValueSet>` map. | ||
| */ | ||
| var StorageValueSet = class extends SqlNode { | ||
| kind = "valueSet"; | ||
| values; | ||
| constructor(input) { | ||
| super(); | ||
| this.values = Object.freeze([...input.values]); | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| function isStorageValueSet(value) { | ||
| if (typeof value !== "object" || value === null) return false; | ||
| return "kind" in value && value.kind === "valueSet" && "values" in value; | ||
| } | ||
| //#endregion | ||
| export { isStorageValueSet as n, StorageValueSet as t }; | ||
| //# sourceMappingURL=storage-value-set-Tx3CFoS_.mjs.map |
| {"version":3,"file":"storage-value-set-Tx3CFoS_.mjs","names":[],"sources":["../src/ir/storage-value-set.ts"],"sourcesContent":["import type { JsonValue } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageValueSet}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface StorageValueSetInput {\n readonly kind: 'valueSet';\n /** Ordered permitted values, codec-encoded. Declaration order is preserved. */\n readonly values: readonly JsonValue[];\n}\n\n/**\n * SQL Contract IR node for a value-set entry in a namespace's `valueSet`\n * map (`SqlNamespace.entries.valueSet`).\n *\n * A value-set records the ordered set of permitted codec-encoded values for\n * an enum-like column restriction. It does not carry a `codecId` — the\n * column that references it already holds the codec; the value-set holds\n * only the permitted values.\n *\n * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope\n * carries the discriminator and the serializer hydration walker can\n * dispatch on it. This follows the per-leaf enumerable-kind convention\n * established in the SQL-node comment (future polymorphic dispatch on\n * namespace entries needs the discriminator in JSON).\n *\n * The entry's name is not on the class — value-sets are keyed by name in\n * the parent namespace's `valueSet: Record<string, StorageValueSet>` map.\n */\nexport class StorageValueSet extends SqlNode {\n override readonly kind = 'valueSet' as const;\n readonly values: readonly JsonValue[];\n\n constructor(input: StorageValueSetInput) {\n super();\n this.values = Object.freeze([...input.values]);\n freezeNode(this);\n }\n}\n\nexport function isStorageValueSet(value: unknown): value is StorageValueSet {\n if (typeof value !== 'object' || value === null) return false;\n return 'kind' in value && value.kind === 'valueSet' && 'values' in value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,kBAAb,cAAqC,QAAQ;CAC3C,OAAyB;CACzB;CAEA,YAAY,OAA6B;EACvC,MAAM;EACN,KAAK,SAAS,OAAO,OAAO,CAAC,GAAG,MAAM,MAAM,CAAC;EAC7C,WAAW,IAAI;CACjB;AACF;AAEA,SAAgB,kBAAkB,OAA0C;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,UAAU,SAAS,MAAM,SAAS,cAAc,YAAY;AACrE"} |
| //#region src/types.ts | ||
| const DEFAULT_FK_CONSTRAINT = true; | ||
| const DEFAULT_FK_INDEX = true; | ||
| function applyFkDefaults(fk, overrideDefaults) { | ||
| return { | ||
| constraint: fk.constraint ?? overrideDefaults?.constraint ?? true, | ||
| index: fk.index ?? overrideDefaults?.index ?? true | ||
| }; | ||
| } | ||
| //#endregion | ||
| export { DEFAULT_FK_INDEX as n, applyFkDefaults as r, DEFAULT_FK_CONSTRAINT as t }; | ||
| //# sourceMappingURL=types-Hkxybhdj.mjs.map |
| {"version":3,"file":"types-Hkxybhdj.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["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":";AA2EA,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"} |
| import { r as ReferentialAction } from "./foreign-key-DM1UTydh.mjs"; | ||
| import { CodecTrait } from "@prisma-next/framework-components/codec"; | ||
| import { ControlDriverInstance } from "@prisma-next/framework-components/control"; | ||
| //#region src/types.d.ts | ||
| interface SqlControlDriverInstance<T extends string = string> extends ControlDriverInstance<'sql', T> { | ||
| query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{ | ||
| readonly rows: Row[]; | ||
| }>; | ||
| } | ||
| type ForeignKeyOptions = { | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| }; | ||
| type SqlModelFieldStorage = { | ||
| readonly column: string; | ||
| readonly codecId?: string; | ||
| readonly nullable?: boolean; | ||
| }; | ||
| type SqlModelStorage = { | ||
| readonly table: string; | ||
| readonly namespaceId: string; | ||
| readonly fields: Record<string, SqlModelFieldStorage>; | ||
| }; | ||
| declare const DEFAULT_FK_CONSTRAINT = true; | ||
| declare const DEFAULT_FK_INDEX = true; | ||
| declare function applyFkDefaults(fk: { | ||
| constraint?: boolean | undefined; | ||
| index?: boolean | undefined; | ||
| }, overrideDefaults?: { | ||
| constraint?: boolean | undefined; | ||
| index?: boolean | undefined; | ||
| }): { | ||
| constraint: boolean; | ||
| index: boolean; | ||
| }; | ||
| type NamespacedFieldTypeMap = Record<string, Record<string, Record<string, unknown>>>; | ||
| type NamespacedStorageColumnTypeMap = Record<string, Record<string, Record<string, unknown>>>; | ||
| type TypeMaps<TCodecTypes extends Record<string, { | ||
| output: unknown; | ||
| }> = Record<string, never>, TQueryOperationTypes extends Record<string, unknown> = Record<string, never>, TFieldOutputTypes extends NamespacedFieldTypeMap = Record<string, never>, TFieldInputTypes extends NamespacedFieldTypeMap = Record<string, never>, TStorageColumnTypes extends NamespacedStorageColumnTypeMap = Record<string, never>, TStorageColumnInputTypes extends NamespacedStorageColumnTypeMap = Record<string, never>> = { | ||
| readonly codecTypes: TCodecTypes; | ||
| readonly queryOperationTypes: TQueryOperationTypes; | ||
| readonly fieldOutputTypes: TFieldOutputTypes; | ||
| readonly fieldInputTypes: TFieldInputTypes; | ||
| readonly storageColumnTypes: TStorageColumnTypes; | ||
| readonly storageColumnInputTypes: TStorageColumnInputTypes; | ||
| }; | ||
| type CodecTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly codecTypes: infer C; | ||
| } ? C extends Record<string, { | ||
| output: unknown; | ||
| }> ? C : Record<string, never> : Record<string, never>; | ||
| /** | ||
| * Dispatch hint identifying the first-argument target of an operation. | ||
| * | ||
| * Used by ORM column helpers to decide whether an operation is reachable on a | ||
| * field. Names a concrete codec identity, a set of capability traits the | ||
| * field's codec must carry, or targets list-typed (`many`) fields. Element | ||
| * capability gating for list ops travels in `elementTraits`. | ||
| */ | ||
| type QueryOperationSelfSpec = { | ||
| readonly codecId: string; | ||
| readonly traits?: never; | ||
| readonly many?: never; | ||
| } | { | ||
| readonly traits: readonly CodecTrait[]; | ||
| readonly codecId?: never; | ||
| readonly many?: never; | ||
| } | { | ||
| readonly many: true; | ||
| readonly elementTraits?: readonly CodecTrait[]; | ||
| readonly codecId?: never; | ||
| readonly traits?: never; | ||
| }; | ||
| /** | ||
| * Structural shape an operation's impl must return: any value carrying a | ||
| * codec-exact `returnType` descriptor. `Expression<T>` (from | ||
| * `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`) | ||
| * extends this. Trait-targeted returns are deliberately excluded — predicate | ||
| * detection and result decoding both depend on knowing the concrete return | ||
| * codec. | ||
| */ | ||
| type QueryOperationReturn = { | ||
| readonly returnType: { | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| }; | ||
| }; | ||
| type QueryOperationTypeEntry = { | ||
| readonly self?: QueryOperationSelfSpec; | ||
| readonly impl: (...args: never[]) => QueryOperationReturn; | ||
| }; | ||
| type SqlQueryOperationTypes<_CT extends Record<string, { | ||
| readonly input: unknown; | ||
| readonly output: unknown; | ||
| }>, T extends Record<string, QueryOperationTypeEntry>> = T; | ||
| type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>; | ||
| type QueryOperationTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly queryOperationTypes: infer Q; | ||
| } ? Q extends Record<string, unknown> ? Q : Record<string, never> : Record<string, never>; | ||
| type TypeMapsPhantomKey = '__@prisma-next/sql-contract/typeMaps@__'; | ||
| type ContractWithTypeMaps<TContract, TTypeMaps> = TContract & { readonly [K in TypeMapsPhantomKey]?: TTypeMaps }; | ||
| type ExtractTypeMapsFromContract<T> = TypeMapsPhantomKey extends keyof T ? NonNullable<T[TypeMapsPhantomKey & keyof T]> : never; | ||
| type FieldOutputTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly fieldOutputTypes: infer F; | ||
| } ? F extends NamespacedFieldTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type FieldInputTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly fieldInputTypes: infer F; | ||
| } ? F extends NamespacedFieldTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type StorageColumnTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly storageColumnTypes: infer F; | ||
| } ? F extends NamespacedStorageColumnTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type StorageColumnInputTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly storageColumnInputTypes: infer F; | ||
| } ? F extends NamespacedStorageColumnTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractFieldOutputTypes<T> = FieldOutputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractStorageColumnTypes<T> = StorageColumnTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractStorageColumnInputTypes<T> = StorageColumnInputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] ? ExtractCodecTypes<TContract> : CodecTypesOf<TTypeMaps>; | ||
| //#endregion | ||
| export { TypeMapsPhantomKey as A, SqlControlDriverInstance as C, StorageColumnInputTypesOf as D, SqlQueryOperationTypes as E, StorageColumnTypesOf as O, ResolveCodecTypes as S, SqlModelStorage as T, QueryOperationReturn as _, ExtractCodecTypes as a, QueryOperationTypesBase as b, ExtractQueryOperationTypes as c, ExtractTypeMapsFromContract as d, FieldInputTypesOf as f, NamespacedStorageColumnTypeMap as g, NamespacedFieldTypeMap as h, DEFAULT_FK_INDEX as i, applyFkDefaults as j, TypeMaps as k, ExtractStorageColumnInputTypes as l, ForeignKeyOptions as m, ContractWithTypeMaps as n, ExtractFieldInputTypes as o, FieldOutputTypesOf as p, DEFAULT_FK_CONSTRAINT as r, ExtractFieldOutputTypes as s, CodecTypesOf as t, ExtractStorageColumnTypes as u, QueryOperationSelfSpec as v, SqlModelFieldStorage as w, QueryOperationTypesOf as x, QueryOperationTypeEntry as y }; | ||
| //# sourceMappingURL=types-zBvpNCmg.d.mts.map |
| {"version":3,"file":"types-zBvpNCmg.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;UAIiB,wBAAA,oCACP,qBAAA,QAA6B,CAAA;EACrC,KAAA,OAAY,MAAA,mBACV,GAAA,UACA,MAAA,wBACC,OAAA;IAAA,SAAmB,IAAA,EAAM,GAAA;EAAA;AAAA;AAAA,KAgDlB,iBAAA;EAAA,SACD,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAiB;AAAA;AAAA,KAG3B,oBAAA;EAAA,SACD,MAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;AAAA;AAAA,KAGC,eAAA;EAAA,SACD,KAAA;EAAA,SAC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EM,iBAAA,MAAuB,YAAA,CAAa,2BAAA,CAA4B,CAAA;AAAA,KAChE,0BAAA,MAAgC,qBAAA,CAAsB,2BAAA,CAA4B,CAAA;AAAA,KAClF,uBAAA,MAA6B,kBAAA,CAAmB,2BAAA,CAA4B,CAAA;AAAA,KAC5E,sBAAA,MAA4B,iBAAA,CAAkB,2BAAA,CAA4B,CAAA;AAAA,KAC1E,yBAAA,MAA+B,oBAAA,CAAqB,2BAAA,CAA4B,CAAA;AAAA,KAChF,8BAAA,MAAoC,yBAAA,CAC9C,2BAAA,CAA4B,CAAA;AAAA,KAGlB,iBAAA,0BAA2C,SAAA,oBACnD,iBAAA,CAAkB,SAAA,IAClB,YAAA,CAAa,SAAA"} |
| {"version":3,"file":"types.d.mts","names":[],"sources":["../src/column-type-resolution.ts"],"mappings":";;;;;;;;KACY,kBAAA,4EAIa,GAAA,WAErB,IAAA,eAAmB,GAAA,wBACI,GAAA,CAAI,IAAA,YAEvB,SAAA,eAAwB,GAAA,CAAI,IAAA,IAC1B,GAAA,CAAI,IAAA,EAAM,SAAA;AAAA,KAIR,iCAAA,4EAKG,GAAA,GAAM,SAAA,eAAwB,GAAA,CAAI,EAAA,IAC3C,UAAA,eAAyB,GAAA,CAAI,EAAA,EAAI,SAAA,IAC/B,GAAA,CAAI,EAAA,EAAI,SAAA,EAAW,UAAA,0BAGnB,GAAA"} |
| {"version":3,"file":"types.mjs","names":[],"sources":["../src/ir/storage-type-instance.ts","../src/ir/sql-storage.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"],"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"} |
| import { n as StorageValueSetInput } from "./storage-value-set-D-jww77l.mjs"; | ||
| //#region src/value-set-derivation-hook.d.ts | ||
| /** | ||
| * SQL-family extension to the framework entity-type authoring registry: a pack's entity-type | ||
| * `factory` output (framework `AuthoringEntityTypeFactoryOutput`) may derive a value-set from an | ||
| * entity it built (e.g. Postgres's `native_enum` deriving its ordered member values). The generic | ||
| * extension-block lowering pass (`contract-psl`'s interpreter) probes each entity-type descriptor's | ||
| * output for this hook after building the entity, and folds a non-undefined result into the same | ||
| * namespace's `valueSet` slot, keyed by the entity's block name. | ||
| * | ||
| * SQL-family concept — the returned shape ({@link StorageValueSetInput}) is SQL-specific, so this | ||
| * hook lives here instead of on the framework `AuthoringEntityTypeFactoryOutput` itself. | ||
| */ | ||
| interface SqlValueSetDerivingEntityTypeOutput { | ||
| /** | ||
| * TypeScript treats method-syntax declarations bivariantly, so a pack's concretely-typed | ||
| * `deriveValueSet(entity: PostgresNativeEnum) => …` is structurally compatible with this | ||
| * interface's `unknown` parameter — no `never`-parameter contravariance bridge needed. | ||
| */ | ||
| deriveValueSet(entity: unknown): StorageValueSetInput | undefined; | ||
| } | ||
| /** Structural check for {@link SqlValueSetDerivingEntityTypeOutput}: no casts. */ | ||
| declare function providesValueSetDerivation(output: unknown): output is SqlValueSetDerivingEntityTypeOutput; | ||
| /** | ||
| * If `output` (an entity-type descriptor's factory output) provides | ||
| * {@link SqlValueSetDerivingEntityTypeOutput.deriveValueSet}, invoke it on `entity` and return the | ||
| * derived value-set; otherwise return `undefined`. `contract-psl`'s generic extension-block | ||
| * lowering pass calls this after building each entity so a value-set-carrying pack entity can | ||
| * contribute its value-set without the pass naming any target discriminator. | ||
| */ | ||
| declare function deriveValueSetFromEntity(output: unknown, entity: unknown): StorageValueSetInput | undefined; | ||
| //#endregion | ||
| export { type SqlValueSetDerivingEntityTypeOutput, deriveValueSetFromEntity, providesValueSetDerivation }; | ||
| //# sourceMappingURL=value-set-derivation-hook.d.mts.map |
| {"version":3,"file":"value-set-derivation-hook.d.mts","names":[],"sources":["../src/value-set-derivation-hook.ts"],"mappings":";;;;;AAaA;;;;;;;;AAMuD;UANtC,mCAAA;EAUyB;;;;;EAJxC,cAAA,CAAe,MAAA,YAAkB,oBAAoB;AAAA;AAMP;AAAA,iBAFhC,0BAAA,CACd,MAAA,YACC,MAAA,IAAU,mCAAmC;;;;;;;;iBAehC,wBAAA,CACd,MAAA,WACA,MAAA,YACC,oBAAoB"} |
| //#region src/value-set-derivation-hook.ts | ||
| /** Structural check for {@link SqlValueSetDerivingEntityTypeOutput}: no casts. */ | ||
| function providesValueSetDerivation(output) { | ||
| if (typeof output !== "object" || output === null || !("deriveValueSet" in output)) return false; | ||
| const { deriveValueSet } = output; | ||
| return typeof deriveValueSet === "function"; | ||
| } | ||
| /** | ||
| * If `output` (an entity-type descriptor's factory output) provides | ||
| * {@link SqlValueSetDerivingEntityTypeOutput.deriveValueSet}, invoke it on `entity` and return the | ||
| * derived value-set; otherwise return `undefined`. `contract-psl`'s generic extension-block | ||
| * lowering pass calls this after building each entity so a value-set-carrying pack entity can | ||
| * contribute its value-set without the pass naming any target discriminator. | ||
| */ | ||
| function deriveValueSetFromEntity(output, entity) { | ||
| if (!providesValueSetDerivation(output)) return void 0; | ||
| return output.deriveValueSet(entity); | ||
| } | ||
| //#endregion | ||
| export { deriveValueSetFromEntity, providesValueSetDerivation }; | ||
| //# sourceMappingURL=value-set-derivation-hook.mjs.map |
| {"version":3,"file":"value-set-derivation-hook.mjs","names":[],"sources":["../src/value-set-derivation-hook.ts"],"sourcesContent":["import type { StorageValueSetInput } from './ir/storage-value-set';\n\n/**\n * SQL-family extension to the framework entity-type authoring registry: a pack's entity-type\n * `factory` output (framework `AuthoringEntityTypeFactoryOutput`) may derive a value-set from an\n * entity it built (e.g. Postgres's `native_enum` deriving its ordered member values). The generic\n * extension-block lowering pass (`contract-psl`'s interpreter) probes each entity-type descriptor's\n * output for this hook after building the entity, and folds a non-undefined result into the same\n * namespace's `valueSet` slot, keyed by the entity's block name.\n *\n * SQL-family concept — the returned shape ({@link StorageValueSetInput}) is SQL-specific, so this\n * hook lives here instead of on the framework `AuthoringEntityTypeFactoryOutput` itself.\n */\nexport interface SqlValueSetDerivingEntityTypeOutput {\n /**\n * TypeScript treats method-syntax declarations bivariantly, so a pack's concretely-typed\n * `deriveValueSet(entity: PostgresNativeEnum) => …` is structurally compatible with this\n * interface's `unknown` parameter — no `never`-parameter contravariance bridge needed.\n */\n deriveValueSet(entity: unknown): StorageValueSetInput | undefined;\n}\n\n/** Structural check for {@link SqlValueSetDerivingEntityTypeOutput}: no casts. */\nexport function providesValueSetDerivation(\n output: unknown,\n): output is SqlValueSetDerivingEntityTypeOutput {\n if (typeof output !== 'object' || output === null || !('deriveValueSet' in output)) {\n return false;\n }\n const { deriveValueSet } = output;\n return typeof deriveValueSet === 'function';\n}\n\n/**\n * If `output` (an entity-type descriptor's factory output) provides\n * {@link SqlValueSetDerivingEntityTypeOutput.deriveValueSet}, invoke it on `entity` and return the\n * derived value-set; otherwise return `undefined`. `contract-psl`'s generic extension-block\n * lowering pass calls this after building each entity so a value-set-carrying pack entity can\n * contribute its value-set without the pass naming any target discriminator.\n */\nexport function deriveValueSetFromEntity(\n output: unknown,\n entity: unknown,\n): StorageValueSetInput | undefined {\n if (!providesValueSetDerivation(output)) return undefined;\n return output.deriveValueSet(entity);\n}\n"],"mappings":";;AAuBA,SAAgB,2BACd,QAC+C;CAC/C,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,EAAE,oBAAoB,SACzE,OAAO;CAET,MAAM,EAAE,mBAAmB;CAC3B,OAAO,OAAO,mBAAmB;AACnC;;;;;;;;AASA,SAAgB,yBACd,QACA,QACkC;CAClC,IAAI,CAAC,2BAA2B,MAAM,GAAG,OAAO,KAAA;CAChD,OAAO,OAAO,eAAe,MAAM;AACrC"} |
| // `string extends keyof SCT` detects the open `Record<string, never>` default that non-emitted contracts carry. | ||
| export type StorageColumnMapAt< | ||
| SCT, | ||
| NsId extends string, | ||
| TableName extends string, | ||
| > = string extends keyof SCT | ||
| ? never | ||
| : NsId extends keyof SCT | ||
| ? string extends keyof SCT[NsId] | ||
| ? never | ||
| : TableName extends keyof SCT[NsId] | ||
| ? SCT[NsId][TableName] | ||
| : never | ||
| : never; | ||
| export type StorageColumnTypeAcrossNamespaces< | ||
| SCT, | ||
| TableName extends string, | ||
| ColumnName extends string, | ||
| > = { | ||
| [Ns in keyof SCT]: TableName extends keyof SCT[Ns] | ||
| ? ColumnName extends keyof SCT[Ns][TableName] | ||
| ? SCT[Ns][TableName][ColumnName] | ||
| : never | ||
| : never; | ||
| }[keyof SCT]; |
| import type { Contract } from '@prisma-next/contract/types'; | ||
| import { | ||
| buildNamespacedEntities, | ||
| buildSingleNamespaceView, | ||
| type DefaultNamespaceEntries, | ||
| type NamespacedEntities, | ||
| type SingleNamespaceView, | ||
| } from '@prisma-next/framework-components/ir'; | ||
| import type { SqlStorage } from './ir/sql-storage'; | ||
| /** | ||
| * The SQL family's statically-named built-in entity kinds. `table` and | ||
| * `valueSet` are promoted to top-level view accessors; pack-contributed kinds | ||
| * (e.g. `policy`) stay under `.entries`. | ||
| */ | ||
| export const SQL_BUILTIN_KINDS = ['table', 'valueSet'] as const; | ||
| export type SqlBuiltinKind = (typeof SQL_BUILTIN_KINDS)[number]; | ||
| type SqlEntries<TContract extends Contract<SqlStorage>> = DefaultNamespaceEntries< | ||
| TContract['storage'] | ||
| >; | ||
| /** | ||
| * The single-namespace SQL accessors: `table`/`valueSet` top-level, pack kinds | ||
| * under `entries`. A target that never emits a built-in kind (SQLite has | ||
| * `sql.enums: false`, so it emits no `valueSet`) resolves that slot to an empty | ||
| * map. | ||
| */ | ||
| export type SqlSingleNamespaceAccessors<TContract extends Contract<SqlStorage>> = | ||
| SingleNamespaceView<SqlEntries<TContract>, SqlBuiltinKind>; | ||
| /** | ||
| * Single-namespace SQL view: the deserialized contract intersected with the | ||
| * by-name accessors, so the value is substitutable for `Contract` while also | ||
| * exposing: | ||
| * - `view.table.<name>` / `view.valueSet.<name>` — built-in kinds, sole | ||
| * namespace unwrapped to the root; pack kinds under `view.entries.<kind>`. | ||
| * - `view.namespace.<id>` — the namespace-keyed entity map (SQLite's sole | ||
| * namespace is `__unbound__`). Mirrors the runtime `db.enums` pattern. | ||
| */ | ||
| export type SqlSingleNamespaceView<TContract extends Contract<SqlStorage>> = TContract & | ||
| SqlSingleNamespaceAccessors<TContract> & { | ||
| readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>; | ||
| }; | ||
| /** | ||
| * Builds the single-namespace SQL view: unwraps the sole namespace's SQL | ||
| * built-in kinds (`table`, `valueSet`) to the root, attaches the namespace-keyed | ||
| * `namespace` map, and layers both over the deserialized contract. Targets with | ||
| * one default namespace (SQLite) call this directly; Postgres qualifies by | ||
| * schema. | ||
| */ | ||
| export function buildSqlSingleNamespaceView<TContract extends Contract<SqlStorage>>( | ||
| contract: TContract, | ||
| ): SqlSingleNamespaceView<TContract> { | ||
| const rootAccessors = buildSingleNamespaceView<SqlSingleNamespaceAccessors<TContract>>( | ||
| contract.storage, | ||
| SQL_BUILTIN_KINDS, | ||
| ); | ||
| const namespace = buildNamespacedEntities< | ||
| NamespacedEntities<TContract['storage'], SqlBuiltinKind> | ||
| >(contract.storage, SQL_BUILTIN_KINDS); | ||
| return { | ||
| ...contract, | ||
| ...rootAccessors, | ||
| namespace, | ||
| }; | ||
| } | ||
| /** | ||
| * Schema-qualified SQL view: the deserialized contract intersected with a single | ||
| * `view.namespace.<id>` member — every schema reached by raw id | ||
| * (`view.namespace.public.table.users`), mirroring the runtime `db.enums.<ns>` | ||
| * keying exactly (the default schema keeps its literal `__unbound__` id). There | ||
| * is NO root schema-name promotion, so there is no collision with contract | ||
| * envelope fields — `view.storage` is always the contract's `storage`. Postgres | ||
| * uses this; SQLite (single default namespace) uses | ||
| * {@link buildSqlSingleNamespaceView}. | ||
| */ | ||
| export type SqlSchemaQualifiedView<TContract extends Contract<SqlStorage>> = TContract & { | ||
| readonly namespace: NamespacedEntities<TContract['storage'], SqlBuiltinKind>; | ||
| }; | ||
| /** | ||
| * Builds the schema-qualified SQL view: attaches the namespace-keyed `namespace` | ||
| * map over the deserialized contract. Postgres uses this. | ||
| */ | ||
| export function buildSqlSchemaQualifiedView<TContract extends Contract<SqlStorage>>( | ||
| contract: TContract, | ||
| ): SqlSchemaQualifiedView<TContract> { | ||
| const namespace = buildNamespacedEntities< | ||
| NamespacedEntities<TContract['storage'], SqlBuiltinKind> | ||
| >(contract.storage, SQL_BUILTIN_KINDS); | ||
| return { | ||
| ...contract, | ||
| namespace, | ||
| }; | ||
| } |
| /** | ||
| * SQL-family extension to the pack authoring contributions: a pack whose | ||
| * `entityTypes` registers entity kinds may implement a batch lowering hook | ||
| * that turns author-declared pack-entity handles (the generic `entities` | ||
| * list on the TS contract input) into `entries` rows. | ||
| * | ||
| * The generic contract build (`contract-ts`) owns the kind-agnostic walk: it | ||
| * groups handles by the pack that registered each `entityKind`, resolves | ||
| * each handle's declared model refs to storage table coordinates using the | ||
| * same model→table maps the relation lowering uses, and calls the owning | ||
| * pack's hook once with all of its claimed handles — batch, so the hook's | ||
| * diagnostics can see sibling handles. Neither the walk nor these types name | ||
| * any specific entity kind. | ||
| * | ||
| * SQL-family concept — the resolved-ref shape is a table coordinate, so the | ||
| * hook lives here beside {@link ../value-set-derivation-hook} instead of on | ||
| * the framework contributions type. | ||
| */ | ||
| /** | ||
| * An authored pack-entity handle: branded by the `entityKind` its owning | ||
| * pack registered, optionally declaring model refs under `refs` (actual | ||
| * model-handle objects, resolved by the generic walk before lowering). | ||
| */ | ||
| export interface PackEntityHandle { | ||
| readonly entityKind: string; | ||
| readonly refs?: Readonly<Record<string, unknown>>; | ||
| } | ||
| /** | ||
| * A declared model ref after the generic walk resolved it: a storage table | ||
| * coordinate for a model of this contract, the coordinate plus `spaceId` for | ||
| * a cross-space (extensionModel) handle, or `unresolved` when the handle | ||
| * does not correspond to any model in the contract. `modelName` is carried | ||
| * for diagnostics where the handle declares one. | ||
| */ | ||
| export type ResolvedEntityHandleRef = | ||
| | { | ||
| readonly kind: 'resolved'; | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly modelName?: string; | ||
| } | ||
| | { | ||
| readonly kind: 'cross-space'; | ||
| readonly spaceId: string; | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly modelName?: string; | ||
| } | ||
| | { | ||
| readonly kind: 'unresolved'; | ||
| readonly modelName?: string; | ||
| }; | ||
| /** One claimed handle paired with its resolved declared refs. */ | ||
| export interface ResolvedPackEntityHandle { | ||
| readonly handle: PackEntityHandle; | ||
| readonly refs: Readonly<Record<string, ResolvedEntityHandleRef>>; | ||
| } | ||
| export interface EntityHandleLoweringInput { | ||
| /** Every handle in the `entities` list whose `entityKind` this pack registered, in authored order. */ | ||
| readonly handles: readonly ResolvedPackEntityHandle[]; | ||
| readonly defaultNamespaceId: string; | ||
| } | ||
| /** One lowered entity row: filed into `storage.namespaces[namespaceId].entries[entityKind][key]`. */ | ||
| export interface LoweredPackEntity { | ||
| readonly namespaceId: string; | ||
| readonly entityKind: string; | ||
| readonly key: string; | ||
| readonly entity: unknown; | ||
| } | ||
| export interface SqlEntityHandleLoweringContribution { | ||
| /** | ||
| * Method syntax keeps the declaration bivariant, so a pack's concretely | ||
| * typed implementation stays structurally compatible (the same convention | ||
| * as `SqlValueSetDerivingEntityTypeOutput.deriveValueSet`). | ||
| */ | ||
| lowerEntityHandles(input: EntityHandleLoweringInput): readonly LoweredPackEntity[]; | ||
| } | ||
| /** Structural check for {@link SqlEntityHandleLoweringContribution}: no casts. */ | ||
| export function providesEntityHandleLowering( | ||
| authoring: unknown, | ||
| ): authoring is SqlEntityHandleLoweringContribution { | ||
| if (typeof authoring !== 'object' || authoring === null || !('lowerEntityHandles' in authoring)) { | ||
| return false; | ||
| } | ||
| const { lowerEntityHandles } = authoring; | ||
| return typeof lowerEntityHandles === 'function'; | ||
| } | ||
| /** | ||
| * PSL-side twin of {@link ResolvedEntityHandleRef}: the family interpreter | ||
| * resolves an extension block's descriptor-declared model ref parameters | ||
| * (`{ kind: 'ref', refKind: 'model' }`) to storage table names and annotates | ||
| * the block with this map (keyed by parameter name) before invoking the | ||
| * entity factory. An unresolved required ref is the interpreter's | ||
| * diagnostic; a factory never sees one. | ||
| */ | ||
| export type ResolvedPslModelRefs = Readonly<Record<string, { readonly tableName: string }>>; |
| export type { | ||
| SqlBuiltinKind, | ||
| SqlSchemaQualifiedView, | ||
| SqlSingleNamespaceAccessors, | ||
| SqlSingleNamespaceView, | ||
| } from '../contract-view'; | ||
| export { | ||
| buildSqlSchemaQualifiedView, | ||
| buildSqlSingleNamespaceView, | ||
| SQL_BUILTIN_KINDS, | ||
| } from '../contract-view'; |
| export { | ||
| type EntityHandleLoweringInput, | ||
| type LoweredPackEntity, | ||
| type PackEntityHandle, | ||
| providesEntityHandleLowering, | ||
| type ResolvedEntityHandleRef, | ||
| type ResolvedPackEntityHandle, | ||
| type ResolvedPslModelRefs, | ||
| type SqlEntityHandleLoweringContribution, | ||
| } from '../entity-handle-lowering-hook'; |
| export type { SqlValueSetDerivingEntityTypeOutput } from '../value-set-derivation-hook'; | ||
| export { deriveValueSetFromEntity, providesValueSetDerivation } from '../value-set-derivation-hook'; |
| import type { StorageValueSetInput } from './ir/storage-value-set'; | ||
| /** | ||
| * SQL-family extension to the framework entity-type authoring registry: a pack's entity-type | ||
| * `factory` output (framework `AuthoringEntityTypeFactoryOutput`) may derive a value-set from an | ||
| * entity it built (e.g. Postgres's `native_enum` deriving its ordered member values). The generic | ||
| * extension-block lowering pass (`contract-psl`'s interpreter) probes each entity-type descriptor's | ||
| * output for this hook after building the entity, and folds a non-undefined result into the same | ||
| * namespace's `valueSet` slot, keyed by the entity's block name. | ||
| * | ||
| * SQL-family concept — the returned shape ({@link StorageValueSetInput}) is SQL-specific, so this | ||
| * hook lives here instead of on the framework `AuthoringEntityTypeFactoryOutput` itself. | ||
| */ | ||
| export interface SqlValueSetDerivingEntityTypeOutput { | ||
| /** | ||
| * TypeScript treats method-syntax declarations bivariantly, so a pack's concretely-typed | ||
| * `deriveValueSet(entity: PostgresNativeEnum) => …` is structurally compatible with this | ||
| * interface's `unknown` parameter — no `never`-parameter contravariance bridge needed. | ||
| */ | ||
| deriveValueSet(entity: unknown): StorageValueSetInput | undefined; | ||
| } | ||
| /** Structural check for {@link SqlValueSetDerivingEntityTypeOutput}: no casts. */ | ||
| export function providesValueSetDerivation( | ||
| output: unknown, | ||
| ): output is SqlValueSetDerivingEntityTypeOutput { | ||
| if (typeof output !== 'object' || output === null || !('deriveValueSet' in output)) { | ||
| return false; | ||
| } | ||
| const { deriveValueSet } = output; | ||
| return typeof deriveValueSet === 'function'; | ||
| } | ||
| /** | ||
| * If `output` (an entity-type descriptor's factory output) provides | ||
| * {@link SqlValueSetDerivingEntityTypeOutput.deriveValueSet}, invoke it on `entity` and return the | ||
| * derived value-set; otherwise return `undefined`. `contract-psl`'s generic extension-block | ||
| * lowering pass calls this after building each entity so a value-set-carrying pack entity can | ||
| * contribute its value-set without the pass naming any target discriminator. | ||
| */ | ||
| export function deriveValueSetFromEntity( | ||
| output: unknown, | ||
| entity: unknown, | ||
| ): StorageValueSetInput | undefined { | ||
| if (!providesValueSetDerivation(output)) return undefined; | ||
| return output.deriveValueSet(entity); | ||
| } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"canonicalization-hooks.d.mts","names":[],"sources":["../src/canonicalization-hooks.ts"],"mappings":";;;cAwBa,gCAAA;EAAA,SACF,mBAAA,EAAqB,sBAAA;EAAA,SACrB,WAAA,EAAa,WAAW;AAAA"} | ||
| {"version":3,"file":"canonicalization-hooks.d.mts","names":[],"sources":["../src/canonicalization-hooks.ts"],"mappings":";;;cAqDa,gCAAA;EAAA,SACF,mBAAA,EAAqB,sBAAA;EAAA,SACrB,WAAA,EAAa,WAAW;AAAA"} |
@@ -1,53 +0,83 @@ | ||
| import { createPreserveEmptyPredicate, createStorageSort } from "@prisma-next/contract/hashing-utils"; | ||
| const sqlContractCanonicalizationHooks = { | ||
| shouldPreserveEmpty: createPreserveEmptyPredicate([ | ||
| import { createPreserveEmptyPredicate, createStorageSort, matchesPathPattern } from "@prisma-next/contract/hashing-utils"; | ||
| //#region src/canonicalization-hooks.ts | ||
| const preserveEmptyPatterns = [ | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table" | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*" | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table" | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*" | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| [ | ||
| "uniques", | ||
| "indexes", | ||
| "foreignKeys" | ||
| ] | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| "foreignKeys", | ||
| ["constraint", "index"] | ||
| "uniques", | ||
| "indexes", | ||
| "foreignKeys" | ||
| ] | ||
| ]), | ||
| sortStorage: createStorageSort([{ | ||
| path: [ | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*" | ||
| ], | ||
| arrayKeys: ["indexes", "uniques"] | ||
| }]) | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| "foreignKeys", | ||
| ["constraint", "index"] | ||
| ], | ||
| [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| "columns", | ||
| "*", | ||
| "default", | ||
| "value" | ||
| ] | ||
| ]; | ||
| const columnDefaultValuePrefix = [ | ||
| "storage", | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*", | ||
| "columns", | ||
| "*", | ||
| "default", | ||
| "value" | ||
| ]; | ||
| const isColumnDefaultValuePath = (path) => path.length >= columnDefaultValuePrefix.length && matchesPathPattern(path.slice(0, columnDefaultValuePrefix.length), columnDefaultValuePrefix); | ||
| const sortTargets = [{ | ||
| path: [ | ||
| "namespaces", | ||
| "*", | ||
| "entries", | ||
| "table", | ||
| "*" | ||
| ], | ||
| arrayKeys: ["indexes", "uniques"] | ||
| }]; | ||
| const matchesPreserveEmptyPattern = createPreserveEmptyPredicate(preserveEmptyPatterns); | ||
| const shouldPreserveEmpty = (path) => isColumnDefaultValuePath(path) || matchesPreserveEmptyPattern(path); | ||
| const sqlContractCanonicalizationHooks = { | ||
| shouldPreserveEmpty, | ||
| sortStorage: createStorageSort(sortTargets) | ||
| }; | ||
@@ -54,0 +84,0 @@ //#endregion |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"canonicalization-hooks.mjs","names":[],"sources":["../src/canonicalization-hooks.ts"],"sourcesContent":["import type { PreserveEmptyPredicate, StorageSort } from '@prisma-next/contract/hashing';\nimport {\n createPreserveEmptyPredicate,\n createStorageSort,\n type NamedArraySortTarget,\n type PathPattern,\n} from '@prisma-next/contract/hashing-utils';\n\nconst preserveEmptyPatterns = [\n ['storage', 'namespaces', '*', 'entries', 'table'],\n ['storage', 'namespaces', '*', 'entries', 'table', '*'],\n ['storage', 'namespaces', '*', 'entries', 'table', '*', ['uniques', 'indexes', 'foreignKeys']],\n ['storage', 'namespaces', '*', 'entries', 'table', '*', 'foreignKeys', ['constraint', 'index']],\n] as const satisfies readonly PathPattern[];\n\nconst sortTargets = [\n { path: ['namespaces', '*', 'entries', 'table', '*'], arrayKeys: ['indexes', 'uniques'] },\n] as const satisfies readonly NamedArraySortTarget[];\n\nconst shouldPreserveEmpty: PreserveEmptyPredicate =\n createPreserveEmptyPredicate(preserveEmptyPatterns);\n\nconst sortStorage: StorageSort = createStorageSort(sortTargets);\n\nexport const sqlContractCanonicalizationHooks: {\n readonly shouldPreserveEmpty: PreserveEmptyPredicate;\n readonly sortStorage: StorageSort;\n} = {\n shouldPreserveEmpty,\n sortStorage,\n};\n"],"mappings":";AAwBA,MAAa,mCAGT;CACF,qBARA,6BAA6B;EAX7B;GAAC;GAAW;GAAc;GAAK;GAAW;EAAO;EACjD;GAAC;GAAW;GAAc;GAAK;GAAW;GAAS;EAAG;EACtD;GAAC;GAAW;GAAc;GAAK;GAAW;GAAS;GAAK;IAAC;IAAW;IAAW;GAAa;EAAC;EAC7F;GAAC;GAAW;GAAc;GAAK;GAAW;GAAS;GAAK;GAAe,CAAC,cAAc,OAAO;EAAC;CAQjE,CAQ7B;CACA,aAP+B,kBAAkB,CANjD;EAAE,MAAM;GAAC;GAAc;GAAK;GAAW;GAAS;EAAG;EAAG,WAAW,CAAC,WAAW,SAAS;CAAE,CAMvC,CAOjD;AACF"} | ||
| {"version":3,"file":"canonicalization-hooks.mjs","names":[],"sources":["../src/canonicalization-hooks.ts"],"sourcesContent":["import type { PreserveEmptyPredicate, StorageSort } from '@prisma-next/contract/hashing';\nimport {\n createPreserveEmptyPredicate,\n createStorageSort,\n matchesPathPattern,\n type NamedArraySortTarget,\n type PathPattern,\n} from '@prisma-next/contract/hashing-utils';\n\nconst preserveEmptyPatterns = [\n ['storage', 'namespaces', '*', 'entries', 'table'],\n ['storage', 'namespaces', '*', 'entries', 'table', '*'],\n ['storage', 'namespaces', '*', 'entries', 'table', '*', ['uniques', 'indexes', 'foreignKeys']],\n ['storage', 'namespaces', '*', 'entries', 'table', '*', 'foreignKeys', ['constraint', 'index']],\n // A column default's literal payload is data, not shape — `{ kind:\n // 'literal', value: false }` (or `value: []`) must survive the\n // default-omission walk or the emitted contract fails its own\n // validation on the next read (PN-CLI-4003 on `Boolean @default(false)`).\n ['storage', 'namespaces', '*', 'entries', 'table', '*', 'columns', '*', 'default', 'value'],\n] as const satisfies readonly PathPattern[];\n\n// A literal column default's value is user data, not omittable structure:\n// `@default(false)` (and empty objects/arrays at any depth inside the value)\n// must survive canonicalization, or the emitted contract fails the runtime's\n// structural validation with `default.value … (was missing)`.\nconst columnDefaultValuePrefix = [\n 'storage',\n 'namespaces',\n '*',\n 'entries',\n 'table',\n '*',\n 'columns',\n '*',\n 'default',\n 'value',\n] as const satisfies PathPattern;\n\nconst isColumnDefaultValuePath = (path: readonly string[]): boolean =>\n path.length >= columnDefaultValuePrefix.length &&\n matchesPathPattern(path.slice(0, columnDefaultValuePrefix.length), columnDefaultValuePrefix);\n\nconst sortTargets = [\n { path: ['namespaces', '*', 'entries', 'table', '*'], arrayKeys: ['indexes', 'uniques'] },\n] as const satisfies readonly NamedArraySortTarget[];\n\nconst matchesPreserveEmptyPattern = createPreserveEmptyPredicate(preserveEmptyPatterns);\n\nconst shouldPreserveEmpty: PreserveEmptyPredicate = (path) =>\n isColumnDefaultValuePath(path) || matchesPreserveEmptyPattern(path);\n\nconst sortStorage: StorageSort = createStorageSort(sortTargets);\n\nexport const sqlContractCanonicalizationHooks: {\n readonly shouldPreserveEmpty: PreserveEmptyPredicate;\n readonly sortStorage: StorageSort;\n} = {\n shouldPreserveEmpty,\n sortStorage,\n};\n"],"mappings":";;AASA,MAAM,wBAAwB;CAC5B;EAAC;EAAW;EAAc;EAAK;EAAW;CAAO;CACjD;EAAC;EAAW;EAAc;EAAK;EAAW;EAAS;CAAG;CACtD;EAAC;EAAW;EAAc;EAAK;EAAW;EAAS;EAAK;GAAC;GAAW;GAAW;EAAa;CAAC;CAC7F;EAAC;EAAW;EAAc;EAAK;EAAW;EAAS;EAAK;EAAe,CAAC,cAAc,OAAO;CAAC;CAK9F;EAAC;EAAW;EAAc;EAAK;EAAW;EAAS;EAAK;EAAW;EAAK;EAAW;CAAO;AAC5F;AAMA,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,4BAA4B,SAChC,KAAK,UAAU,yBAAyB,UACxC,mBAAmB,KAAK,MAAM,GAAG,yBAAyB,MAAM,GAAG,wBAAwB;AAE7F,MAAM,cAAc,CAClB;CAAE,MAAM;EAAC;EAAc;EAAK;EAAW;EAAS;CAAG;CAAG,WAAW,CAAC,WAAW,SAAS;AAAE,CAC1F;AAEA,MAAM,8BAA8B,6BAA6B,qBAAqB;AAEtF,MAAM,uBAA+C,SACnD,yBAAyB,IAAI,KAAK,4BAA4B,IAAI;AAIpE,MAAa,mCAGT;CACF;CACA,aAP+B,kBAAkB,WAOjD;AACF"} |
@@ -1,2 +0,3 @@ | ||
| import { i as StorageTableInput, n as StorageValueSetInput, r as StorageTable, t as StorageValueSet } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { n as StorageTableInput, t as StorageTable } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { n as StorageValueSetInput, t as StorageValueSet } from "./storage-value-set-D-jww77l.mjs"; | ||
| import { AnyEntityKindDescriptor, EntityKindDescriptor } from "@prisma-next/framework-components/ir"; | ||
@@ -3,0 +4,0 @@ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"entity-kinds.d.mts","names":[],"sources":["../src/entity-kinds.ts"],"mappings":";;;;cAQa,eAAA,EAAiB,oBAAA,CAAqB,iBAAA,EAAmB,YAAA;AAAA,cAMzD,kBAAA,EAAoB,oBAAA,CAAqB,oBAAA,EAAsB,eAAA;;;;;;;;;iBAc5D,qBAAA,CACd,SAAA,YAAoB,uBAAA,KACnB,WAAA,SAAoB,uBAAA"} | ||
| {"version":3,"file":"entity-kinds.d.mts","names":[],"sources":["../src/entity-kinds.ts"],"mappings":";;;;;cAQa,eAAA,EAAiB,oBAAA,CAAqB,iBAAA,EAAmB,YAAA;AAAA,cAMzD,kBAAA,EAAoB,oBAAA,CAAqB,oBAAA,EAAsB,eAAA;AAN5E;;;;;;;;AAAA,iBAoBgB,qBAAA,CACd,SAAA,YAAoB,uBAAA,KACnB,WAAA,SAAoB,uBAAA"} |
@@ -1,2 +0,2 @@ | ||
| import { n as tableEntityKind, r as valueSetEntityKind, t as composeSqlEntityKinds } from "./entity-kinds-Cl36zL5j.mjs"; | ||
| import { n as tableEntityKind, r as valueSetEntityKind, t as composeSqlEntityKinds } from "./entity-kinds-BEPZdFBN.mjs"; | ||
| export { composeSqlEntityKinds, tableEntityKind, valueSetEntityKind }; |
@@ -1,8 +0,10 @@ | ||
| import { t as ForeignKey } from "./foreign-key-BATxB95l.mjs"; | ||
| import { a as UniqueConstraint, c as StorageColumnInput, d as PrimaryKey, l as Index, r as StorageTable, s as StorageColumn } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { b as SqlModelFieldStorage, f as ForeignKeyOptions, x as SqlModelStorage } from "./types-B1N8w0I2.mjs"; | ||
| import { a as StorageColumn, l as PrimaryKey, o as StorageColumnInput, r as UniqueConstraint, s as Index, t as StorageTable } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { t as ForeignKey } from "./foreign-key-DM1UTydh.mjs"; | ||
| import { T as SqlModelStorage, m as ForeignKeyOptions, w as SqlModelFieldStorage } from "./types-zBvpNCmg.mjs"; | ||
| import { ScalarFieldType } from "@prisma-next/contract/types"; | ||
| //#region src/factories.d.ts | ||
| declare function col(nativeType: string, codecId: string, nullable?: boolean): StorageColumn; | ||
| declare function col(nativeType: string, codecId: string, nullable?: boolean, opts?: { | ||
| readonly many?: boolean; | ||
| }): StorageColumn; | ||
| declare function pk(...columns: readonly string[]): PrimaryKey; | ||
@@ -9,0 +11,0 @@ declare function unique(...columns: readonly string[]): UniqueConstraint; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"factories.d.mts","names":[],"sources":["../src/factories.ts"],"mappings":";;;;;;iBAgBgB,GAAA,CAAI,UAAA,UAAoB,OAAA,UAAiB,QAAA,aAAmB,aAAa;AAAA,iBAIzE,EAAA,IAAM,OAAA,sBAA6B,UAAU;AAAA,iBAI7C,MAAA,IAAU,OAAA,sBAA6B,gBAAgB;AAAA,iBAIvD,KAAA,IAAS,OAAA,sBAA6B,KAAK;AAAA,iBAI3C,EAAA,CACd,YAAA,UACA,UAAA,qBACA,eAAA,UACA,aAAA,qBACA,IAAA,GAAO,iBAAA;EAAsB,UAAA;EAAsB,KAAA;EAAiB,WAAA;AAAA,IACnE,UAAU;AAAA,iBAcG,KAAA,CACd,OAAA,EAAS,MAAA,SAAe,aAAA,GAAgB,kBAAA,GACxC,IAAA;EACE,EAAA,GAAK,UAAA;EACL,OAAA,YAAmB,gBAAA;EACnB,OAAA,YAAmB,KAAA;EACnB,GAAA,YAAe,UAAA;AAAA,IAEhB,YAAA;AAAA,iBAUa,KAAA,CACd,SAAA,UACA,MAAA,EAAQ,MAAA,SAAe,oBAAA,GACvB,SAAA,GAAW,MAAA,mBACX,WAAA;EAEA,OAAA,EAAS,eAAA;EACT,MAAA,EAAQ,MAAA;IAAA,SAA0B,QAAA;IAAA,SAA4B,IAAA,EAAM,eAAA;EAAA;EACpE,SAAA,EAAW,MAAA;AAAA"} | ||
| {"version":3,"file":"factories.d.mts","names":[],"sources":["../src/factories.ts"],"mappings":";;;;;;iBAgBgB,GAAA,CACd,UAAA,UACA,OAAA,UACA,QAAA,YACA,IAAA;EAAA,SAAkB,IAAA;AAAA,IACjB,aAAa;AAAA,iBASA,EAAA,IAAM,OAAA,sBAA6B,UAAU;AAAA,iBAI7C,MAAA,IAAU,OAAA,sBAA6B,gBAAgB;AAAA,iBAIvD,KAAA,IAAS,OAAA,sBAA6B,KAAK;AAAA,iBAI3C,EAAA,CACd,YAAA,UACA,UAAA,qBACA,eAAA,UACA,aAAA,qBACA,IAAA,GAAO,iBAAA;EAAsB,UAAA;EAAsB,KAAA;EAAiB,WAAA;AAAA,IACnE,UAAU;AAAA,iBAcG,KAAA,CACd,OAAA,EAAS,MAAA,SAAe,aAAA,GAAgB,kBAAA,GACxC,IAAA;EACE,EAAA,GAAK,UAAA;EACL,OAAA,YAAmB,gBAAA;EACnB,OAAA,YAAmB,KAAA;EACnB,GAAA,YAAe,UAAA;AAAA,IAEhB,YAAA;AAAA,iBAUa,KAAA,CACd,SAAA,UACA,MAAA,EAAQ,MAAA,SAAe,oBAAA,GACvB,SAAA,GAAW,MAAA,mBACX,WAAA;EAEA,OAAA,EAAS,eAAA;EACT,MAAA,EAAQ,MAAA;IAAA,SAA0B,QAAA;IAAA,SAA4B,IAAA,EAAM,eAAA;EAAA;EACpE,SAAA,EAAW,MAAA;AAAA"} |
@@ -1,11 +0,12 @@ | ||
| import { a as StorageTable, c as Index, l as PrimaryKey, o as UniqueConstraint, s as StorageColumn, u as ForeignKey } from "./entity-kinds-Cl36zL5j.mjs"; | ||
| import { r as applyFkDefaults } from "./types-B-eiQXff.mjs"; | ||
| import { a as PrimaryKey, i as Index, n as UniqueConstraint, o as ForeignKey, r as StorageColumn, t as StorageTable } from "./storage-table-y6R6pxyI.mjs"; | ||
| import { r as applyFkDefaults } from "./types-Hkxybhdj.mjs"; | ||
| import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir"; | ||
| import { asNamespaceId } from "@prisma-next/contract/types"; | ||
| //#region src/factories.ts | ||
| function col(nativeType, codecId, nullable = false) { | ||
| function col(nativeType, codecId, nullable = false, opts) { | ||
| return new StorageColumn({ | ||
| nativeType, | ||
| codecId, | ||
| nullable | ||
| nullable, | ||
| ...opts?.many !== void 0 && { many: opts.many } | ||
| }); | ||
@@ -12,0 +13,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"factories.mjs","names":[],"sources":["../src/factories.ts"],"sourcesContent":["import { asNamespaceId, type ScalarFieldType } from '@prisma-next/contract/types';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n applyFkDefaults,\n ForeignKey,\n type ForeignKeyOptions,\n Index,\n PrimaryKey,\n type SqlModelFieldStorage,\n type SqlModelStorage,\n StorageColumn,\n type StorageColumnInput,\n StorageTable,\n UniqueConstraint,\n} from './types';\n\nexport function col(nativeType: string, codecId: string, nullable = false): StorageColumn {\n return new StorageColumn({ nativeType, codecId, nullable });\n}\n\nexport function pk(...columns: readonly string[]): PrimaryKey {\n return new PrimaryKey({ columns });\n}\n\nexport function unique(...columns: readonly string[]): UniqueConstraint {\n return new UniqueConstraint({ columns });\n}\n\nexport function index(...columns: readonly string[]): Index {\n return new Index({ columns });\n}\n\nexport function fk(\n srcTableName: string,\n srcColumns: readonly string[],\n targetTableName: string,\n targetColumns: readonly string[],\n opts?: ForeignKeyOptions & { constraint?: boolean; index?: boolean; namespaceId?: string },\n): ForeignKey {\n const defaults = applyFkDefaults({ constraint: opts?.constraint, index: opts?.index });\n const namespaceId = asNamespaceId(opts?.namespaceId ?? UNBOUND_NAMESPACE_ID);\n return new ForeignKey({\n source: { namespaceId, tableName: srcTableName, columns: srcColumns },\n target: { namespaceId, tableName: targetTableName, columns: targetColumns },\n ...(opts?.name !== undefined && { name: opts.name }),\n ...(opts?.onDelete !== undefined && { onDelete: opts.onDelete }),\n ...(opts?.onUpdate !== undefined && { onUpdate: opts.onUpdate }),\n constraint: defaults.constraint,\n index: defaults.index,\n });\n}\n\nexport function table(\n columns: Record<string, StorageColumn | StorageColumnInput>,\n opts?: {\n pk?: PrimaryKey;\n uniques?: readonly UniqueConstraint[];\n indexes?: readonly Index[];\n fks?: readonly ForeignKey[];\n },\n): StorageTable {\n return new StorageTable({\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 tableName: string,\n fields: Record<string, SqlModelFieldStorage>,\n relations: Record<string, unknown> = {},\n namespaceId: string = UNBOUND_NAMESPACE_ID,\n): {\n storage: SqlModelStorage;\n fields: Record<string, { readonly nullable: boolean; readonly type: ScalarFieldType }>;\n relations: Record<string, unknown>;\n} {\n const storage: SqlModelStorage = { table: tableName, namespaceId, fields };\n const domainFields = Object.fromEntries(\n Object.entries(fields).map(([name, field]) => [\n name,\n {\n nullable: field.nullable ?? false,\n type: { kind: 'scalar' as const, codecId: field.codecId ?? 'core/unknown@1' },\n },\n ]),\n ) as Record<string, { nullable: boolean; type: ScalarFieldType }>;\n return {\n storage,\n fields: domainFields,\n relations,\n };\n}\n"],"mappings":";;;;;AAgBA,SAAgB,IAAI,YAAoB,SAAiB,WAAW,OAAsB;CACxF,OAAO,IAAI,cAAc;EAAE;EAAY;EAAS;CAAS,CAAC;AAC5D;AAEA,SAAgB,GAAG,GAAG,SAAwC;CAC5D,OAAO,IAAI,WAAW,EAAE,QAAQ,CAAC;AACnC;AAEA,SAAgB,OAAO,GAAG,SAA8C;CACtE,OAAO,IAAI,iBAAiB,EAAE,QAAQ,CAAC;AACzC;AAEA,SAAgB,MAAM,GAAG,SAAmC;CAC1D,OAAO,IAAI,MAAM,EAAE,QAAQ,CAAC;AAC9B;AAEA,SAAgB,GACd,cACA,YACA,iBACA,eACA,MACY;CACZ,MAAM,WAAW,gBAAgB;EAAE,YAAY,MAAM;EAAY,OAAO,MAAM;CAAM,CAAC;CACrF,MAAM,cAAc,cAAc,MAAM,eAAe,oBAAoB;CAC3E,OAAO,IAAI,WAAW;EACpB,QAAQ;GAAE;GAAa,WAAW;GAAc,SAAS;EAAW;EACpE,QAAQ;GAAE;GAAa,WAAW;GAAiB,SAAS;EAAc;EAC1E,GAAI,MAAM,SAAS,KAAA,KAAa,EAAE,MAAM,KAAK,KAAK;EAClD,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;EAC9D,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;EAC9D,YAAY,SAAS;EACrB,OAAO,SAAS;CAClB,CAAC;AACH;AAEA,SAAgB,MACd,SACA,MAMc;CACd,OAAO,IAAI,aAAa;EACtB;EACA,GAAI,MAAM,OAAO,KAAA,KAAa,EAAE,YAAY,KAAK,GAAG;EACpD,SAAS,MAAM,WAAW,CAAC;EAC3B,SAAS,MAAM,WAAW,CAAC;EAC3B,aAAa,MAAM,OAAO,CAAC;CAC7B,CAAC;AACH;AAEA,SAAgB,MACd,WACA,QACA,YAAqC,CAAC,GACtC,cAAsB,sBAKtB;CAWA,OAAO;EACL,SAAA;GAXiC,OAAO;GAAW;GAAa;EAW1D;EACN,QAXmB,OAAO,YAC1B,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAC5C,MACA;GACE,UAAU,MAAM,YAAY;GAC5B,MAAM;IAAE,MAAM;IAAmB,SAAS,MAAM,WAAW;GAAiB;EAC9E,CACF,CAAC,CAIkB;EACnB;CACF;AACF"} | ||
| {"version":3,"file":"factories.mjs","names":[],"sources":["../src/factories.ts"],"sourcesContent":["import { asNamespaceId, type ScalarFieldType } from '@prisma-next/contract/types';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n applyFkDefaults,\n ForeignKey,\n type ForeignKeyOptions,\n Index,\n PrimaryKey,\n type SqlModelFieldStorage,\n type SqlModelStorage,\n StorageColumn,\n type StorageColumnInput,\n StorageTable,\n UniqueConstraint,\n} from './types';\n\nexport function col(\n nativeType: string,\n codecId: string,\n nullable = false,\n opts?: { readonly many?: boolean },\n): StorageColumn {\n return new StorageColumn({\n nativeType,\n codecId,\n nullable,\n ...(opts?.many !== undefined && { many: opts.many }),\n });\n}\n\nexport function pk(...columns: readonly string[]): PrimaryKey {\n return new PrimaryKey({ columns });\n}\n\nexport function unique(...columns: readonly string[]): UniqueConstraint {\n return new UniqueConstraint({ columns });\n}\n\nexport function index(...columns: readonly string[]): Index {\n return new Index({ columns });\n}\n\nexport function fk(\n srcTableName: string,\n srcColumns: readonly string[],\n targetTableName: string,\n targetColumns: readonly string[],\n opts?: ForeignKeyOptions & { constraint?: boolean; index?: boolean; namespaceId?: string },\n): ForeignKey {\n const defaults = applyFkDefaults({ constraint: opts?.constraint, index: opts?.index });\n const namespaceId = asNamespaceId(opts?.namespaceId ?? UNBOUND_NAMESPACE_ID);\n return new ForeignKey({\n source: { namespaceId, tableName: srcTableName, columns: srcColumns },\n target: { namespaceId, tableName: targetTableName, columns: targetColumns },\n ...(opts?.name !== undefined && { name: opts.name }),\n ...(opts?.onDelete !== undefined && { onDelete: opts.onDelete }),\n ...(opts?.onUpdate !== undefined && { onUpdate: opts.onUpdate }),\n constraint: defaults.constraint,\n index: defaults.index,\n });\n}\n\nexport function table(\n columns: Record<string, StorageColumn | StorageColumnInput>,\n opts?: {\n pk?: PrimaryKey;\n uniques?: readonly UniqueConstraint[];\n indexes?: readonly Index[];\n fks?: readonly ForeignKey[];\n },\n): StorageTable {\n return new StorageTable({\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 tableName: string,\n fields: Record<string, SqlModelFieldStorage>,\n relations: Record<string, unknown> = {},\n namespaceId: string = UNBOUND_NAMESPACE_ID,\n): {\n storage: SqlModelStorage;\n fields: Record<string, { readonly nullable: boolean; readonly type: ScalarFieldType }>;\n relations: Record<string, unknown>;\n} {\n const storage: SqlModelStorage = { table: tableName, namespaceId, fields };\n const domainFields = Object.fromEntries(\n Object.entries(fields).map(([name, field]) => [\n name,\n {\n nullable: field.nullable ?? false,\n type: { kind: 'scalar' as const, codecId: field.codecId ?? 'core/unknown@1' },\n },\n ]),\n ) as Record<string, { nullable: boolean; type: ScalarFieldType }>;\n return {\n storage,\n fields: domainFields,\n relations,\n };\n}\n"],"mappings":";;;;;AAgBA,SAAgB,IACd,YACA,SACA,WAAW,OACX,MACe;CACf,OAAO,IAAI,cAAc;EACvB;EACA;EACA;EACA,GAAI,MAAM,SAAS,KAAA,KAAa,EAAE,MAAM,KAAK,KAAK;CACpD,CAAC;AACH;AAEA,SAAgB,GAAG,GAAG,SAAwC;CAC5D,OAAO,IAAI,WAAW,EAAE,QAAQ,CAAC;AACnC;AAEA,SAAgB,OAAO,GAAG,SAA8C;CACtE,OAAO,IAAI,iBAAiB,EAAE,QAAQ,CAAC;AACzC;AAEA,SAAgB,MAAM,GAAG,SAAmC;CAC1D,OAAO,IAAI,MAAM,EAAE,QAAQ,CAAC;AAC9B;AAEA,SAAgB,GACd,cACA,YACA,iBACA,eACA,MACY;CACZ,MAAM,WAAW,gBAAgB;EAAE,YAAY,MAAM;EAAY,OAAO,MAAM;CAAM,CAAC;CACrF,MAAM,cAAc,cAAc,MAAM,eAAe,oBAAoB;CAC3E,OAAO,IAAI,WAAW;EACpB,QAAQ;GAAE;GAAa,WAAW;GAAc,SAAS;EAAW;EACpE,QAAQ;GAAE;GAAa,WAAW;GAAiB,SAAS;EAAc;EAC1E,GAAI,MAAM,SAAS,KAAA,KAAa,EAAE,MAAM,KAAK,KAAK;EAClD,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;EAC9D,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,KAAK,SAAS;EAC9D,YAAY,SAAS;EACrB,OAAO,SAAS;CAClB,CAAC;AACH;AAEA,SAAgB,MACd,SACA,MAMc;CACd,OAAO,IAAI,aAAa;EACtB;EACA,GAAI,MAAM,OAAO,KAAA,KAAa,EAAE,YAAY,KAAK,GAAG;EACpD,SAAS,MAAM,WAAW,CAAC;EAC3B,SAAS,MAAM,WAAW,CAAC;EAC3B,aAAa,MAAM,OAAO,CAAC;CAC7B,CAAC;AACH;AAEA,SAAgB,MACd,WACA,QACA,YAAqC,CAAC,GACtC,cAAsB,sBAKtB;CAWA,OAAO;EACL,SAAA;GAXiC,OAAO;GAAW;GAAa;EAW1D;EACN,QAXmB,OAAO,YAC1B,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAC5C,MACA;GACE,UAAU,MAAM,YAAY;GAC5B,MAAM;IAAE,MAAM;IAAmB,SAAS,MAAM,WAAW;GAAiB;EAC9E,CACF,CAAC,CAIkB;EACnB;CACF;AACF"} |
@@ -1,2 +0,2 @@ | ||
| import { i as SqlStorage } from "./sql-storage-Dga0jwP2.mjs"; | ||
| import { s as SqlStorage } from "./sql-storage-Dt5ipcRl.mjs"; | ||
| import { a as IndexTypeRegistry } from "./index-types-Czsyu7Iw.mjs"; | ||
@@ -3,0 +3,0 @@ import { Contract } from "@prisma-next/contract/types"; |
@@ -1,2 +0,2 @@ | ||
| import { r as ReferentialAction } from "./foreign-key-BATxB95l.mjs"; | ||
| import { r as ReferentialAction } from "./foreign-key-DM1UTydh.mjs"; | ||
@@ -3,0 +3,0 @@ //#region src/referential-action-sql.d.ts |
@@ -1,3 +0,3 @@ | ||
| import { r as StorageTable } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { i as SqlStorage } from "./sql-storage-Dga0jwP2.mjs"; | ||
| import { t as StorageTable } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { s as SqlStorage } from "./sql-storage-Dt5ipcRl.mjs"; | ||
@@ -4,0 +4,0 @@ //#region src/resolve-storage-table.d.ts |
+13
-5
@@ -1,5 +0,13 @@ | ||
| import { a as ForeignKeyReferenceInput, i as ForeignKeyReference, n as ForeignKeyInput, o as SqlNode, r as ReferentialAction, t as ForeignKey } from "./foreign-key-BATxB95l.mjs"; | ||
| import { a as UniqueConstraint, c as StorageColumnInput, d as PrimaryKey, f as PrimaryKeyInput, i as StorageTableInput, l as Index, m as CheckConstraintInput, n as StorageValueSetInput, o as UniqueConstraintInput, p as CheckConstraint, r as StorageTable, s as StorageColumn, t as StorageValueSet, u as IndexInput } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { a as SqlStorageInput, c as StorageTypeInstance, d as toStorageTypeInstance, i as SqlStorage, l as StorageTypeInstanceInput, n as SqlNamespaceEntries, o as SqlStorageTypeEntry, r as SqlNamespaceTablesInput, s as CODEC_INSTANCE_KIND, t as SqlNamespace, u as isStorageTypeInstance } from "./sql-storage-Dga0jwP2.mjs"; | ||
| import { C as TypeMaps, D as buildSqlNamespace, E as SqlUnboundNamespace, O as buildSqlNamespaceMap, S as SqlQueryOperationTypes, T as applyFkDefaults, _ as QueryOperationTypesOf, a as ExtractCodecTypes, b as SqlModelFieldStorage, c as ExtractQueryOperationTypes, d as FieldOutputTypesOf, f as ForeignKeyOptions, g as QueryOperationTypesBase, h as QueryOperationTypeEntry, i as DEFAULT_FK_INDEX, l as ExtractTypeMapsFromContract, m as QueryOperationSelfSpec, n as ContractWithTypeMaps, o as ExtractFieldInputTypes, p as QueryOperationReturn, r as DEFAULT_FK_CONSTRAINT, s as ExtractFieldOutputTypes, t as CodecTypesOf, u as FieldInputTypesOf, v as ResolveCodecTypes, w as TypeMapsPhantomKey, x as SqlModelStorage, y as SqlControlDriverInstance } from "./types-B1N8w0I2.mjs"; | ||
| export { CODEC_INSTANCE_KIND, CheckConstraint, type CheckConstraintInput, type CodecTypesOf, type ContractWithTypeMaps, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, type ExtractCodecTypes, type ExtractFieldInputTypes, type ExtractFieldOutputTypes, type ExtractQueryOperationTypes, type ExtractTypeMapsFromContract, type FieldInputTypesOf, type FieldOutputTypesOf, ForeignKey, type ForeignKeyInput, type ForeignKeyOptions, ForeignKeyReference, type ForeignKeyReferenceInput, Index, type IndexInput, PrimaryKey, type PrimaryKeyInput, type QueryOperationReturn, type QueryOperationSelfSpec, type QueryOperationTypeEntry, type QueryOperationTypesBase, type QueryOperationTypesOf, type ReferentialAction, type ResolveCodecTypes, type SqlControlDriverInstance, type SqlModelFieldStorage, type SqlModelStorage, type SqlNamespace, type SqlNamespaceEntries, type SqlNamespaceTablesInput, SqlNode, type SqlQueryOperationTypes, SqlStorage, type SqlStorageInput, type SqlStorageTypeEntry, SqlUnboundNamespace, StorageColumn, type StorageColumnInput, StorageTable, type StorageTableInput, type StorageTypeInstance, type StorageTypeInstanceInput, StorageValueSet, type StorageValueSetInput, type TypeMaps, type TypeMapsPhantomKey, UniqueConstraint, type UniqueConstraintInput, applyFkDefaults, buildSqlNamespace, buildSqlNamespaceMap, isStorageTypeInstance, toStorageTypeInstance }; | ||
| import { t as SqlNode } from "./sql-node-V214WXQD.mjs"; | ||
| import { a as StorageColumn, c as IndexInput, d as CheckConstraint, f as CheckConstraintInput, i as UniqueConstraintInput, l as PrimaryKey, n as StorageTableInput, o as StorageColumnInput, r as UniqueConstraint, s as Index, t as StorageTable, u as PrimaryKeyInput } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { a as ForeignKeyReferenceInput, i as ForeignKeyReference, n as ForeignKeyInput, r as ReferentialAction, t as ForeignKey } from "./foreign-key-DM1UTydh.mjs"; | ||
| import { a as SqlNamespaceFactory, c as SqlStorageInput, d as isSqlAuthoringContributions, f as CODEC_INSTANCE_KIND, g as toStorageTypeInstance, h as isStorageTypeInstance, i as SqlNamespaceEntries, l as SqlStorageTypeEntry, m as StorageTypeInstanceInput, n as SqlNamespace, o as SqlNamespaceInput, p as StorageTypeInstance, r as SqlNamespaceBase, s as SqlStorage, t as SqlAuthoringContributions, u as isMaterializedSqlNamespace } from "./sql-storage-Dt5ipcRl.mjs"; | ||
| import { n as StorageValueSetInput, r as isStorageValueSet, t as StorageValueSet } from "./storage-value-set-D-jww77l.mjs"; | ||
| import { A as TypeMapsPhantomKey, C as SqlControlDriverInstance, D as StorageColumnInputTypesOf, E as SqlQueryOperationTypes, O as StorageColumnTypesOf, S as ResolveCodecTypes, T as SqlModelStorage, _ as QueryOperationReturn, a as ExtractCodecTypes, b as QueryOperationTypesBase, c as ExtractQueryOperationTypes, d as ExtractTypeMapsFromContract, f as FieldInputTypesOf, g as NamespacedStorageColumnTypeMap, h as NamespacedFieldTypeMap, i as DEFAULT_FK_INDEX, j as applyFkDefaults, k as TypeMaps, l as ExtractStorageColumnInputTypes, m as ForeignKeyOptions, n as ContractWithTypeMaps, o as ExtractFieldInputTypes, p as FieldOutputTypesOf, r as DEFAULT_FK_CONSTRAINT, s as ExtractFieldOutputTypes, t as CodecTypesOf, u as ExtractStorageColumnTypes, v as QueryOperationSelfSpec, w as SqlModelFieldStorage, x as QueryOperationTypesOf, y as QueryOperationTypeEntry } from "./types-zBvpNCmg.mjs"; | ||
| //#region src/column-type-resolution.d.ts | ||
| type StorageColumnMapAt<SCT, NsId extends string, TableName extends string> = string extends keyof SCT ? never : NsId extends keyof SCT ? string extends keyof SCT[NsId] ? never : TableName extends keyof SCT[NsId] ? SCT[NsId][TableName] : never : never; | ||
| type StorageColumnTypeAcrossNamespaces<SCT, TableName extends string, ColumnName extends string> = { [Ns in keyof SCT]: TableName extends keyof SCT[Ns] ? ColumnName extends keyof SCT[Ns][TableName] ? SCT[Ns][TableName][ColumnName] : never : never }[keyof SCT]; | ||
| //#endregion | ||
| export { CODEC_INSTANCE_KIND, CheckConstraint, type CheckConstraintInput, type CodecTypesOf, type ContractWithTypeMaps, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, type ExtractCodecTypes, type ExtractFieldInputTypes, type ExtractFieldOutputTypes, type ExtractQueryOperationTypes, type ExtractStorageColumnInputTypes, type ExtractStorageColumnTypes, type ExtractTypeMapsFromContract, type FieldInputTypesOf, type FieldOutputTypesOf, ForeignKey, type ForeignKeyInput, type ForeignKeyOptions, ForeignKeyReference, type ForeignKeyReferenceInput, Index, type IndexInput, type NamespacedFieldTypeMap, type NamespacedStorageColumnTypeMap, PrimaryKey, type PrimaryKeyInput, type QueryOperationReturn, type QueryOperationSelfSpec, type QueryOperationTypeEntry, type QueryOperationTypesBase, type QueryOperationTypesOf, type ReferentialAction, type ResolveCodecTypes, type SqlAuthoringContributions, type SqlControlDriverInstance, type SqlModelFieldStorage, type SqlModelStorage, type SqlNamespace, SqlNamespaceBase, type SqlNamespaceEntries, type SqlNamespaceFactory, type SqlNamespaceInput, SqlNode, type SqlQueryOperationTypes, SqlStorage, type SqlStorageInput, type SqlStorageTypeEntry, StorageColumn, type StorageColumnInput, type StorageColumnInputTypesOf, type StorageColumnMapAt, type StorageColumnTypeAcrossNamespaces, type StorageColumnTypesOf, StorageTable, type StorageTableInput, type StorageTypeInstance, type StorageTypeInstanceInput, StorageValueSet, type StorageValueSetInput, type TypeMaps, type TypeMapsPhantomKey, UniqueConstraint, type UniqueConstraintInput, applyFkDefaults, isMaterializedSqlNamespace, isSqlAuthoringContributions, isStorageTypeInstance, isStorageValueSet, toStorageTypeInstance }; | ||
| //# sourceMappingURL=types.d.mts.map |
+106
-3
@@ -1,3 +0,106 @@ | ||
| import { a as StorageTable, c as Index, d as ForeignKeyReference, f as CheckConstraint, i as StorageValueSet, l as PrimaryKey, o as UniqueConstraint, p as SqlNode, s as StorageColumn, u as ForeignKey } from "./entity-kinds-Cl36zL5j.mjs"; | ||
| import { a as CODEC_INSTANCE_KIND, c as buildSqlNamespace, i as SqlStorage, l as buildSqlNamespaceMap, n as DEFAULT_FK_INDEX, o as isStorageTypeInstance, r as applyFkDefaults, s as toStorageTypeInstance, t as DEFAULT_FK_CONSTRAINT, u as SqlUnboundNamespace } from "./types-B-eiQXff.mjs"; | ||
| export { CODEC_INSTANCE_KIND, CheckConstraint, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, ForeignKey, ForeignKeyReference, Index, PrimaryKey, SqlNode, SqlStorage, SqlUnboundNamespace, StorageColumn, StorageTable, StorageValueSet, UniqueConstraint, applyFkDefaults, buildSqlNamespace, buildSqlNamespaceMap, isStorageTypeInstance, toStorageTypeInstance }; | ||
| 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-y6R6pxyI.mjs"; | ||
| import { n as isStorageValueSet, t as StorageValueSet } from "./storage-value-set-Tx3CFoS_.mjs"; | ||
| import { n as DEFAULT_FK_INDEX, r as applyFkDefaults, t as DEFAULT_FK_CONSTRAINT } from "./types-Hkxybhdj.mjs"; | ||
| import { NamespaceBase, freezeNode, isPlainRecord } from "@prisma-next/framework-components/ir"; | ||
| //#region src/ir/storage-type-instance.ts | ||
| /** | ||
| * Sentinel kind for the legacy codec-triple shape persisted under | ||
| * `SqlStorage.types`. Plain JSON-clean object literals carry this | ||
| * discriminator so the polymorphic slot dispatch can route them down | ||
| * the codec path while target-specific IR class instances (e.g. the | ||
| * Postgres enum class) keep their own narrower `kind` literal. | ||
| */ | ||
| const CODEC_INSTANCE_KIND = "codec-instance"; | ||
| /** | ||
| * Stamp the codec-instance `kind` discriminator on a caller-supplied | ||
| * codec triple. Idempotent: input that already carries the discriminator | ||
| * passes through unchanged. Missing `typeParams` is normalised to `{}`. | ||
| */ | ||
| function toStorageTypeInstance(input) { | ||
| return { | ||
| kind: CODEC_INSTANCE_KIND, | ||
| codecId: input.codecId, | ||
| nativeType: input.nativeType, | ||
| typeParams: input.typeParams ?? {} | ||
| }; | ||
| } | ||
| /** | ||
| * Type-guard for codec-typed entries on the polymorphic | ||
| * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from | ||
| * any class-instance kinds a target pack contributes. | ||
| */ | ||
| function isStorageTypeInstance(value) { | ||
| if (typeof value !== "object" || value === null) return false; | ||
| return value.kind === CODEC_INSTANCE_KIND; | ||
| } | ||
| //#endregion | ||
| //#region src/ir/sql-storage.ts | ||
| /** | ||
| * Narrows framework `AuthoringContributions` to the SQL-family shape by testing | ||
| * for the SQL-specific `createNamespace` capability. | ||
| */ | ||
| function isSqlAuthoringContributions(authoring) { | ||
| if (authoring === void 0 || !Object.hasOwn(authoring, "createNamespace")) return false; | ||
| return typeof Reflect.get(authoring, "createNamespace") === "function"; | ||
| } | ||
| /** | ||
| * Abstract SQL family namespace base class. Target concretions (`PostgresSchema`, | ||
| * `SqliteDatabase`, …) extend this — it is never instantiated directly. | ||
| * `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]` | ||
| * addresses any entity. | ||
| */ | ||
| var SqlNamespaceBase = class extends NamespaceBase {}; | ||
| /** | ||
| * Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks | ||
| * `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it | ||
| * survives duplicate-module boundaries (e.g. dist e2e where the target and | ||
| * the family carry separate copies of `@prisma-next/framework-components`). | ||
| * | ||
| * Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`, | ||
| * `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput` | ||
| * objects (`{ id, entries }`) do not. | ||
| */ | ||
| function isMaterializedSqlNamespace(x) { | ||
| if (typeof x !== "object" || x === null || !("qualifyTable" in x)) return false; | ||
| return typeof x.qualifyTable === "function"; | ||
| } | ||
| var SqlStorage = class extends SqlNode { | ||
| storageHash; | ||
| namespaces; | ||
| constructor(input) { | ||
| super(); | ||
| this.storageHash = input.storageHash; | ||
| this.namespaces = Object.freeze(input.namespaces); | ||
| if (input.types !== void 0) this.types = Object.freeze(Object.fromEntries(Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]))); | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| /** | ||
| * Strict polymorphic-slot dispatch for `SqlStorage.types` entries. | ||
| * Every entry must carry a `kind: 'codec-instance'` discriminator or | ||
| * be an already-constructed `StorageTypeInstance`. Untagged or | ||
| * unrecognised inputs throw a diagnostic naming the entry and its | ||
| * `kind`, so format drift surfaces loudly at the deserializer | ||
| * boundary instead of slipping past the seam and corrupting | ||
| * downstream IR walks. | ||
| * | ||
| * Codec-triple authors that have an untagged shape on hand can call | ||
| * `toStorageTypeInstance(...)` (which stamps the `'codec-instance'` | ||
| * discriminator) before constructing `SqlStorage`. On-disk reads | ||
| * cross `familyInstance.deserializeContract` first; the structural | ||
| * arktype schema rejects untagged entries earlier, so this throw | ||
| * only fires for in-memory authoring bugs. | ||
| */ | ||
| function normaliseTypeEntry(name, entry) { | ||
| if (isStorageTypeInstance(entry)) { | ||
| if ("typeParams" in entry) return entry; | ||
| return toStorageTypeInstance(entry); | ||
| } | ||
| const rawKind = isPlainRecord(entry) ? entry["kind"] : void 0; | ||
| const kindDescription = rawKind === void 0 ? "missing `kind` discriminator" : `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`; | ||
| 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.`); | ||
| } | ||
| //#endregion | ||
| 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 }; | ||
| //# sourceMappingURL=types.mjs.map |
@@ -1,6 +0,6 @@ | ||
| import { n as ForeignKeyInput, r as ReferentialAction } from "./foreign-key-BATxB95l.mjs"; | ||
| import { f as PrimaryKeyInput, o as UniqueConstraintInput } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { i as SqlStorage } from "./sql-storage-Dga0jwP2.mjs"; | ||
| import { i as UniqueConstraintInput, u as PrimaryKeyInput } from "./storage-table-Bj1ZN1P7.mjs"; | ||
| import { n as ForeignKeyInput, r as ReferentialAction } from "./foreign-key-DM1UTydh.mjs"; | ||
| import { s as SqlStorage } from "./sql-storage-Dt5ipcRl.mjs"; | ||
| import { AnyEntityKindDescriptor } from "@prisma-next/framework-components/ir"; | ||
| import { Type } from "arktype"; | ||
| import { AnyEntityKindDescriptor } from "@prisma-next/framework-components/ir"; | ||
| import { Contract } from "@prisma-next/contract/types"; | ||
@@ -65,2 +65,3 @@ | ||
| nullable: boolean; | ||
| many?: boolean; | ||
| typeParams?: Record<string, unknown>; | ||
@@ -137,9 +138,11 @@ typeRef?: string; | ||
| /** | ||
| * Validates the structural shape of SqlStorage using Arktype. | ||
| * Validates the structural shape of SqlStorage using Arktype. Pure | ||
| * structural check: namespace IR is never materialized here (that needs | ||
| * a target concretion via the serializer hydration path), so this throws | ||
| * on invalid input and constructs nothing. | ||
| * | ||
| * @param value - The storage value to validate | ||
| * @returns The validated storage if structure is valid | ||
| * @throws Error if the storage structure is invalid | ||
| */ | ||
| declare function validateStorage(value: unknown): SqlStorage; | ||
| declare function validateStorage(value: unknown): void; | ||
| declare function validateModel(value: unknown): unknown; | ||
@@ -146,0 +149,0 @@ /** |
@@ -1,1 +0,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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Ac;AAAA,iBAQ9B,aAAA,CAAc,KAAc;;;;ADnT5C;;;;;;;;;;iBCiXgB,wBAAA,CAAyB,OAAmB,EAAV,UAAU;;AD1W5D;;;;;iBC+gBgB,8BAAA,CAA+B,QAAA,EAAU,QAAQ,CAAC,UAAA;;;;;;ADvgBlE;iBCmkBgB,6BAAA,CAA8B,QAAA,EAAU,QAAQ,CAAC,UAAA;AAAA,UAwGhD,+BAAA;EDtqB0B;;;;;;;AAE3C;EAF2C,SC+qBhC,cAAA,GAAiB,IAAI;AAAA;;AD7qBI;AAIpC;;;;AAA6B;AAU7B;iBC0qBgB,wBAAA,WAAmC,QAAA,CAAS,UAAA,GAC1D,KAAA,WACA,OAAA,GAAU,+BAAA,GACT,CAAA"} |
+110
-18
@@ -1,9 +0,8 @@ | ||
| import { C as StorageTableSchema, S as ReferentialActionSchema, _ as ColumnDefaultSchema, b as ForeignKeySourceSchema, g as ColumnDefaultLiteralSchema, h as ColumnDefaultFunctionSchema, m as CheckConstraintSchema, t as composeSqlEntityKinds, v as ForeignKeyReferenceSchema, w as StorageValueSetSchema, x as IndexSchema, y as ForeignKeySchema } from "./entity-kinds-Cl36zL5j.mjs"; | ||
| import { i as SqlStorage, l as buildSqlNamespaceMap, u as SqlUnboundNamespace } from "./types-B-eiQXff.mjs"; | ||
| 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-BEPZdFBN.mjs"; | ||
| import { isPlainRecord } from "@prisma-next/framework-components/ir"; | ||
| import { type } from "arktype"; | ||
| import { UNBOUND_NAMESPACE_ID, isPlainRecord } from "@prisma-next/framework-components/ir"; | ||
| import { CrossReferenceSchema } from "@prisma-next/contract/types"; | ||
| import { blindCast } from "@prisma-next/utils/casts"; | ||
| import { ContractValidationError } from "@prisma-next/contract/contract-validation-error"; | ||
| import { validateContractDomain } from "@prisma-next/contract/validate-domain"; | ||
| import { blindCast } from "@prisma-next/utils/casts"; | ||
| import { ifDefined } from "@prisma-next/utils/defined"; | ||
@@ -239,6 +238,8 @@ //#region src/validators.ts | ||
| /** | ||
| * Validates the structural shape of SqlStorage using Arktype. | ||
| * Validates the structural shape of SqlStorage using Arktype. Pure | ||
| * structural check: namespace IR is never materialized here (that needs | ||
| * a target concretion via the serializer hydration path), so this throws | ||
| * on invalid input and constructs nothing. | ||
| * | ||
| * @param value - The storage value to validate | ||
| * @returns The validated storage if structure is valid | ||
| * @throws Error if the storage structure is invalid | ||
@@ -252,13 +253,2 @@ */ | ||
| } | ||
| const validated = blindCast(result); | ||
| const namespaces = buildSqlNamespaceMap(validated.namespaces ?? {}); | ||
| const unbound = namespaces[UNBOUND_NAMESPACE_ID] ?? SqlUnboundNamespace.instance; | ||
| return new SqlStorage({ | ||
| storageHash: validated.storageHash, | ||
| ...ifDefined("types", validated.types), | ||
| namespaces: { | ||
| ...namespaces, | ||
| [UNBOUND_NAMESPACE_ID]: unbound | ||
| } | ||
| }); | ||
| } | ||
@@ -405,3 +395,3 @@ function validateModel(value) { | ||
| 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"); | ||
| const JSON_NATIVE_TYPES = new Set(["json", "jsonb"]); | ||
| const JSON_NATIVE_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]); | ||
| for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) { | ||
@@ -469,4 +459,106 @@ if (domainField.type?.kind !== "valueObject") continue; | ||
| validateModelStorageReferences(validated); | ||
| validateRelationThroughConsistency(validated); | ||
| return validated; | ||
| } | ||
| /** Storage column lookup for through-consistency validation. */ | ||
| function lookupStorageColumn(contract, namespaceId, tableName, columnName) { | ||
| const rawTable = contract.storage.namespaces[namespaceId]?.entries.table?.[tableName]; | ||
| if (rawTable === void 0) return; | ||
| return blindCast(rawTable).columns[columnName]; | ||
| } | ||
| /** | ||
| * Two storage columns share a type when their `nativeType` and `typeParams` | ||
| * match. The contract is canonicalized, so `typeParams` key order is stable and | ||
| * a JSON comparison is exact. `codecId` and `nullable` are intentionally not | ||
| * compared: they do not change the database-level type that governs a join. | ||
| */ | ||
| function sameStorageType(a, b) { | ||
| return a.nativeType === b.nativeType && JSON.stringify(a.typeParams ?? null) === JSON.stringify(b.typeParams ?? null); | ||
| } | ||
| function describeColumnType(column) { | ||
| return column.typeParams === void 0 ? column.nativeType : `${column.nativeType} ${JSON.stringify(column.typeParams)}`; | ||
| } | ||
| /** | ||
| * Validates one side of an N:M join: the junction columns and the model | ||
| * columns they pair against positionally must be equal in number, exist in | ||
| * their tables, and share the same storage type (`nativeType` + `typeParams`). | ||
| * The junction's storage foreign keys already guarantee this for user-declared | ||
| * FK constraints, but `through` is a logical descriptor never tied to them by | ||
| * the rest of validation — and the TS builder accepts explicit join columns | ||
| * without requiring a junction FK at all — so this checks the columns directly | ||
| * against storage, one path regardless of how the junction was authored. | ||
| * | ||
| * Joined columns must be the *same* storage type, not merely compatible: | ||
| * relying on implicit conversion (e.g. `text`↔`character`) is unsafe on writes | ||
| * — `character(n)` space-padding makes such coercions non-associative — and no | ||
| * ADR sanctions heterogeneous junction columns. Equality is the conservative | ||
| * default; it can be relaxed deliberately if a real use case ever appears. | ||
| */ | ||
| function validateThroughJoinSide(input) { | ||
| const fail = (detail) => new ContractValidationError(`Many-to-many relation "${input.qualifiedName}" ${detail}`, "storage"); | ||
| 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.`); | ||
| for (const [index, junctionColumnName] of input.junctionColumns.entries()) { | ||
| const modelColumnRef = input.modelColumns[index]; | ||
| if (modelColumnRef === void 0) continue; | ||
| const junctionColumn = lookupStorageColumn(input.contract, input.junctionNamespaceId, input.junctionTable, junctionColumnName); | ||
| if (junctionColumn === void 0) throw fail(`${input.junctionColumnsLabel} references column "${junctionColumnName}" absent from junction table "${input.junctionNamespaceId}.${input.junctionTable}".`); | ||
| const model = input.model; | ||
| if (model === void 0) continue; | ||
| let modelColumnName = modelColumnRef; | ||
| if (model.fieldToColumn !== void 0) { | ||
| const mapped = model.fieldToColumn[modelColumnRef]; | ||
| if (mapped === void 0) throw fail(`${input.modelColumnsLabel} references field "${modelColumnRef}" absent from model on table "${model.namespaceId}.${model.table}".`); | ||
| modelColumnName = mapped.column; | ||
| } | ||
| const modelColumn = lookupStorageColumn(input.contract, model.namespaceId, model.table, modelColumnName); | ||
| if (modelColumn === void 0) throw fail(`${input.modelColumnsLabel} references column "${modelColumnName}" absent from table "${model.namespaceId}.${model.table}".`); | ||
| 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.`); | ||
| } | ||
| } | ||
| /** | ||
| * Validates that every N:M relation's `through` descriptor is consistent with | ||
| * the storage columns it joins: both join sides match in column count, | ||
| * reference columns that exist in their tables, and pair columns of the same | ||
| * storage type. Without this, a `through` that disagrees with storage surfaces | ||
| * as a silently wrong JOIN at query time rather than a validation error here. | ||
| */ | ||
| function validateRelationThroughConsistency(contract) { | ||
| 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)) { | ||
| if (relation.cardinality !== "N:M") continue; | ||
| const qualifiedName = `${namespaceId}.${modelName}.${relationName}`; | ||
| const { on, through } = relation; | ||
| const modelStorage = blindCast(model.storage); | ||
| validateThroughJoinSide({ | ||
| contract, | ||
| qualifiedName, | ||
| modelColumns: on.localFields, | ||
| modelColumnsLabel: "on.localFields", | ||
| model: { | ||
| namespaceId, | ||
| table: modelStorage.table, | ||
| fieldToColumn: modelStorage.fields | ||
| }, | ||
| junctionColumns: through.parentColumns, | ||
| junctionColumnsLabel: "through.parentColumns", | ||
| junctionNamespaceId: through.namespaceId, | ||
| junctionTable: through.table | ||
| }); | ||
| const targetModel = relation.to.space === void 0 ? contract.domain.namespaces[relation.to.namespace]?.models[relation.to.model] : void 0; | ||
| const targetModelSide = targetModel === void 0 ? void 0 : { | ||
| namespaceId: relation.to.namespace, | ||
| table: blindCast(targetModel.storage).table | ||
| }; | ||
| validateThroughJoinSide({ | ||
| contract, | ||
| qualifiedName, | ||
| modelColumns: through.targetColumns, | ||
| modelColumnsLabel: "through.targetColumns", | ||
| ...ifDefined("model", targetModelSide), | ||
| junctionColumns: through.childColumns, | ||
| junctionColumnsLabel: "through.childColumns", | ||
| junctionNamespaceId: through.namespaceId, | ||
| junctionTable: through.table | ||
| }); | ||
| } | ||
| } | ||
| //#endregion | ||
@@ -473,0 +565,0 @@ export { CheckConstraintSchema, ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ContractEnumSchema, ForeignKeyReferenceSchema, ForeignKeySchema, ForeignKeySourceSchema, IndexSchema, ReferentialActionSchema, StorageTableSchema, StorageValueSetSchema, createNamespaceEntrySchema, createSqlContractSchema, createSqlStorageSchema, validateModel, validateModelStorageReferences, validateSqlContractFully, validateSqlStorageConsistency, validateStorage, validateStorageSemantics }; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"validators.mjs","names":["f","referencedTable"],"sources":["../src/validators.ts"],"sourcesContent":["import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';\nimport {\n type Contract,\n type ContractField,\n type ContractModel,\n CrossReferenceSchema,\n} from '@prisma-next/contract/types';\nimport { validateContractDomain } from '@prisma-next/contract/validate-domain';\nimport {\n type AnyEntityKindDescriptor,\n isPlainRecord,\n type Namespace,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type Type, type } from 'arktype';\nimport { composeSqlEntityKinds } from './entity-kinds';\nimport { buildSqlNamespaceMap } from './ir/build-sql-namespace';\n\nexport {\n CheckConstraintSchema,\n ColumnDefaultFunctionSchema,\n ColumnDefaultLiteralSchema,\n ColumnDefaultSchema,\n ForeignKeyReferenceSchema,\n ForeignKeySchema,\n ForeignKeySourceSchema,\n IndexSchema,\n ReferentialActionSchema,\n StorageTableSchema,\n StorageValueSetSchema,\n} from './ir/storage-entry-schemas';\n\nimport { SqlUnboundNamespace } from './ir/sql-unbound-namespace';\nimport {\n type SqlModelStorage,\n SqlStorage,\n type SqlStorageInput,\n type StorageTable,\n type StorageTypeInstanceInput,\n} from './types';\n\nconst generatorKindSchema = type(\"'generator'\");\nconst ControlPolicySchema = type(\"'managed' | 'tolerated' | 'external' | 'observed'\");\nconst generatorIdSchema = type('string').narrow((value, ctx) => {\n return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value) ? true : ctx.mustBe('a flat generator id');\n});\n\nconst ExecutionMutationDefaultValueSchema = type({\n '+': 'reject',\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n '+': 'reject',\n ref: {\n '+': 'reject',\n namespace: 'string',\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n '+': 'reject',\n executionHash: 'string',\n mutations: {\n '+': 'reject',\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst DomainEnumRefSchema = type({\n plane: \"'domain'\",\n namespaceId: 'string',\n entityKind: \"'enum'\",\n entityName: 'string',\n 'spaceId?': 'string',\n});\n\n/**\n * Codec-triple entry persisted under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'codec-instance'` discriminator so the\n * polymorphic slot dispatch can distinguish codec triples from\n * class-instance kinds (e.g. `'postgres-enum'`) sharing the slot.\n */\nconst StorageTypeInstanceSchema = type\n .declare<StorageTypeInstanceInput & { kind: 'codec-instance' }>()\n .type({\n kind: \"'codec-instance'\",\n codecId: 'string',\n nativeType: 'string',\n 'typeParams?': 'Record<string, unknown>',\n });\n\n/** Document-scoped `storage.types`: codec triples only. */\nconst DocumentScopedStorageTypeSchema = StorageTypeInstanceSchema;\n\n/**\n * Domain enum entry under `domain.namespaces[id].enum[name]`.\n * Carries the codec id and an ordered `members` array of `{name, value}` pairs.\n */\nexport const ContractEnumSchema = type({\n '+': 'reject',\n codecId: 'string',\n members: type({\n name: 'string',\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n })\n .array()\n .readonly(),\n});\n\n/**\n * Derives a schema map from a descriptor map: maps each kind's key to its\n * `schema` field. Used by validation functions to validate entries.\n */\nfunction schemaViewOf(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): ReadonlyMap<string, Type<unknown>> {\n return new Map([...kinds].map(([k, d]) => [k, d.schema]));\n}\n\nconst DEFAULT_SQL_KINDS = composeSqlEntityKinds();\n\n/**\n * Builds the per-namespace entry schema for `storage.namespaces[id]`.\n *\n * Validation is descriptor-driven: the `kinds` map carries both the schema\n * (used here for structural validation) and the construct function (used at\n * hydration time). An unregistered key fails validation naming the kind and\n * the namespace id, so validation fails closed.\n */\nexport function createNamespaceEntrySchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const schemas = schemaViewOf(kinds);\n const knownKinds = new Set(kinds.keys());\n return type({\n '+': 'reject',\n id: 'string',\n 'kind?': 'string',\n entries: 'object',\n }).narrow((ns, ctx) => {\n if (!isPlainRecord(ns.entries)) {\n return ctx.mustBe('an entries object');\n }\n for (const [key, innerMap] of Object.entries(ns.entries)) {\n if (!knownKinds.has(key)) {\n return ctx.reject({\n expected: `entries key \"${key}\" in namespace \"${ns.id}\" is not a registered entity kind`,\n });\n }\n if (!isPlainRecord(innerMap)) {\n return ctx.reject({\n expected: `entries[\"${key}\"] in namespace \"${ns.id}\" must be an object`,\n });\n }\n const entrySchema = blindCast<\n Type<unknown>,\n 'knownKinds.has(key) guarantees schemas.get(key) is defined'\n >(schemas.get(key));\n for (const [, value] of Object.entries(innerMap)) {\n const parsed = entrySchema(value);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n }\n }\n return true;\n }) as Type<unknown>;\n}\n\n/**\n * Builds the storage schema. Pack contributions reach the per-namespace\n * entry shape through {@link createNamespaceEntrySchema}; the\n * document-scoped `storage.types` field (codec triples only) and the\n * storage hash stay family-shared.\n */\nexport function createSqlStorageSchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const namespaceEntry = createNamespaceEntrySchema(kinds);\n return type({\n '+': 'reject',\n storageHash: 'string',\n 'types?': type({ '[string]': DocumentScopedStorageTypeSchema }),\n // `__unbound__` is NOT required here: cross-namespace contracts can\n // declare only named namespaces (see cross-namespace FK fixtures). The\n // `__unbound__` brand on `SqlStorageInput['namespaces']` is kept sound at\n // construction time by injecting the unbound singleton when absent\n // (see `validateStorage` / `hydrateSqlStorage`), not by structural require.\n 'namespaces?': type({ '[string]': namespaceEntry }),\n }) as Type<unknown>;\n}\n\nconst StorageSchema = createSqlStorageSchema(DEFAULT_SQL_KINDS);\n\ntype NamespacedStorageWalk = {\n readonly namespaces: Readonly<\n Record<\n string,\n Namespace & { readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>> }\n >\n >;\n};\n\nfunction eachStorageTable(storage: NamespacedStorageWalk) {\n return Object.entries(storage.namespaces).flatMap(([namespaceId, ns]) =>\n Object.entries(ns.entries['table'] ?? {}).map(([tableName, table]) => ({\n namespaceId,\n tableName,\n table,\n })),\n );\n}\n\nfunction findDuplicateValue(values: readonly string[]): string | undefined {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n }\n return undefined;\n}\n\nfunction isContractFieldType(value: unknown): boolean {\n if (!isPlainRecord(value)) return false;\n const kind = value['kind'];\n if (kind === 'scalar') {\n if (typeof value['codecId'] !== 'string') return false;\n const typeParams = value['typeParams'];\n if (typeParams !== undefined && !isPlainRecord(typeParams)) return false;\n return true;\n }\n if (kind === 'valueObject') {\n return typeof value['name'] === 'string';\n }\n if (kind === 'union') {\n const members = value['members'];\n if (!Array.isArray(members)) return false;\n return members.every((m) => isContractFieldType(m));\n }\n return false;\n}\n\nconst ContractFieldTypeSchema = type('unknown').narrow((value, ctx) =>\n isContractFieldType(value) ? true : ctx.mustBe('scalar, valueObject, or union field type'),\n);\n\nconst ModelFieldSchema = type({\n '+': 'reject',\n nullable: 'boolean',\n type: ContractFieldTypeSchema,\n 'many?': 'true',\n 'dict?': 'true',\n 'valueSet?': DomainEnumRefSchema,\n});\n\nconst ModelStorageFieldSchema = type({\n column: 'string',\n 'codecId?': 'string',\n 'nullable?': 'boolean',\n});\n\nconst ModelStorageSchema = type({\n table: 'string',\n namespaceId: 'string',\n fields: type({ '[string]': ModelStorageFieldSchema }),\n});\n\nconst ContractRelationThroughSchema = type({\n '+': 'reject',\n table: 'string',\n namespaceId: 'string',\n parentColumns: type.string.array().readonly(),\n childColumns: type.string.array().readonly(),\n targetColumns: type.string.array().readonly(),\n});\n\nconst ContractRelationOnSchema = type({\n '+': 'reject',\n localFields: type.string.array().readonly(),\n targetFields: type.string.array().readonly(),\n});\n\nconst ContractManyToManyRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'N:M'\",\n on: ContractRelationOnSchema,\n through: ContractRelationThroughSchema,\n});\n\nconst ContractNonJunctionRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'1:1' | '1:N' | 'N:1'\",\n on: ContractRelationOnSchema,\n});\n\nconst ContractReferenceRelationSchema = ContractManyToManyRelationSchema.or(\n ContractNonJunctionRelationSchema,\n);\n\nconst ContractEmbedRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'1:1' | '1:N'\",\n});\n\nconst ContractRelationSchema = ContractReferenceRelationSchema.or(ContractEmbedRelationSchema);\n\nconst ModelSchema = type({\n storage: ModelStorageSchema,\n 'fields?': type({ '[string]': ModelFieldSchema }),\n 'relations?': type({ '[string]': ContractRelationSchema }),\n 'discriminator?': 'unknown',\n 'variants?': 'unknown',\n 'base?': CrossReferenceSchema,\n 'owner?': 'string',\n});\n\nconst ContractMetaSchema = type({\n '[string]': 'unknown',\n});\n\n/**\n * Builds the full SQL contract schema. The storage subtree threads\n * pack contributions through {@link createSqlStorageSchema}; the rest\n * of the contract envelope is family-shared.\n */\nexport function createSqlContractSchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const storage = createSqlStorageSchema(kinds);\n return type({\n '+': 'reject',\n target: 'string',\n targetFamily: \"'sql'\",\n 'coreHash?': 'string',\n profileHash: 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': ContractMetaSchema,\n 'defaultControlPolicy?': ControlPolicySchema,\n 'roots?': type({ '[string]': CrossReferenceSchema }),\n domain: type({\n namespaces: type({\n '[string]': type({\n models: type({ '[string]': ModelSchema }),\n 'valueObjects?': 'Record<string, unknown>',\n 'enum?': type({ '[string]': ContractEnumSchema }),\n }),\n }),\n }),\n storage,\n 'execution?': ExecutionSchema,\n }) as Type<unknown>;\n}\n\nconst SqlContractSchema = createSqlContractSchema(DEFAULT_SQL_KINDS);\n\n// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()\n// instead of type.declare<T>().type() because the ColumnDefault union's value field\n// includes bigint | Date (runtime-only types after decoding) which cannot be expressed\n// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges\n// the gap between the JSON-safe Arktype output and the runtime TypeScript type.\n\n/**\n * Validates the structural shape of SqlStorage using Arktype.\n *\n * @param value - The storage value to validate\n * @returns The validated storage if structure is valid\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): SqlStorage {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n // Arktype validates the JSON-safe envelope, but the `ColumnDefault`\n // union carries runtime-only `bigint | Date` that the validation DSL\n // can't express (see NOTE above), so bridge the validated shape to the\n // input type. Construction below re-materialises nested IR fields.\n const validated = blindCast<\n SqlStorageInput & { readonly namespaces?: SqlStorageInput['namespaces'] },\n 'arktype validated the JSON envelope but its output type is unknown (ColumnDefault carries runtime-only bigint|Date); bridge to the input shape'\n >(result);\n const namespaces = buildSqlNamespaceMap(validated.namespaces ?? {});\n // Compatibility shim: inject the empty unbound singleton when absent so that\n // production code paths which address __unbound__ for table metadata have a\n // slot to read or write into. The `SqlStorageInput['namespaces']` type no\n // longer requires __unbound__, so this is a runtime convenience, not a type\n // invariant.\n const unbound = namespaces[UNBOUND_NAMESPACE_ID] ?? SqlUnboundNamespace.instance;\n return new SqlStorage({\n storageHash: validated.storageHash,\n ...ifDefined('types', validated.types),\n namespaces: { ...namespaces, [UNBOUND_NAMESPACE_ID]: unbound },\n });\n}\n\nexport function validateModel(value: unknown): unknown {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Structural arktype validation of an SQL contract envelope. Internal\n * helper for {@link validateSqlContractFully} — exposed only inside\n * this module, since the family seam-of-record is the\n * `SqlContractSerializerBase.deserializeContract` SPI.\n */\nfunction validateSqlContractStructure<T extends Contract<SqlStorage>>(\n value: unknown,\n contractSchema: Type<unknown>,\n): T {\n if (typeof value !== 'object' || value === null) {\n throw new ContractValidationError(\n 'Contract structural validation failed: value must be an object',\n 'structural',\n );\n }\n\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n throw new ContractValidationError(\n `Unsupported target family: ${rawValue.targetFamily}`,\n 'structural',\n );\n }\n\n const contractResult = contractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new ContractValidationError(\n `Contract structural validation failed: ${messages}`,\n 'structural',\n );\n }\n\n // Arktype's inferred output type differs from T due to exactOptionalPropertyTypes\n // and branded hash types — the runtime value is structurally compatible after validation\n return contractResult as unknown as T;\n}\n\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - duplicate named primary key / unique / index / foreign key objects within a table\n * - duplicate unique, index, or foreign key declarations within a table\n * - duplicate columns within primary key / unique / index definitions\n * - nullable columns in primary key definitions\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const { namespaceId, tableName, table: rawTable } of eachStorageTable(storage)) {\n const table = rawTable as StorageTable;\n const namedObjects = new Map<string, string[]>();\n const registerNamedObject = (kind: string, name: string | undefined) => {\n if (!name) return;\n namedObjects.set(name, [...(namedObjects.get(name) ?? []), kind]);\n };\n\n registerNamedObject('primary key', table.primaryKey?.name);\n for (const unique of table.uniques) {\n registerNamedObject('unique constraint', unique.name);\n }\n for (const index of table.indexes) {\n registerNamedObject('index', index.name);\n }\n for (const fk of table.foreignKeys) {\n registerNamedObject('foreign key', fk.name);\n }\n for (const check of table.checks ?? []) {\n registerNamedObject('check constraint', check.name);\n }\n\n for (const [name, kinds] of namedObjects) {\n if (kinds.length > 1) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": named object \"${name}\" is declared multiple times (${kinds.join(', ')})`,\n );\n }\n }\n\n if (table.primaryKey) {\n const duplicateColumn = findDuplicateValue(table.primaryKey.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": primary key contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n for (const columnName of table.primaryKey.columns) {\n const column = table.columns[columnName];\n if (column?.nullable === true) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": primary key column \"${columnName}\" is nullable; primary key columns must be NOT NULL`,\n );\n }\n }\n }\n\n const seenUniqueDefinitions = new Set<string>();\n for (const unique of table.uniques) {\n const duplicateColumn = findDuplicateValue(unique.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": unique constraint contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({ columns: unique.columns });\n if (seenUniqueDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate unique constraint definition on columns [${unique.columns.join(', ')}]`,\n );\n continue;\n }\n seenUniqueDefinitions.add(signature);\n }\n\n const sortOptions = (o: Record<string, unknown> | undefined): Record<string, unknown> | null =>\n o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;\n\n const seenIndexDefinitions = new Set<string>();\n for (const index of table.indexes) {\n const duplicateColumn = findDuplicateValue(index.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": index contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({\n columns: index.columns,\n type: index.type ?? null,\n options: sortOptions(index.options),\n });\n if (seenIndexDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate index definition on columns [${index.columns.join(', ')}]`,\n );\n continue;\n }\n seenIndexDefinitions.add(signature);\n }\n\n const seenForeignKeyDefinitions = new Set<string>();\n for (const fk of table.foreignKeys) {\n const signature = JSON.stringify({\n source: fk.source,\n target: fk.target,\n onDelete: fk.onDelete ?? null,\n onUpdate: fk.onUpdate ?? null,\n constraint: fk.constraint,\n index: fk.index,\n });\n if (seenForeignKeyDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate foreign key definition on columns [${fk.source.columns.join(', ')}]`,\n );\n continue;\n }\n seenForeignKeyDefinitions.add(signature);\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.source.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n\n const seenCheckDefinitions = new Set<string>();\n for (const check of table.checks ?? []) {\n const signature = JSON.stringify({ column: check.column, valueSet: check.valueSet });\n if (seenCheckDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate check constraint definition on column \"${check.column}\"`,\n );\n continue;\n }\n seenCheckDefinitions.add(signature);\n }\n }\n\n return errors;\n}\n\n/**\n * SQL storage logical-consistency checks: every model.storage.table\n * resolves to a real table, every model.storage.fields[*].column\n * resolves to a real column, and value-object fields land on JSON-native\n * columns. Throws `ContractValidationError` on the first mismatch.\n */\nexport function validateModelStorageReferences(contract: Contract<SqlStorage>): void {\n for (const [namespaceId, namespace] of Object.entries(contract.domain.namespaces)) {\n const models = namespace.models as Record<string, ContractModel<SqlModelStorage>>;\n for (const [modelName, model] of Object.entries(models)) {\n const qualifiedName = `${namespaceId}:${modelName}`;\n const storageNamespaceId = model.storage.namespaceId;\n if (storageNamespaceId !== namespaceId) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" storage.namespaceId \"${storageNamespaceId}\" does not match domain namespace \"${namespaceId}\"`,\n 'storage',\n );\n }\n\n const storageTable = model.storage.table;\n const storageNs = contract.storage.namespaces[storageNamespaceId];\n const rawTable = storageNs?.entries.table?.[storageTable];\n if (rawTable === undefined) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" references non-existent table \"${storageNamespaceId}.${storageTable}\"`,\n 'storage',\n );\n }\n\n const table = rawTable as StorageTable;\n\n const columnNames = new Set(Object.keys(table.columns));\n for (const [fieldName, field] of Object.entries(model.storage.fields)) {\n if (!columnNames.has(field.column)) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${storageTable}\"`,\n 'storage',\n );\n }\n }\n\n const JSON_NATIVE_TYPES = new Set(['json', 'jsonb']);\n for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) {\n const f = domainField as ContractField;\n if (f.type?.kind !== 'valueObject') continue;\n const storageField = model.storage.fields[fieldName];\n if (!storageField) continue;\n const column = table.columns[storageField.column];\n if (!column) continue;\n if (!JSON_NATIVE_TYPES.has(column.nativeType)) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" field \"${fieldName}\" is a value object but storage column \"${storageField.column}\" has nativeType \"${column.nativeType}\" (expected json or jsonb)`,\n 'storage',\n );\n }\n }\n }\n }\n}\n\n/**\n * Cross-table consistency checks for SQL storage: primary key, unique,\n * index, and foreign key column references resolve to real columns;\n * NOT NULL columns don't carry a literal `null` default; FK column\n * counts match their referenced columns. Throws on the first mismatch.\n */\nexport function validateSqlStorageConsistency(contract: Contract<SqlStorage>): void {\n for (const { namespaceId, tableName, table: rawTable } of eachStorageTable(contract.storage)) {\n const table = rawTable as StorageTable;\n const columnNames = new Set(Object.keys(table.columns));\n\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" index references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const check of table.checks ?? []) {\n if (!columnNames.has(check.column)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" check constraint \"${check.name}\" references non-existent column \"${check.column}\"`,\n 'storage',\n );\n }\n }\n\n for (const [colName, column] of Object.entries(table.columns)) {\n if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" column \"${colName}\" is NOT NULL but has a literal null default`,\n 'storage',\n );\n }\n }\n\n for (const fk of table.foreignKeys) {\n if (fk.source.namespaceId !== namespaceId || fk.source.tableName !== tableName) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" contains foreignKey with mismatched source coordinates (${fk.source.namespaceId}.${fk.source.tableName})`,\n 'storage',\n );\n }\n\n for (const colName of fk.source.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n\n if (fk.target.spaceId === undefined) {\n const targetNamespace = contract.storage.namespaces[fk.target.namespaceId];\n const referencedRaw = targetNamespace?.entries.table?.[fk.target.tableName];\n if (referencedRaw === undefined) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent table \"${fk.target.namespaceId}.${fk.target.tableName}\"`,\n 'storage',\n );\n }\n const referencedTable = referencedRaw as StorageTable;\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n for (const colName of fk.target.columns) {\n if (!referencedColumnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.target.tableName}\"`,\n 'storage',\n );\n }\n }\n }\n\n if (fk.source.columns.length !== fk.target.columns.length) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey column count (${fk.source.columns.length}) does not match referenced column count (${fk.target.columns.length})`,\n 'storage',\n );\n }\n }\n }\n}\n\nexport interface ValidateSqlContractFullyOptions {\n /**\n * Precomputed structural schema to validate against. Built once at\n * serializer construction time when the family `ContractSerializer`\n * has folded pack-contributed `validatorSchema` fragments into the\n * per-namespace entry shape; absent for the family-default validator\n * path (no pack contributions). Falls back to the cached default\n * `SqlContractSchema` when omitted.\n */\n readonly contractSchema?: Type<unknown>;\n}\n\n/**\n * Full SQL contract validation: structural (arktype) +\n * framework-shared domain + SQL storage logical-consistency + SQL\n * storage semantic + model ↔ storage reference checks. Throws\n * `ContractValidationError` on the first failure. Returns the\n * validated flat-data shape; IR class hydration happens in the SPI\n * base on top of this helper.\n */\nexport function validateSqlContractFully<T extends Contract<SqlStorage>>(\n value: unknown,\n options?: ValidateSqlContractFullyOptions,\n): T {\n const stripped =\n typeof value === 'object' && value !== null\n ? (() => {\n const { schemaVersion: _, _generated: _g, ...rest } = value as Record<string, unknown>;\n return rest;\n })()\n : value;\n const schema = options?.contractSchema ?? SqlContractSchema;\n const validated = validateSqlContractStructure<T>(stripped, schema);\n validateContractDomain({\n roots: validated.roots,\n domain: validated.domain,\n });\n validateSqlStorageConsistency(validated);\n const semanticErrors = validateStorageSemantics(validated.storage);\n if (semanticErrors.length > 0) {\n throw new ContractValidationError(\n `Contract semantic validation failed: ${semanticErrors.join('; ')}`,\n 'storage',\n );\n }\n validateModelStorageReferences(validated);\n return validated;\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,sBAAsB,KAAK,aAAa;AAC9C,MAAM,sBAAsB,KAAK,mDAAmD;AAKpF,MAAM,sCAAsC,KAAK;CAC/C,KAAK;CACL,MAAM;CACN,IAPwB,KAAK,QAAQ,CAAC,CAAC,QAAQ,OAAO,QAAQ;EAC9D,OAAO,8BAA8B,KAAK,KAAK,IAAI,OAAO,IAAI,OAAO,qBAAqB;CAC5F,CAKsB;CACpB,WAAW;AACb,CAAC;AAcD,MAAM,kBAAkB,KAAK;CAC3B,KAAK;CACL,eAAe;CACf,WAAW;EACT,KAAK;EACL,UAjBmC,KAAK;GAC1C,KAAK;GACL,KAAK;IACH,KAAK;IACL,WAAW;IACX,OAAO;IACP,QAAQ;GACV;GACA,aAAa;GACb,aAAa;EACf,CAO2C,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;CAC5D;AACF,CAAC;AAED,MAAM,sBAAsB,KAAK;CAC/B,OAAO;CACP,aAAa;CACb,YAAY;CACZ,YAAY;CACZ,YAAY;AACd,CAAC;;AAkBD,MAAM,kCAV4B,KAC/B,QAA+D,CAAC,CAChE,KAAK;CACJ,MAAM;CACN,SAAS;CACT,YAAY;CACZ,eAAe;AACjB,CAG8D;;;;;AAMhE,MAAa,qBAAqB,KAAK;CACrC,KAAK;CACL,SAAS;CACT,SAAS,KAAK;EACZ,MAAM;EACN,OAAO;CACT,CAAC,CAAC,CACC,MAAM,CAAC,CACP,SAAS;AACd,CAAC;;;;;AAMD,SAAS,aACP,OAC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,MAAM,iBAAiB,yBAAyB,UAAU,OAAO;CACjE,IAAI,eAAe,SAAS,GAC1B,MAAM,IAAI,wBACR,wCAAwC,eAAe,KAAK,IAAI,KAChE,SACF;CAEF,+BAA+B,SAAS;CACxC,OAAO;AACT"} | ||
| {"version":3,"file":"validators.mjs","names":["f","referencedTable"],"sources":["../src/validators.ts"],"sourcesContent":["import { ContractValidationError } from '@prisma-next/contract/contract-validation-error';\nimport {\n type Contract,\n type ContractField,\n type ContractModel,\n CrossReferenceSchema,\n} from '@prisma-next/contract/types';\nimport { validateContractDomain } from '@prisma-next/contract/validate-domain';\nimport {\n type AnyEntityKindDescriptor,\n isPlainRecord,\n type Namespace,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type Type, type } from 'arktype';\nimport { composeSqlEntityKinds } from './entity-kinds';\n\nexport {\n CheckConstraintSchema,\n ColumnDefaultFunctionSchema,\n ColumnDefaultLiteralSchema,\n ColumnDefaultSchema,\n ForeignKeyReferenceSchema,\n ForeignKeySchema,\n ForeignKeySourceSchema,\n IndexSchema,\n ReferentialActionSchema,\n StorageTableSchema,\n StorageValueSetSchema,\n} from './ir/storage-entry-schemas';\n\nimport type {\n SqlModelStorage,\n SqlStorage,\n StorageColumn,\n StorageTable,\n StorageTypeInstanceInput,\n} from './types';\n\nconst generatorKindSchema = type(\"'generator'\");\nconst ControlPolicySchema = type(\"'managed' | 'tolerated' | 'external' | 'observed'\");\nconst generatorIdSchema = type('string').narrow((value, ctx) => {\n return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value) ? true : ctx.mustBe('a flat generator id');\n});\n\nconst ExecutionMutationDefaultValueSchema = type({\n '+': 'reject',\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n '+': 'reject',\n ref: {\n '+': 'reject',\n namespace: 'string',\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n '+': 'reject',\n executionHash: 'string',\n mutations: {\n '+': 'reject',\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst DomainEnumRefSchema = type({\n plane: \"'domain'\",\n namespaceId: 'string',\n entityKind: \"'enum'\",\n entityName: 'string',\n 'spaceId?': 'string',\n});\n\n/**\n * Codec-triple entry persisted under `storage.types[name]`. Carries an\n * enumerable literal `kind: 'codec-instance'` discriminator so the\n * polymorphic slot dispatch can distinguish codec triples from\n * class-instance kinds (e.g. `'postgres-enum'`) sharing the slot.\n */\nconst StorageTypeInstanceSchema = type\n .declare<StorageTypeInstanceInput & { kind: 'codec-instance' }>()\n .type({\n kind: \"'codec-instance'\",\n codecId: 'string',\n nativeType: 'string',\n 'typeParams?': 'Record<string, unknown>',\n });\n\n/** Document-scoped `storage.types`: codec triples only. */\nconst DocumentScopedStorageTypeSchema = StorageTypeInstanceSchema;\n\n/**\n * Domain enum entry under `domain.namespaces[id].enum[name]`.\n * Carries the codec id and an ordered `members` array of `{name, value}` pairs.\n */\nexport const ContractEnumSchema = type({\n '+': 'reject',\n codecId: 'string',\n members: type({\n name: 'string',\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n })\n .array()\n .readonly(),\n});\n\n/**\n * Derives a schema map from a descriptor map: maps each kind's key to its\n * `schema` field. Used by validation functions to validate entries.\n */\nfunction schemaViewOf(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): ReadonlyMap<string, Type<unknown>> {\n return new Map([...kinds].map(([k, d]) => [k, d.schema]));\n}\n\nconst DEFAULT_SQL_KINDS = composeSqlEntityKinds();\n\n/**\n * Builds the per-namespace entry schema for `storage.namespaces[id]`.\n *\n * Validation is descriptor-driven: the `kinds` map carries both the schema\n * (used here for structural validation) and the construct function (used at\n * hydration time). An unregistered key fails validation naming the kind and\n * the namespace id, so validation fails closed.\n */\nexport function createNamespaceEntrySchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const schemas = schemaViewOf(kinds);\n const knownKinds = new Set(kinds.keys());\n return type({\n '+': 'reject',\n id: 'string',\n 'kind?': 'string',\n entries: 'object',\n }).narrow((ns, ctx) => {\n if (!isPlainRecord(ns.entries)) {\n return ctx.mustBe('an entries object');\n }\n for (const [key, innerMap] of Object.entries(ns.entries)) {\n if (!knownKinds.has(key)) {\n return ctx.reject({\n expected: `entries key \"${key}\" in namespace \"${ns.id}\" is not a registered entity kind`,\n });\n }\n if (!isPlainRecord(innerMap)) {\n return ctx.reject({\n expected: `entries[\"${key}\"] in namespace \"${ns.id}\" must be an object`,\n });\n }\n const entrySchema = blindCast<\n Type<unknown>,\n 'knownKinds.has(key) guarantees schemas.get(key) is defined'\n >(schemas.get(key));\n for (const [, value] of Object.entries(innerMap)) {\n const parsed = entrySchema(value);\n if (parsed instanceof type.errors) {\n return ctx.reject({ expected: parsed.summary });\n }\n }\n }\n return true;\n }) as Type<unknown>;\n}\n\n/**\n * Builds the storage schema. Pack contributions reach the per-namespace\n * entry shape through {@link createNamespaceEntrySchema}; the\n * document-scoped `storage.types` field (codec triples only) and the\n * storage hash stay family-shared.\n */\nexport function createSqlStorageSchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const namespaceEntry = createNamespaceEntrySchema(kinds);\n return type({\n '+': 'reject',\n storageHash: 'string',\n 'types?': type({ '[string]': DocumentScopedStorageTypeSchema }),\n // `__unbound__` is NOT required here: cross-namespace contracts can\n // declare only named namespaces (see cross-namespace FK fixtures). The\n // unbound slot is injected when absent by `ensureUnboundNamespaceSlot`\n // in `build-contract.ts`, not enforced here structurally.\n 'namespaces?': type({ '[string]': namespaceEntry }),\n }) as Type<unknown>;\n}\n\nconst StorageSchema = createSqlStorageSchema(DEFAULT_SQL_KINDS);\n\ntype NamespacedStorageWalk = {\n readonly namespaces: Readonly<\n Record<\n string,\n Namespace & { readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>> }\n >\n >;\n};\n\nfunction eachStorageTable(storage: NamespacedStorageWalk) {\n return Object.entries(storage.namespaces).flatMap(([namespaceId, ns]) =>\n Object.entries(ns.entries['table'] ?? {}).map(([tableName, table]) => ({\n namespaceId,\n tableName,\n table,\n })),\n );\n}\n\nfunction findDuplicateValue(values: readonly string[]): string | undefined {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n }\n return undefined;\n}\n\nfunction isContractFieldType(value: unknown): boolean {\n if (!isPlainRecord(value)) return false;\n const kind = value['kind'];\n if (kind === 'scalar') {\n if (typeof value['codecId'] !== 'string') return false;\n const typeParams = value['typeParams'];\n if (typeParams !== undefined && !isPlainRecord(typeParams)) return false;\n return true;\n }\n if (kind === 'valueObject') {\n return typeof value['name'] === 'string';\n }\n if (kind === 'union') {\n const members = value['members'];\n if (!Array.isArray(members)) return false;\n return members.every((m) => isContractFieldType(m));\n }\n return false;\n}\n\nconst ContractFieldTypeSchema = type('unknown').narrow((value, ctx) =>\n isContractFieldType(value) ? true : ctx.mustBe('scalar, valueObject, or union field type'),\n);\n\nconst ModelFieldSchema = type({\n '+': 'reject',\n nullable: 'boolean',\n type: ContractFieldTypeSchema,\n 'many?': 'true',\n 'dict?': 'true',\n 'valueSet?': DomainEnumRefSchema,\n});\n\nconst ModelStorageFieldSchema = type({\n column: 'string',\n 'codecId?': 'string',\n 'nullable?': 'boolean',\n});\n\nconst ModelStorageSchema = type({\n table: 'string',\n namespaceId: 'string',\n fields: type({ '[string]': ModelStorageFieldSchema }),\n});\n\nconst ContractRelationThroughSchema = type({\n '+': 'reject',\n table: 'string',\n namespaceId: 'string',\n parentColumns: type.string.array().readonly(),\n childColumns: type.string.array().readonly(),\n targetColumns: type.string.array().readonly(),\n});\n\nconst ContractRelationOnSchema = type({\n '+': 'reject',\n localFields: type.string.array().readonly(),\n targetFields: type.string.array().readonly(),\n});\n\nconst ContractManyToManyRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'N:M'\",\n on: ContractRelationOnSchema,\n through: ContractRelationThroughSchema,\n});\n\nconst ContractNonJunctionRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'1:1' | '1:N' | 'N:1'\",\n on: ContractRelationOnSchema,\n});\n\nconst ContractReferenceRelationSchema = ContractManyToManyRelationSchema.or(\n ContractNonJunctionRelationSchema,\n);\n\nconst ContractEmbedRelationSchema = type({\n '+': 'reject',\n to: CrossReferenceSchema,\n cardinality: \"'1:1' | '1:N'\",\n});\n\nconst ContractRelationSchema = ContractReferenceRelationSchema.or(ContractEmbedRelationSchema);\n\nconst ModelSchema = type({\n storage: ModelStorageSchema,\n 'fields?': type({ '[string]': ModelFieldSchema }),\n 'relations?': type({ '[string]': ContractRelationSchema }),\n 'discriminator?': 'unknown',\n 'variants?': 'unknown',\n 'base?': CrossReferenceSchema,\n 'owner?': 'string',\n});\n\nconst ContractMetaSchema = type({\n '[string]': 'unknown',\n});\n\n/**\n * Builds the full SQL contract schema. The storage subtree threads\n * pack contributions through {@link createSqlStorageSchema}; the rest\n * of the contract envelope is family-shared.\n */\nexport function createSqlContractSchema(\n kinds: ReadonlyMap<string, AnyEntityKindDescriptor>,\n): Type<unknown> {\n const storage = createSqlStorageSchema(kinds);\n return type({\n '+': 'reject',\n target: 'string',\n targetFamily: \"'sql'\",\n 'coreHash?': 'string',\n profileHash: 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': ContractMetaSchema,\n 'defaultControlPolicy?': ControlPolicySchema,\n 'roots?': type({ '[string]': CrossReferenceSchema }),\n domain: type({\n namespaces: type({\n '[string]': type({\n models: type({ '[string]': ModelSchema }),\n 'valueObjects?': 'Record<string, unknown>',\n 'enum?': type({ '[string]': ContractEnumSchema }),\n }),\n }),\n }),\n storage,\n 'execution?': ExecutionSchema,\n }) as Type<unknown>;\n}\n\nconst SqlContractSchema = createSqlContractSchema(DEFAULT_SQL_KINDS);\n\n/**\n * Validates the structural shape of SqlStorage using Arktype. Pure\n * structural check: namespace IR is never materialized here (that needs\n * a target concretion via the serializer hydration path), so this throws\n * on invalid input and constructs nothing.\n *\n * @param value - The storage value to validate\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): void {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n}\n\nexport function validateModel(value: unknown): unknown {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Structural arktype validation of an SQL contract envelope. Internal\n * helper for {@link validateSqlContractFully} — exposed only inside\n * this module, since the family seam-of-record is the\n * `SqlContractSerializerBase.deserializeContract` SPI.\n */\nfunction validateSqlContractStructure<T extends Contract<SqlStorage>>(\n value: unknown,\n contractSchema: Type<unknown>,\n): T {\n if (typeof value !== 'object' || value === null) {\n throw new ContractValidationError(\n 'Contract structural validation failed: value must be an object',\n 'structural',\n );\n }\n\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n throw new ContractValidationError(\n `Unsupported target family: ${rawValue.targetFamily}`,\n 'structural',\n );\n }\n\n const contractResult = contractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new ContractValidationError(\n `Contract structural validation failed: ${messages}`,\n 'structural',\n );\n }\n\n // Arktype's inferred output type differs from T due to exactOptionalPropertyTypes\n // and branded hash types — the runtime value is structurally compatible after validation\n return contractResult as unknown as T;\n}\n\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - duplicate named primary key / unique / index / foreign key objects within a table\n * - duplicate unique, index, or foreign key declarations within a table\n * - duplicate columns within primary key / unique / index definitions\n * - nullable columns in primary key definitions\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const { namespaceId, tableName, table: rawTable } of eachStorageTable(storage)) {\n const table = rawTable as StorageTable;\n const namedObjects = new Map<string, string[]>();\n const registerNamedObject = (kind: string, name: string | undefined) => {\n if (!name) return;\n namedObjects.set(name, [...(namedObjects.get(name) ?? []), kind]);\n };\n\n registerNamedObject('primary key', table.primaryKey?.name);\n for (const unique of table.uniques) {\n registerNamedObject('unique constraint', unique.name);\n }\n for (const index of table.indexes) {\n registerNamedObject('index', index.name);\n }\n for (const fk of table.foreignKeys) {\n registerNamedObject('foreign key', fk.name);\n }\n for (const check of table.checks ?? []) {\n registerNamedObject('check constraint', check.name);\n }\n\n for (const [name, kinds] of namedObjects) {\n if (kinds.length > 1) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": named object \"${name}\" is declared multiple times (${kinds.join(', ')})`,\n );\n }\n }\n\n if (table.primaryKey) {\n const duplicateColumn = findDuplicateValue(table.primaryKey.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": primary key contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n for (const columnName of table.primaryKey.columns) {\n const column = table.columns[columnName];\n if (column?.nullable === true) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": primary key column \"${columnName}\" is nullable; primary key columns must be NOT NULL`,\n );\n }\n }\n }\n\n const seenUniqueDefinitions = new Set<string>();\n for (const unique of table.uniques) {\n const duplicateColumn = findDuplicateValue(unique.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": unique constraint contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({ columns: unique.columns });\n if (seenUniqueDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate unique constraint definition on columns [${unique.columns.join(', ')}]`,\n );\n continue;\n }\n seenUniqueDefinitions.add(signature);\n }\n\n const sortOptions = (o: Record<string, unknown> | undefined): Record<string, unknown> | null =>\n o ? Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))) : null;\n\n const seenIndexDefinitions = new Set<string>();\n for (const index of table.indexes) {\n const duplicateColumn = findDuplicateValue(index.columns);\n if (duplicateColumn !== undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": index contains duplicate column \"${duplicateColumn}\"`,\n );\n }\n\n const signature = JSON.stringify({\n columns: index.columns,\n type: index.type ?? null,\n options: sortOptions(index.options),\n });\n if (seenIndexDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate index definition on columns [${index.columns.join(', ')}]`,\n );\n continue;\n }\n seenIndexDefinitions.add(signature);\n }\n\n const seenForeignKeyDefinitions = new Set<string>();\n for (const fk of table.foreignKeys) {\n const signature = JSON.stringify({\n source: fk.source,\n target: fk.target,\n onDelete: fk.onDelete ?? null,\n onUpdate: fk.onUpdate ?? null,\n constraint: fk.constraint,\n index: fk.index,\n });\n if (seenForeignKeyDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate foreign key definition on columns [${fk.source.columns.join(', ')}]`,\n );\n continue;\n }\n seenForeignKeyDefinitions.add(signature);\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.source.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n\n const seenCheckDefinitions = new Set<string>();\n for (const check of table.checks ?? []) {\n const signature = JSON.stringify({ column: check.column, valueSet: check.valueSet });\n if (seenCheckDefinitions.has(signature)) {\n errors.push(\n `Namespace \"${namespaceId}\" table \"${tableName}\": duplicate check constraint definition on column \"${check.column}\"`,\n );\n continue;\n }\n seenCheckDefinitions.add(signature);\n }\n }\n\n return errors;\n}\n\n/**\n * SQL storage logical-consistency checks: every model.storage.table\n * resolves to a real table, every model.storage.fields[*].column\n * resolves to a real column, and value-object fields land on JSON-native\n * columns. Throws `ContractValidationError` on the first mismatch.\n */\nexport function validateModelStorageReferences(contract: Contract<SqlStorage>): void {\n for (const [namespaceId, namespace] of Object.entries(contract.domain.namespaces)) {\n const models = namespace.models as Record<string, ContractModel<SqlModelStorage>>;\n for (const [modelName, model] of Object.entries(models)) {\n const qualifiedName = `${namespaceId}:${modelName}`;\n const storageNamespaceId = model.storage.namespaceId;\n if (storageNamespaceId !== namespaceId) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" storage.namespaceId \"${storageNamespaceId}\" does not match domain namespace \"${namespaceId}\"`,\n 'storage',\n );\n }\n\n const storageTable = model.storage.table;\n const storageNs = contract.storage.namespaces[storageNamespaceId];\n const rawTable = storageNs?.entries.table?.[storageTable];\n if (rawTable === undefined) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" references non-existent table \"${storageNamespaceId}.${storageTable}\"`,\n 'storage',\n );\n }\n\n const table = rawTable as StorageTable;\n\n const columnNames = new Set(Object.keys(table.columns));\n for (const [fieldName, field] of Object.entries(model.storage.fields)) {\n if (!columnNames.has(field.column)) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${storageTable}\"`,\n 'storage',\n );\n }\n }\n\n const JSON_NATIVE_TYPES = new Set(['json', 'jsonb']);\n for (const [fieldName, domainField] of Object.entries(model.fields ?? {})) {\n const f = domainField as ContractField;\n if (f.type?.kind !== 'valueObject') continue;\n const storageField = model.storage.fields[fieldName];\n if (!storageField) continue;\n const column = table.columns[storageField.column];\n if (!column) continue;\n if (!JSON_NATIVE_TYPES.has(column.nativeType)) {\n throw new ContractValidationError(\n `Model \"${qualifiedName}\" field \"${fieldName}\" is a value object but storage column \"${storageField.column}\" has nativeType \"${column.nativeType}\" (expected json or jsonb)`,\n 'storage',\n );\n }\n }\n }\n }\n}\n\n/**\n * Cross-table consistency checks for SQL storage: primary key, unique,\n * index, and foreign key column references resolve to real columns;\n * NOT NULL columns don't carry a literal `null` default; FK column\n * counts match their referenced columns. Throws on the first mismatch.\n */\nexport function validateSqlStorageConsistency(contract: Contract<SqlStorage>): void {\n for (const { namespaceId, tableName, table: rawTable } of eachStorageTable(contract.storage)) {\n const table = rawTable as StorageTable;\n const columnNames = new Set(Object.keys(table.columns));\n\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" index references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n }\n\n for (const check of table.checks ?? []) {\n if (!columnNames.has(check.column)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" check constraint \"${check.name}\" references non-existent column \"${check.column}\"`,\n 'storage',\n );\n }\n }\n\n for (const [colName, column] of Object.entries(table.columns)) {\n if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" column \"${colName}\" is NOT NULL but has a literal null default`,\n 'storage',\n );\n }\n }\n\n for (const fk of table.foreignKeys) {\n if (fk.source.namespaceId !== namespaceId || fk.source.tableName !== tableName) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" contains foreignKey with mismatched source coordinates (${fk.source.namespaceId}.${fk.source.tableName})`,\n 'storage',\n );\n }\n\n for (const colName of fk.source.columns) {\n if (!columnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n 'storage',\n );\n }\n }\n\n if (fk.target.spaceId === undefined) {\n const targetNamespace = contract.storage.namespaces[fk.target.namespaceId];\n const referencedRaw = targetNamespace?.entries.table?.[fk.target.tableName];\n if (referencedRaw === undefined) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent table \"${fk.target.namespaceId}.${fk.target.tableName}\"`,\n 'storage',\n );\n }\n const referencedTable = referencedRaw as StorageTable;\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n for (const colName of fk.target.columns) {\n if (!referencedColumnNames.has(colName)) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.target.tableName}\"`,\n 'storage',\n );\n }\n }\n }\n\n if (fk.source.columns.length !== fk.target.columns.length) {\n throw new ContractValidationError(\n `Namespace \"${namespaceId}\" table \"${tableName}\" foreignKey column count (${fk.source.columns.length}) does not match referenced column count (${fk.target.columns.length})`,\n 'storage',\n );\n }\n }\n }\n}\n\nexport interface ValidateSqlContractFullyOptions {\n /**\n * Precomputed structural schema to validate against. Built once at\n * serializer construction time when the family `ContractSerializer`\n * has folded pack-contributed `validatorSchema` fragments into the\n * per-namespace entry shape; absent for the family-default validator\n * path (no pack contributions). Falls back to the cached default\n * `SqlContractSchema` when omitted.\n */\n readonly contractSchema?: Type<unknown>;\n}\n\n/**\n * Full SQL contract validation: structural (arktype) +\n * framework-shared domain + SQL storage logical-consistency + SQL\n * storage semantic + model ↔ storage reference checks. Throws\n * `ContractValidationError` on the first failure. Returns the\n * validated flat-data shape; IR class hydration happens in the SPI\n * base on top of this helper.\n */\nexport function validateSqlContractFully<T extends Contract<SqlStorage>>(\n value: unknown,\n options?: ValidateSqlContractFullyOptions,\n): T {\n const stripped =\n typeof value === 'object' && value !== null\n ? (() => {\n const { schemaVersion: _, _generated: _g, ...rest } = value as Record<string, unknown>;\n return rest;\n })()\n : value;\n const schema = options?.contractSchema ?? SqlContractSchema;\n const validated = validateSqlContractStructure<T>(stripped, schema);\n validateContractDomain({\n roots: validated.roots,\n domain: validated.domain,\n });\n validateSqlStorageConsistency(validated);\n const semanticErrors = validateStorageSemantics(validated.storage);\n if (semanticErrors.length > 0) {\n throw new ContractValidationError(\n `Contract semantic validation failed: ${semanticErrors.join('; ')}`,\n 'storage',\n );\n }\n validateModelStorageReferences(validated);\n validateRelationThroughConsistency(validated);\n return validated;\n}\n\n/** Storage column lookup for through-consistency validation. */\nfunction lookupStorageColumn(\n contract: Contract<SqlStorage>,\n namespaceId: string,\n tableName: string,\n columnName: string,\n): StorageColumn | undefined {\n const rawTable = contract.storage.namespaces[namespaceId]?.entries.table?.[tableName];\n if (rawTable === undefined) {\n return undefined;\n }\n const table = blindCast<StorageTable, 'structurally validated storage table'>(rawTable);\n return table.columns[columnName];\n}\n\n/**\n * Two storage columns share a type when their `nativeType` and `typeParams`\n * match. The contract is canonicalized, so `typeParams` key order is stable and\n * a JSON comparison is exact. `codecId` and `nullable` are intentionally not\n * compared: they do not change the database-level type that governs a join.\n */\nfunction sameStorageType(a: StorageColumn, b: StorageColumn): boolean {\n return (\n a.nativeType === b.nativeType &&\n JSON.stringify(a.typeParams ?? null) === JSON.stringify(b.typeParams ?? null)\n );\n}\n\nfunction describeColumnType(column: StorageColumn): string {\n return column.typeParams === undefined\n ? column.nativeType\n : `${column.nativeType} ${JSON.stringify(column.typeParams)}`;\n}\n\n/**\n * Validates one side of an N:M join: the junction columns and the model\n * columns they pair against positionally must be equal in number, exist in\n * their tables, and share the same storage type (`nativeType` + `typeParams`).\n * The junction's storage foreign keys already guarantee this for user-declared\n * FK constraints, but `through` is a logical descriptor never tied to them by\n * the rest of validation — and the TS builder accepts explicit join columns\n * without requiring a junction FK at all — so this checks the columns directly\n * against storage, one path regardless of how the junction was authored.\n *\n * Joined columns must be the *same* storage type, not merely compatible:\n * relying on implicit conversion (e.g. `text`↔`character`) is unsafe on writes\n * — `character(n)` space-padding makes such coercions non-associative — and no\n * ADR sanctions heterogeneous junction columns. Equality is the conservative\n * default; it can be relaxed deliberately if a real use case ever appears.\n */\nfunction validateThroughJoinSide(input: {\n readonly contract: Contract<SqlStorage>;\n readonly qualifiedName: string;\n readonly modelColumns: readonly string[];\n readonly modelColumnsLabel: string;\n /**\n * The model side of the join, when resolvable. Absent for a cross-space\n * target whose storage lives in another contract: the length and\n * junction-column-existence checks still run, but the target-column\n * existence and type checks are skipped because the target table is not\n * available here. `fieldToColumn` is present when `modelColumns` are domain\n * field names (the `on.*Fields` arrays), absent when they are already storage\n * column names (the `through.*Columns` arrays).\n */\n readonly model?: {\n readonly namespaceId: string;\n readonly table: string;\n readonly fieldToColumn?: Readonly<Record<string, { readonly column: string }>>;\n };\n readonly junctionColumns: readonly string[];\n readonly junctionColumnsLabel: string;\n readonly junctionNamespaceId: string;\n readonly junctionTable: string;\n}): void {\n const fail = (detail: string): ContractValidationError =>\n new ContractValidationError(\n `Many-to-many relation \"${input.qualifiedName}\" ${detail}`,\n 'storage',\n );\n if (input.junctionColumns.length !== input.modelColumns.length) {\n throw fail(\n `pairs ${input.junctionColumnsLabel} (${input.junctionColumns.length}) with ${input.modelColumnsLabel} (${input.modelColumns.length}) of differing length; they join positionally and must match.`,\n );\n }\n for (const [index, junctionColumnName] of input.junctionColumns.entries()) {\n const modelColumnRef = input.modelColumns[index];\n if (modelColumnRef === undefined) {\n continue;\n }\n const junctionColumn = lookupStorageColumn(\n input.contract,\n input.junctionNamespaceId,\n input.junctionTable,\n junctionColumnName,\n );\n if (junctionColumn === undefined) {\n throw fail(\n `${input.junctionColumnsLabel} references column \"${junctionColumnName}\" absent from junction table \"${input.junctionNamespaceId}.${input.junctionTable}\".`,\n );\n }\n // Cross-space target: its storage lives in another contract, so the target\n // column's existence and type cannot be checked here. Length and\n // junction-column existence have already been validated above.\n const model = input.model;\n if (model === undefined) {\n continue;\n }\n let modelColumnName = modelColumnRef;\n if (model.fieldToColumn !== undefined) {\n const mapped = model.fieldToColumn[modelColumnRef];\n if (mapped === undefined) {\n throw fail(\n `${input.modelColumnsLabel} references field \"${modelColumnRef}\" absent from model on table \"${model.namespaceId}.${model.table}\".`,\n );\n }\n modelColumnName = mapped.column;\n }\n const modelColumn = lookupStorageColumn(\n input.contract,\n model.namespaceId,\n model.table,\n modelColumnName,\n );\n if (modelColumn === undefined) {\n throw fail(\n `${input.modelColumnsLabel} references column \"${modelColumnName}\" absent from table \"${model.namespaceId}.${model.table}\".`,\n );\n }\n if (!sameStorageType(junctionColumn, modelColumn)) {\n throw fail(\n `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.`,\n );\n }\n }\n}\n\n/**\n * Validates that every N:M relation's `through` descriptor is consistent with\n * the storage columns it joins: both join sides match in column count,\n * reference columns that exist in their tables, and pair columns of the same\n * storage type. Without this, a `through` that disagrees with storage surfaces\n * as a silently wrong JOIN at query time rather than a validation error here.\n */\nfunction validateRelationThroughConsistency(contract: Contract<SqlStorage>): void {\n for (const [namespaceId, namespace] of Object.entries(contract.domain.namespaces)) {\n for (const [modelName, model] of Object.entries(namespace.models)) {\n for (const [relationName, relation] of Object.entries(model.relations)) {\n if (relation.cardinality !== 'N:M') continue;\n const qualifiedName = `${namespaceId}.${modelName}.${relationName}`;\n const { on, through } = relation;\n const modelStorage = blindCast<SqlModelStorage, 'SQL contract model storage'>(\n model.storage,\n );\n // Parent side: the owning model's localFields (domain field names) join\n // the junction's parentColumns (storage columns).\n validateThroughJoinSide({\n contract,\n qualifiedName,\n modelColumns: on.localFields,\n modelColumnsLabel: 'on.localFields',\n model: {\n namespaceId,\n table: modelStorage.table,\n fieldToColumn: modelStorage.fields,\n },\n junctionColumns: through.parentColumns,\n junctionColumnsLabel: 'through.parentColumns',\n junctionNamespaceId: through.namespaceId,\n junctionTable: through.table,\n });\n // Child side: the junction's childColumns join the target model's\n // targetColumns. Length and junction-column existence are checked\n // regardless; a cross-space target lives in another contract, so its\n // column existence and type are checked only when it is resolvable here.\n const targetModel =\n relation.to.space === undefined\n ? contract.domain.namespaces[relation.to.namespace]?.models[relation.to.model]\n : undefined;\n const targetModelSide =\n targetModel === undefined\n ? undefined\n : {\n namespaceId: relation.to.namespace,\n table: blindCast<SqlModelStorage, 'SQL contract model storage'>(targetModel.storage)\n .table,\n };\n validateThroughJoinSide({\n contract,\n qualifiedName,\n modelColumns: through.targetColumns,\n modelColumnsLabel: 'through.targetColumns',\n ...ifDefined('model', targetModelSide),\n junctionColumns: through.childColumns,\n junctionColumnsLabel: 'through.childColumns',\n junctionNamespaceId: through.namespaceId,\n junctionTable: through.table,\n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"version": "0.14.0", | ||
| "version": "0.15.0", | ||
| "license": "Apache-2.0", | ||
@@ -9,14 +9,14 @@ "type": "module", | ||
| "dependencies": { | ||
| "@prisma-next/contract": "0.14.0", | ||
| "@prisma-next/framework-components": "0.14.0", | ||
| "@prisma-next/utils": "0.14.0", | ||
| "arktype": "^2.2.0" | ||
| "@prisma-next/contract": "0.15.0", | ||
| "@prisma-next/framework-components": "0.15.0", | ||
| "@prisma-next/utils": "0.15.0", | ||
| "arktype": "^2.2.2" | ||
| }, | ||
| "devDependencies": { | ||
| "@prisma-next/test-utils": "0.14.0", | ||
| "@prisma-next/tsconfig": "0.14.0", | ||
| "@prisma-next/tsdown": "0.14.0", | ||
| "tsdown": "0.22.1", | ||
| "@prisma-next/test-utils": "0.15.0", | ||
| "@prisma-next/tsconfig": "0.15.0", | ||
| "@prisma-next/tsdown": "0.15.0", | ||
| "tsdown": "0.22.3", | ||
| "typescript": "5.9.3", | ||
| "vitest": "4.1.8" | ||
| "vitest": "4.1.10" | ||
| }, | ||
@@ -37,2 +37,4 @@ "peerDependencies": { | ||
| "./canonicalization-hooks": "./dist/canonicalization-hooks.mjs", | ||
| "./contract-view": "./dist/contract-view.mjs", | ||
| "./entity-handle-lowering-hook": "./dist/entity-handle-lowering-hook.mjs", | ||
| "./entity-kinds": "./dist/entity-kinds.mjs", | ||
@@ -47,2 +49,3 @@ "./factories": "./dist/factories.mjs", | ||
| "./validators": "./dist/validators.mjs", | ||
| "./value-set-derivation-hook": "./dist/value-set-derivation-hook.mjs", | ||
| "./package.json": "./package.json" | ||
@@ -49,0 +52,0 @@ }, |
@@ -5,2 +5,3 @@ import type { PreserveEmptyPredicate, StorageSort } from '@prisma-next/contract/hashing'; | ||
| createStorageSort, | ||
| matchesPathPattern, | ||
| type NamedArraySortTarget, | ||
@@ -15,4 +16,30 @@ type PathPattern, | ||
| ['storage', 'namespaces', '*', 'entries', 'table', '*', 'foreignKeys', ['constraint', 'index']], | ||
| // A column default's literal payload is data, not shape — `{ kind: | ||
| // 'literal', value: false }` (or `value: []`) must survive the | ||
| // default-omission walk or the emitted contract fails its own | ||
| // validation on the next read (PN-CLI-4003 on `Boolean @default(false)`). | ||
| ['storage', 'namespaces', '*', 'entries', 'table', '*', 'columns', '*', 'default', 'value'], | ||
| ] as const satisfies readonly PathPattern[]; | ||
| // A literal column default's value is user data, not omittable structure: | ||
| // `@default(false)` (and empty objects/arrays at any depth inside the value) | ||
| // must survive canonicalization, or the emitted contract fails the runtime's | ||
| // structural validation with `default.value … (was missing)`. | ||
| const columnDefaultValuePrefix = [ | ||
| 'storage', | ||
| 'namespaces', | ||
| '*', | ||
| 'entries', | ||
| 'table', | ||
| '*', | ||
| 'columns', | ||
| '*', | ||
| 'default', | ||
| 'value', | ||
| ] as const satisfies PathPattern; | ||
| const isColumnDefaultValuePath = (path: readonly string[]): boolean => | ||
| path.length >= columnDefaultValuePrefix.length && | ||
| matchesPathPattern(path.slice(0, columnDefaultValuePrefix.length), columnDefaultValuePrefix); | ||
| const sortTargets = [ | ||
@@ -22,5 +49,7 @@ { path: ['namespaces', '*', 'entries', 'table', '*'], arrayKeys: ['indexes', 'uniques'] }, | ||
| const shouldPreserveEmpty: PreserveEmptyPredicate = | ||
| createPreserveEmptyPredicate(preserveEmptyPatterns); | ||
| const matchesPreserveEmptyPattern = createPreserveEmptyPredicate(preserveEmptyPatterns); | ||
| const shouldPreserveEmpty: PreserveEmptyPredicate = (path) => | ||
| isColumnDefaultValuePath(path) || matchesPreserveEmptyPattern(path); | ||
| const sortStorage: StorageSort = createStorageSort(sortTargets); | ||
@@ -27,0 +56,0 @@ |
+17
-4
| export type { | ||
| StorageColumnMapAt, | ||
| StorageColumnTypeAcrossNamespaces, | ||
| } from '../column-type-resolution'; | ||
| export type { | ||
| CheckConstraintInput, | ||
@@ -9,2 +13,4 @@ CodecTypesOf, | ||
| ExtractQueryOperationTypes, | ||
| ExtractStorageColumnInputTypes, | ||
| ExtractStorageColumnTypes, | ||
| ExtractTypeMapsFromContract, | ||
@@ -17,2 +23,4 @@ FieldInputTypesOf, | ||
| IndexInput, | ||
| NamespacedFieldTypeMap, | ||
| NamespacedStorageColumnTypeMap, | ||
| PrimaryKeyInput, | ||
@@ -26,2 +34,3 @@ QueryOperationReturn, | ||
| ResolveCodecTypes, | ||
| SqlAuthoringContributions, | ||
| SqlControlDriverInstance, | ||
@@ -32,3 +41,4 @@ SqlModelFieldStorage, | ||
| SqlNamespaceEntries, | ||
| SqlNamespaceTablesInput, | ||
| SqlNamespaceFactory, | ||
| SqlNamespaceInput, | ||
| SqlQueryOperationTypes, | ||
@@ -38,2 +48,4 @@ SqlStorageInput, | ||
| StorageColumnInput, | ||
| StorageColumnInputTypesOf, | ||
| StorageColumnTypesOf, | ||
| StorageTableInput, | ||
@@ -49,4 +61,2 @@ StorageTypeInstance, | ||
| applyFkDefaults, | ||
| buildSqlNamespace, | ||
| buildSqlNamespaceMap, | ||
| CheckConstraint, | ||
@@ -59,7 +69,10 @@ CODEC_INSTANCE_KIND, | ||
| Index, | ||
| isMaterializedSqlNamespace, | ||
| isSqlAuthoringContributions, | ||
| isStorageTypeInstance, | ||
| isStorageValueSet, | ||
| PrimaryKey, | ||
| SqlNamespaceBase, | ||
| SqlNode, | ||
| SqlStorage, | ||
| SqlUnboundNamespace, | ||
| StorageColumn, | ||
@@ -66,0 +79,0 @@ StorageTable, |
+12
-2
@@ -17,4 +17,14 @@ import { asNamespaceId, type ScalarFieldType } from '@prisma-next/contract/types'; | ||
| export function col(nativeType: string, codecId: string, nullable = false): StorageColumn { | ||
| return new StorageColumn({ nativeType, codecId, nullable }); | ||
| export function col( | ||
| nativeType: string, | ||
| codecId: string, | ||
| nullable = false, | ||
| opts?: { readonly many?: boolean }, | ||
| ): StorageColumn { | ||
| return new StorageColumn({ | ||
| nativeType, | ||
| codecId, | ||
| nullable, | ||
| ...(opts?.many !== undefined && { many: opts.many }), | ||
| }); | ||
| } | ||
@@ -21,0 +31,0 @@ |
+81
-17
| import type { StorageHashBase } from '@prisma-next/contract/types'; | ||
| import { freezeNode, type Namespace, type Storage } from '@prisma-next/framework-components/ir'; | ||
| import type { AuthoringContributions } from '@prisma-next/framework-components/authoring'; | ||
| import { | ||
| freezeNode, | ||
| isPlainRecord, | ||
| type Namespace, | ||
| NamespaceBase, | ||
| type Storage, | ||
| } from '@prisma-next/framework-components/ir'; | ||
| import { SqlNode } from './sql-node'; | ||
@@ -22,3 +29,3 @@ import type { StorageTable } from './storage-table'; | ||
| export interface SqlNamespaceTablesInput { | ||
| export interface SqlNamespaceInput { | ||
| readonly id: string; | ||
@@ -28,6 +35,36 @@ readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>; | ||
| /** | ||
| * Target-supplied factory that materializes a `Namespace` from a SQL | ||
| * `SqlNamespaceInput` (used to populate `SqlStorage.namespaces`). | ||
| */ | ||
| export type SqlNamespaceFactory = (input: SqlNamespaceInput) => Namespace; | ||
| /** | ||
| * SQL-family extension of the framework `AuthoringContributions`. SQL target | ||
| * packs add a `createNamespace` factory so the PSL/TS authoring paths can | ||
| * materialize namespaces (and merge lowered extension-block entities) without | ||
| * each consumer re-specifying it. The factory is SQL-specific, so it lives here | ||
| * rather than on the framework `AuthoringContributions` base. | ||
| */ | ||
| export interface SqlAuthoringContributions extends AuthoringContributions { | ||
| readonly createNamespace?: SqlNamespaceFactory; | ||
| } | ||
| /** | ||
| * Narrows framework `AuthoringContributions` to the SQL-family shape by testing | ||
| * for the SQL-specific `createNamespace` capability. | ||
| */ | ||
| export function isSqlAuthoringContributions( | ||
| authoring: AuthoringContributions | undefined, | ||
| ): authoring is SqlAuthoringContributions { | ||
| if (authoring === undefined || !Object.hasOwn(authoring, 'createNamespace')) { | ||
| return false; | ||
| } | ||
| return typeof Reflect.get(authoring, 'createNamespace') === 'function'; | ||
| } | ||
| export interface SqlStorageInput<THash extends string = string> { | ||
| readonly storageHash: StorageHashBase<THash>; | ||
| readonly types?: Record<string, SqlStorageTypeEntry>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespace>>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespaceBase>>; | ||
| } | ||
@@ -68,19 +105,46 @@ | ||
| /** | ||
| * SQL family namespace. `entries` is the open ADR 224 dictionary — | ||
| * `entries[entityKind][entityName]` addresses any entity. Emitted | ||
| * contract literals satisfy this structurally (no prototype getters | ||
| * needed). For typed access to specific kinds, use the class getters | ||
| * on the concretion or `ns.entries.table` / `ns.entries.valueSet` directly. | ||
| * Structural interface for SQL family namespaces. Generated `.d.ts` contract | ||
| * types satisfy this structurally (no prototype methods). The runtime | ||
| * abstract class `SqlNamespaceBase` extends this. | ||
| * | ||
| * `qualifyTable` and `isUnbound` are optional so JSON-shaped contract types | ||
| * (which carry no methods) are accepted where `SqlNamespace` is required. | ||
| * Hydrated `SqlNamespaceBase` instances always have both. | ||
| */ | ||
| export type SqlNamespace = Namespace & { | ||
| export interface SqlNamespace { | ||
| readonly kind: string; | ||
| readonly id: string; | ||
| readonly entries: SqlNamespaceEntries; | ||
| /** | ||
| * Render a dialect-qualified table reference for runtime SQL emission. | ||
| * Present on materialised target concretions (`PostgresSchema`, | ||
| * `SqliteDatabase`, …) and family placeholders; omitted on emitted | ||
| * contract structural namespace literals (methods are not serialised). | ||
| */ | ||
| readonly isUnbound?: boolean; | ||
| qualifyTable?(tableName: string): string; | ||
| }; | ||
| } | ||
| /** | ||
| * Abstract SQL family namespace base class. Target concretions (`PostgresSchema`, | ||
| * `SqliteDatabase`, …) extend this — it is never instantiated directly. | ||
| * `entries` is the open ADR 224 dictionary: `entries[entityKind][entityName]` | ||
| * addresses any entity. | ||
| */ | ||
| export abstract class SqlNamespaceBase extends NamespaceBase implements SqlNamespace { | ||
| abstract override readonly id: string; | ||
| abstract override readonly entries: SqlNamespaceEntries; | ||
| abstract qualifyTable(tableName: string): string; | ||
| } | ||
| /** | ||
| * Realm-safe guard for hydrated `SqlNamespaceBase` concretions. Checks | ||
| * `qualifyTable` structurally instead of `instanceof NamespaceBase`, so it | ||
| * survives duplicate-module boundaries (e.g. dist e2e where the target and | ||
| * the family carry separate copies of `@prisma-next/framework-components`). | ||
| * | ||
| * Every concrete `SqlNamespaceBase` subclass (`PostgresSchema`, `SqliteDatabase`, | ||
| * `TestSqlNamespace`, …) implements `qualifyTable`. Raw `SqlNamespaceInput` | ||
| * objects (`{ id, entries }`) do not. | ||
| */ | ||
| export function isMaterializedSqlNamespace(x: unknown): x is SqlNamespaceBase { | ||
| if (typeof x !== 'object' || x === null || !('qualifyTable' in x)) return false; | ||
| return typeof x.qualifyTable === 'function'; | ||
| } | ||
| export class SqlStorage<THash extends string = string> extends SqlNode implements Storage { | ||
@@ -134,3 +198,3 @@ readonly storageHash: StorageHashBase<THash>; | ||
| } | ||
| const rawKind = (entry as { kind?: unknown }).kind; | ||
| const rawKind = isPlainRecord(entry) ? entry['kind'] : undefined; | ||
| const kindDescription = | ||
@@ -137,0 +201,0 @@ rawKind === undefined |
@@ -19,2 +19,3 @@ import type { ColumnDefault, ControlPolicy, ValueSetRef } from '@prisma-next/contract/types'; | ||
| readonly nullable: boolean; | ||
| readonly many?: boolean; | ||
| readonly typeParams?: Record<string, unknown>; | ||
@@ -44,2 +45,3 @@ readonly typeRef?: string; | ||
| readonly nullable: boolean; | ||
| declare readonly many?: boolean; | ||
| declare readonly typeParams?: Record<string, unknown>; | ||
@@ -56,2 +58,3 @@ declare readonly typeRef?: string; | ||
| this.nullable = input.nullable; | ||
| if (input.many !== undefined) this.many = input.many; | ||
| if (input.typeParams !== undefined) this.typeParams = input.typeParams; | ||
@@ -58,0 +61,0 @@ if (input.typeRef !== undefined) this.typeRef = input.typeRef; |
@@ -42,2 +42,3 @@ import { type Type, type } from 'arktype'; | ||
| nullable: 'boolean', | ||
| 'many?': 'boolean', | ||
| 'typeParams?': 'Record<string, unknown>', | ||
@@ -44,0 +45,0 @@ 'typeRef?': 'string', |
@@ -71,2 +71,23 @@ import type { ControlPolicy } from '@prisma-next/contract/types'; | ||
| } | ||
| /** | ||
| * Runtime guard that a namespace `table` entry is really a `StorageTable`. | ||
| * The compiler already types the entry as `StorageTable`, but a | ||
| * freshly-deserialized contract may carry plain JSON at that slot until | ||
| * hydration; this duck-types the structural shape. Accepts `undefined` so | ||
| * optional-chained entry lookups pass straight through. | ||
| */ | ||
| static is(value: StorageTable | undefined): value is StorageTable { | ||
| if (typeof value !== 'object' || value === null) return false; | ||
| return 'columns' in value && 'uniques' in value && 'indexes' in value && 'foreignKeys' in value; | ||
| } | ||
| static assert( | ||
| value: StorageTable | undefined, | ||
| coordinate: string, | ||
| ): asserts value is StorageTable { | ||
| if (!StorageTable.is(value)) { | ||
| throw new Error(`Expected a StorageTable at ${coordinate}`); | ||
| } | ||
| } | ||
| } |
@@ -44,1 +44,6 @@ import type { JsonValue } from '@prisma-next/contract/types'; | ||
| } | ||
| export function isStorageValueSet(value: unknown): value is StorageValueSet { | ||
| if (typeof value !== 'object' || value === null) return false; | ||
| return 'kind' in value && value.kind === 'valueSet' && 'values' in value; | ||
| } |
+51
-8
@@ -13,3 +13,2 @@ import type { CodecTrait } from '@prisma-next/framework-components/codec'; | ||
| export { buildSqlNamespace, buildSqlNamespaceMap } from './ir/build-sql-namespace'; | ||
| export { CheckConstraint, type CheckConstraintInput } from './ir/check-constraint'; | ||
@@ -29,5 +28,10 @@ export { | ||
| export { | ||
| isMaterializedSqlNamespace, | ||
| isSqlAuthoringContributions, | ||
| type SqlAuthoringContributions, | ||
| type SqlNamespace, | ||
| SqlNamespaceBase, | ||
| type SqlNamespaceEntries, | ||
| type SqlNamespaceTablesInput, | ||
| type SqlNamespaceFactory, | ||
| type SqlNamespaceInput, | ||
| SqlStorage, | ||
@@ -37,3 +41,2 @@ type SqlStorageInput, | ||
| } from './ir/sql-storage'; | ||
| export { SqlUnboundNamespace } from './ir/sql-unbound-namespace'; | ||
| export { StorageColumn, type StorageColumnInput } from './ir/storage-column'; | ||
@@ -48,4 +51,8 @@ export { StorageTable, type StorageTableInput } from './ir/storage-table'; | ||
| } from './ir/storage-type-instance'; | ||
| export { StorageValueSet, type StorageValueSetInput } from './ir/storage-value-set'; | ||
| export { | ||
| isStorageValueSet, | ||
| StorageValueSet, | ||
| type StorageValueSetInput, | ||
| } from './ir/storage-value-set'; | ||
| export { | ||
| UniqueConstraint, | ||
@@ -90,2 +97,7 @@ type UniqueConstraintInput, | ||
| export type NamespacedStorageColumnTypeMap = Record< | ||
| string, | ||
| Record<string, Record<string, unknown>> | ||
| >; | ||
| export type TypeMaps< | ||
@@ -96,2 +108,4 @@ TCodecTypes extends Record<string, { output: unknown }> = Record<string, never>, | ||
| TFieldInputTypes extends NamespacedFieldTypeMap = Record<string, never>, | ||
| TStorageColumnTypes extends NamespacedStorageColumnTypeMap = Record<string, never>, | ||
| TStorageColumnInputTypes extends NamespacedStorageColumnTypeMap = Record<string, never>, | ||
| > = { | ||
@@ -102,2 +116,4 @@ readonly codecTypes: TCodecTypes; | ||
| readonly fieldInputTypes: TFieldInputTypes; | ||
| readonly storageColumnTypes: TStorageColumnTypes; | ||
| readonly storageColumnInputTypes: TStorageColumnInputTypes; | ||
| }; | ||
@@ -117,8 +133,15 @@ | ||
| * Used by ORM column helpers to decide whether an operation is reachable on a | ||
| * field. Either names a concrete codec identity or a set of capability traits | ||
| * that the field's codec must carry. | ||
| * field. Names a concrete codec identity, a set of capability traits the | ||
| * field's codec must carry, or targets list-typed (`many`) fields. Element | ||
| * capability gating for list ops travels in `elementTraits`. | ||
| */ | ||
| export type QueryOperationSelfSpec = | ||
| | { readonly codecId: string; readonly traits?: never } | ||
| | { readonly traits: readonly CodecTrait[]; readonly codecId?: never }; | ||
| | { readonly codecId: string; readonly traits?: never; readonly many?: never } | ||
| | { readonly traits: readonly CodecTrait[]; readonly codecId?: never; readonly many?: never } | ||
| | { | ||
| readonly many: true; | ||
| readonly elementTraits?: readonly CodecTrait[]; | ||
| readonly codecId?: never; | ||
| readonly traits?: never; | ||
| }; | ||
@@ -183,2 +206,18 @@ /** | ||
| export type StorageColumnTypesOf<T> = [T] extends [never] | ||
| ? Record<string, never> | ||
| : T extends { readonly storageColumnTypes: infer F } | ||
| ? F extends NamespacedStorageColumnTypeMap | ||
| ? F | ||
| : Record<string, never> | ||
| : Record<string, never>; | ||
| export type StorageColumnInputTypesOf<T> = [T] extends [never] | ||
| ? Record<string, never> | ||
| : T extends { readonly storageColumnInputTypes: infer F } | ||
| ? F extends NamespacedStorageColumnTypeMap | ||
| ? F | ||
| : Record<string, never> | ||
| : Record<string, never>; | ||
| export type ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>; | ||
@@ -188,2 +227,6 @@ export type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| export type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| export type ExtractStorageColumnTypes<T> = StorageColumnTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| export type ExtractStorageColumnInputTypes<T> = StorageColumnInputTypesOf< | ||
| ExtractTypeMapsFromContract<T> | ||
| >; | ||
@@ -190,0 +233,0 @@ export type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] |
+215
-40
@@ -13,3 +13,2 @@ import { ContractValidationError } from '@prisma-next/contract/contract-validation-error'; | ||
| type Namespace, | ||
| UNBOUND_NAMESPACE_ID, | ||
| } from '@prisma-next/framework-components/ir'; | ||
@@ -20,3 +19,2 @@ import { blindCast } from '@prisma-next/utils/casts'; | ||
| import { composeSqlEntityKinds } from './entity-kinds'; | ||
| import { buildSqlNamespaceMap } from './ir/build-sql-namespace'; | ||
@@ -37,9 +35,8 @@ export { | ||
| import { SqlUnboundNamespace } from './ir/sql-unbound-namespace'; | ||
| import { | ||
| type SqlModelStorage, | ||
| import type { | ||
| SqlModelStorage, | ||
| SqlStorage, | ||
| type SqlStorageInput, | ||
| type StorageTable, | ||
| type StorageTypeInstanceInput, | ||
| StorageColumn, | ||
| StorageTable, | ||
| StorageTypeInstanceInput, | ||
| } from './types'; | ||
@@ -198,5 +195,4 @@ | ||
| // declare only named namespaces (see cross-namespace FK fixtures). The | ||
| // `__unbound__` brand on `SqlStorageInput['namespaces']` is kept sound at | ||
| // construction time by injecting the unbound singleton when absent | ||
| // (see `validateStorage` / `hydrateSqlStorage`), not by structural require. | ||
| // unbound slot is injected when absent by `ensureUnboundNamespaceSlot` | ||
| // in `build-contract.ts`, not enforced here structurally. | ||
| 'namespaces?': type({ '[string]': namespaceEntry }), | ||
@@ -375,16 +371,12 @@ }) as Type<unknown>; | ||
| // NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type() | ||
| // instead of type.declare<T>().type() because the ColumnDefault union's value field | ||
| // includes bigint | Date (runtime-only types after decoding) which cannot be expressed | ||
| // in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges | ||
| // the gap between the JSON-safe Arktype output and the runtime TypeScript type. | ||
| /** | ||
| * Validates the structural shape of SqlStorage using Arktype. | ||
| * Validates the structural shape of SqlStorage using Arktype. Pure | ||
| * structural check: namespace IR is never materialized here (that needs | ||
| * a target concretion via the serializer hydration path), so this throws | ||
| * on invalid input and constructs nothing. | ||
| * | ||
| * @param value - The storage value to validate | ||
| * @returns The validated storage if structure is valid | ||
| * @throws Error if the storage structure is invalid | ||
| */ | ||
| export function validateStorage(value: unknown): SqlStorage { | ||
| export function validateStorage(value: unknown): void { | ||
| const result = StorageSchema(value); | ||
@@ -395,22 +387,2 @@ if (result instanceof type.errors) { | ||
| } | ||
| // Arktype validates the JSON-safe envelope, but the `ColumnDefault` | ||
| // union carries runtime-only `bigint | Date` that the validation DSL | ||
| // can't express (see NOTE above), so bridge the validated shape to the | ||
| // input type. Construction below re-materialises nested IR fields. | ||
| const validated = blindCast< | ||
| SqlStorageInput & { readonly namespaces?: SqlStorageInput['namespaces'] }, | ||
| 'arktype validated the JSON envelope but its output type is unknown (ColumnDefault carries runtime-only bigint|Date); bridge to the input shape' | ||
| >(result); | ||
| const namespaces = buildSqlNamespaceMap(validated.namespaces ?? {}); | ||
| // Compatibility shim: inject the empty unbound singleton when absent so that | ||
| // production code paths which address __unbound__ for table metadata have a | ||
| // slot to read or write into. The `SqlStorageInput['namespaces']` type no | ||
| // longer requires __unbound__, so this is a runtime convenience, not a type | ||
| // invariant. | ||
| const unbound = namespaces[UNBOUND_NAMESPACE_ID] ?? SqlUnboundNamespace.instance; | ||
| return new SqlStorage({ | ||
| storageHash: validated.storageHash, | ||
| ...ifDefined('types', validated.types), | ||
| namespaces: { ...namespaces, [UNBOUND_NAMESPACE_ID]: unbound }, | ||
| }); | ||
| } | ||
@@ -855,3 +827,206 @@ | ||
| validateModelStorageReferences(validated); | ||
| validateRelationThroughConsistency(validated); | ||
| return validated; | ||
| } | ||
| /** Storage column lookup for through-consistency validation. */ | ||
| function lookupStorageColumn( | ||
| contract: Contract<SqlStorage>, | ||
| namespaceId: string, | ||
| tableName: string, | ||
| columnName: string, | ||
| ): StorageColumn | undefined { | ||
| const rawTable = contract.storage.namespaces[namespaceId]?.entries.table?.[tableName]; | ||
| if (rawTable === undefined) { | ||
| return undefined; | ||
| } | ||
| const table = blindCast<StorageTable, 'structurally validated storage table'>(rawTable); | ||
| return table.columns[columnName]; | ||
| } | ||
| /** | ||
| * Two storage columns share a type when their `nativeType` and `typeParams` | ||
| * match. The contract is canonicalized, so `typeParams` key order is stable and | ||
| * a JSON comparison is exact. `codecId` and `nullable` are intentionally not | ||
| * compared: they do not change the database-level type that governs a join. | ||
| */ | ||
| function sameStorageType(a: StorageColumn, b: StorageColumn): boolean { | ||
| return ( | ||
| a.nativeType === b.nativeType && | ||
| JSON.stringify(a.typeParams ?? null) === JSON.stringify(b.typeParams ?? null) | ||
| ); | ||
| } | ||
| function describeColumnType(column: StorageColumn): string { | ||
| return column.typeParams === undefined | ||
| ? column.nativeType | ||
| : `${column.nativeType} ${JSON.stringify(column.typeParams)}`; | ||
| } | ||
| /** | ||
| * Validates one side of an N:M join: the junction columns and the model | ||
| * columns they pair against positionally must be equal in number, exist in | ||
| * their tables, and share the same storage type (`nativeType` + `typeParams`). | ||
| * The junction's storage foreign keys already guarantee this for user-declared | ||
| * FK constraints, but `through` is a logical descriptor never tied to them by | ||
| * the rest of validation — and the TS builder accepts explicit join columns | ||
| * without requiring a junction FK at all — so this checks the columns directly | ||
| * against storage, one path regardless of how the junction was authored. | ||
| * | ||
| * Joined columns must be the *same* storage type, not merely compatible: | ||
| * relying on implicit conversion (e.g. `text`↔`character`) is unsafe on writes | ||
| * — `character(n)` space-padding makes such coercions non-associative — and no | ||
| * ADR sanctions heterogeneous junction columns. Equality is the conservative | ||
| * default; it can be relaxed deliberately if a real use case ever appears. | ||
| */ | ||
| function validateThroughJoinSide(input: { | ||
| readonly contract: Contract<SqlStorage>; | ||
| readonly qualifiedName: string; | ||
| readonly modelColumns: readonly string[]; | ||
| readonly modelColumnsLabel: string; | ||
| /** | ||
| * The model side of the join, when resolvable. Absent for a cross-space | ||
| * target whose storage lives in another contract: the length and | ||
| * junction-column-existence checks still run, but the target-column | ||
| * existence and type checks are skipped because the target table is not | ||
| * available here. `fieldToColumn` is present when `modelColumns` are domain | ||
| * field names (the `on.*Fields` arrays), absent when they are already storage | ||
| * column names (the `through.*Columns` arrays). | ||
| */ | ||
| readonly model?: { | ||
| readonly namespaceId: string; | ||
| readonly table: string; | ||
| readonly fieldToColumn?: Readonly<Record<string, { readonly column: string }>>; | ||
| }; | ||
| readonly junctionColumns: readonly string[]; | ||
| readonly junctionColumnsLabel: string; | ||
| readonly junctionNamespaceId: string; | ||
| readonly junctionTable: string; | ||
| }): void { | ||
| const fail = (detail: string): ContractValidationError => | ||
| new ContractValidationError( | ||
| `Many-to-many relation "${input.qualifiedName}" ${detail}`, | ||
| 'storage', | ||
| ); | ||
| 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.`, | ||
| ); | ||
| } | ||
| for (const [index, junctionColumnName] of input.junctionColumns.entries()) { | ||
| const modelColumnRef = input.modelColumns[index]; | ||
| if (modelColumnRef === undefined) { | ||
| continue; | ||
| } | ||
| const junctionColumn = lookupStorageColumn( | ||
| input.contract, | ||
| input.junctionNamespaceId, | ||
| input.junctionTable, | ||
| junctionColumnName, | ||
| ); | ||
| if (junctionColumn === undefined) { | ||
| throw fail( | ||
| `${input.junctionColumnsLabel} references column "${junctionColumnName}" absent from junction table "${input.junctionNamespaceId}.${input.junctionTable}".`, | ||
| ); | ||
| } | ||
| // Cross-space target: its storage lives in another contract, so the target | ||
| // column's existence and type cannot be checked here. Length and | ||
| // junction-column existence have already been validated above. | ||
| const model = input.model; | ||
| if (model === undefined) { | ||
| continue; | ||
| } | ||
| let modelColumnName = modelColumnRef; | ||
| if (model.fieldToColumn !== undefined) { | ||
| const mapped = model.fieldToColumn[modelColumnRef]; | ||
| if (mapped === undefined) { | ||
| throw fail( | ||
| `${input.modelColumnsLabel} references field "${modelColumnRef}" absent from model on table "${model.namespaceId}.${model.table}".`, | ||
| ); | ||
| } | ||
| modelColumnName = mapped.column; | ||
| } | ||
| const modelColumn = lookupStorageColumn( | ||
| input.contract, | ||
| model.namespaceId, | ||
| model.table, | ||
| modelColumnName, | ||
| ); | ||
| if (modelColumn === undefined) { | ||
| throw fail( | ||
| `${input.modelColumnsLabel} references column "${modelColumnName}" absent from table "${model.namespaceId}.${model.table}".`, | ||
| ); | ||
| } | ||
| 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.`, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| /** | ||
| * Validates that every N:M relation's `through` descriptor is consistent with | ||
| * the storage columns it joins: both join sides match in column count, | ||
| * reference columns that exist in their tables, and pair columns of the same | ||
| * storage type. Without this, a `through` that disagrees with storage surfaces | ||
| * as a silently wrong JOIN at query time rather than a validation error here. | ||
| */ | ||
| function validateRelationThroughConsistency(contract: Contract<SqlStorage>): void { | ||
| 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)) { | ||
| if (relation.cardinality !== 'N:M') continue; | ||
| const qualifiedName = `${namespaceId}.${modelName}.${relationName}`; | ||
| const { on, through } = relation; | ||
| const modelStorage = blindCast<SqlModelStorage, 'SQL contract model storage'>( | ||
| model.storage, | ||
| ); | ||
| // Parent side: the owning model's localFields (domain field names) join | ||
| // the junction's parentColumns (storage columns). | ||
| validateThroughJoinSide({ | ||
| contract, | ||
| qualifiedName, | ||
| modelColumns: on.localFields, | ||
| modelColumnsLabel: 'on.localFields', | ||
| model: { | ||
| namespaceId, | ||
| table: modelStorage.table, | ||
| fieldToColumn: modelStorage.fields, | ||
| }, | ||
| junctionColumns: through.parentColumns, | ||
| junctionColumnsLabel: 'through.parentColumns', | ||
| junctionNamespaceId: through.namespaceId, | ||
| junctionTable: through.table, | ||
| }); | ||
| // Child side: the junction's childColumns join the target model's | ||
| // targetColumns. Length and junction-column existence are checked | ||
| // regardless; a cross-space target lives in another contract, so its | ||
| // column existence and type are checked only when it is resolvable here. | ||
| const targetModel = | ||
| relation.to.space === undefined | ||
| ? contract.domain.namespaces[relation.to.namespace]?.models[relation.to.model] | ||
| : undefined; | ||
| const targetModelSide = | ||
| targetModel === undefined | ||
| ? undefined | ||
| : { | ||
| namespaceId: relation.to.namespace, | ||
| table: blindCast<SqlModelStorage, 'SQL contract model storage'>(targetModel.storage) | ||
| .table, | ||
| }; | ||
| validateThroughJoinSide({ | ||
| contract, | ||
| qualifiedName, | ||
| modelColumns: through.targetColumns, | ||
| modelColumnsLabel: 'through.targetColumns', | ||
| ...ifDefined('model', targetModelSide), | ||
| junctionColumns: through.childColumns, | ||
| junctionColumnsLabel: 'through.childColumns', | ||
| junctionNamespaceId: through.namespaceId, | ||
| junctionTable: through.table, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| } |
| import { type } from "arktype"; | ||
| import { IRNodeBase, freezeNode } from "@prisma-next/framework-components/ir"; | ||
| import { asNamespaceId } from "@prisma-next/contract/types"; | ||
| //#region src/ir/storage-entry-schemas.ts | ||
| const literalKindSchema = type("'literal'"); | ||
| const functionKindSchema = type("'function'"); | ||
| const ControlPolicySchema = type("'managed' | 'tolerated' | 'external' | 'observed'"); | ||
| const ColumnDefaultLiteralSchema = type.declare().type({ | ||
| kind: literalKindSchema, | ||
| value: "string | number | boolean | null | unknown[] | Record<string, unknown>" | ||
| }); | ||
| const ColumnDefaultFunctionSchema = type.declare().type({ | ||
| kind: functionKindSchema, | ||
| expression: "string" | ||
| }); | ||
| const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema); | ||
| const StorageValueSetRefSchema = type({ | ||
| plane: "'storage'", | ||
| namespaceId: "string", | ||
| entityKind: "'valueSet'", | ||
| entityName: "string", | ||
| "spaceId?": "string" | ||
| }); | ||
| const StorageColumnSchema = type({ | ||
| "+": "reject", | ||
| nativeType: "string", | ||
| codecId: "string", | ||
| nullable: "boolean", | ||
| "typeParams?": "Record<string, unknown>", | ||
| "typeRef?": "string", | ||
| "default?": ColumnDefaultSchema, | ||
| "control?": ControlPolicySchema, | ||
| "valueSet?": StorageValueSetRefSchema | ||
| }).narrow((col, ctx) => { | ||
| if (col.typeParams !== void 0 && col.typeRef !== void 0) return ctx.mustBe("a column with either typeParams or typeRef, not both"); | ||
| return true; | ||
| }); | ||
| /** | ||
| * Storage value-set entry under `storage.namespaces[id].entries.valueSet[name]`. | ||
| * Carries a `kind: 'valueSet'` discriminator (enumerable, survives JSON) and an | ||
| * ordered `values` array of codec-encoded permitted values. | ||
| */ | ||
| const StorageValueSetSchema = type({ | ||
| kind: "'valueSet'", | ||
| values: type("string | number | boolean | null | unknown[] | Record<string, unknown>").array().readonly() | ||
| }); | ||
| const PrimaryKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| const UniqueConstraintSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| const IndexSchema = type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string", | ||
| "type?": "string", | ||
| "options?": "Record<string, unknown>" | ||
| }); | ||
| const ForeignKeyReferenceSchema = type({ | ||
| "+": "reject", | ||
| namespaceId: "string", | ||
| tableName: "string", | ||
| columns: type.string.array().readonly(), | ||
| "spaceId?": "string" | ||
| }); | ||
| const ForeignKeySourceSchema = type({ | ||
| "+": "reject", | ||
| namespaceId: "string", | ||
| tableName: "string", | ||
| columns: type.string.array().readonly() | ||
| }); | ||
| const ReferentialActionSchema = type.declare().type("'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'"); | ||
| const ForeignKeySchema = type.declare().type({ | ||
| source: ForeignKeySourceSchema, | ||
| target: ForeignKeyReferenceSchema, | ||
| "name?": "string", | ||
| "onDelete?": ReferentialActionSchema, | ||
| "onUpdate?": ReferentialActionSchema, | ||
| constraint: "boolean", | ||
| index: "boolean" | ||
| }); | ||
| const CheckConstraintSchema = type({ | ||
| "+": "reject", | ||
| name: "string", | ||
| column: "string", | ||
| valueSet: StorageValueSetRefSchema | ||
| }); | ||
| const StorageTableSchema = type({ | ||
| "+": "reject", | ||
| columns: type({ "[string]": StorageColumnSchema }), | ||
| "primaryKey?": PrimaryKeySchema, | ||
| uniques: UniqueConstraintSchema.array().readonly(), | ||
| indexes: IndexSchema.array().readonly(), | ||
| foreignKeys: ForeignKeySchema.array().readonly(), | ||
| "control?": ControlPolicySchema, | ||
| "checks?": CheckConstraintSchema.array().readonly() | ||
| }); | ||
| //#endregion | ||
| //#region src/ir/sql-node.ts | ||
| /** | ||
| * SQL family IR node base. Carries the family-level `kind` discriminator | ||
| * `'sql'` and inherits the framework's `freezeNode` affordance. | ||
| * | ||
| * Single family-level discriminator (not per-leaf) reflects the fact that | ||
| * SQL IR has no polymorphic dispatch today — verifiers and serializers | ||
| * walk by structural position (`storage.tables[name].columns[name]`), | ||
| * not by inspecting `kind`. The abstract bar for per-leaf discriminators | ||
| * isn't earned until a future polymorphic consumer arrives. | ||
| * | ||
| * `kind` is installed as a non-enumerable own property on every instance, | ||
| * which keeps three things clean simultaneously: | ||
| * | ||
| * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope | ||
| * shape (no `kind` field), so emitted contract.json files and the | ||
| * `validateSqlContractFully` arktype schemas stay unchanged. | ||
| * - Test assertions that use `toEqual({...})` against the pre-lift flat | ||
| * shape continue to pass — only enumerable own properties are | ||
| * compared. | ||
| * - Direct access (`node.kind`) and runtime narrowing | ||
| * (`if (node.kind === 'sql')`) still work, so future polymorphic | ||
| * dispatch can begin reading `kind` without a runtime change. | ||
| * | ||
| * Future per-leaf overrides land cleanly: a class that gains a | ||
| * polymorphic-dispatch consumer (e.g. an enum type instance walked | ||
| * alongside other types) overrides `kind` with its narrower literal | ||
| * at that leaf level. Per-leaf overrides will use enumerable kind | ||
| * (matching the Mongo per-class-discriminator precedent) because they | ||
| * encode dispatch-relevant information that callers need to see in | ||
| * JSON envelopes; the family-level `'sql'` is uniform across all SQL | ||
| * IR and carries no dispatch-relevant information. | ||
| */ | ||
| var SqlNode = class extends IRNodeBase { | ||
| kind; | ||
| constructor() { | ||
| super(); | ||
| Object.defineProperty(this, "kind", { | ||
| value: "sql", | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/check-constraint.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level check constraint that restricts | ||
| * a column to the permitted values of a value-set. | ||
| * | ||
| * The constraint is **structured** (names a column and a value-set | ||
| * reference), not a raw SQL expression. Each target renders its own DDL | ||
| * from the structured form, keeping the contract target-agnostic. | ||
| * | ||
| * Construction is idempotent: passing an existing `CheckConstraint` | ||
| * instance as input produces a new instance with identical fields. | ||
| * The constructor does not use `instanceof` for input discrimination — | ||
| * it reads plain named properties, which is sufficient since | ||
| * `CheckConstraintInput` is a structural type. | ||
| */ | ||
| var CheckConstraint = class extends SqlNode { | ||
| name; | ||
| column; | ||
| valueSet; | ||
| constructor(input) { | ||
| super(); | ||
| this.name = input.name; | ||
| this.column = input.column; | ||
| this.valueSet = input.valueSet; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/foreign-key-reference.ts | ||
| /** | ||
| * SQL Contract IR node for one side (source or target) of a foreign-key | ||
| * declaration. Carries the full coordinate: namespace, table, and columns. | ||
| * | ||
| * Cross-space discrimination is based on `spaceId` presence: absent means | ||
| * local (same contract-space); present means cross-space (the referenced | ||
| * table lives in the contract-space identified by `spaceId`). | ||
| * | ||
| * For local references `spaceId` is absent from JSON, keeping the serialized | ||
| * shape byte-identical to contracts authored before cross-space support was | ||
| * added. For cross-space references `spaceId` appears in JSON so round-trips | ||
| * are lossless. | ||
| * | ||
| * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir` | ||
| * as the sentinel `namespaceId` for single-namespace (unbound) references. | ||
| */ | ||
| var ForeignKeyReference = class extends SqlNode { | ||
| namespaceId; | ||
| tableName; | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.namespaceId = asNamespaceId(input.namespaceId); | ||
| this.tableName = input.tableName; | ||
| this.columns = input.columns; | ||
| if (input.spaceId !== void 0) this.spaceId = input.spaceId; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/foreign-key.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level foreign-key declaration. | ||
| * | ||
| * Each FK carries explicit `source` and `target` {@link ForeignKeyReference} | ||
| * coordinates (namespace, table, columns). For single-namespace contracts the | ||
| * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides. | ||
| * | ||
| * The nested references are normalised to {@link ForeignKeyReference} | ||
| * instances inside the constructor so downstream walks see a uniform AST | ||
| * regardless of whether the input was a JSON literal or an already-constructed | ||
| * class instance. | ||
| */ | ||
| var ForeignKey = class extends SqlNode { | ||
| source; | ||
| target; | ||
| constraint; | ||
| index; | ||
| constructor(input) { | ||
| super(); | ||
| this.source = input.source instanceof ForeignKeyReference ? input.source : new ForeignKeyReference(input.source); | ||
| this.target = input.target instanceof ForeignKeyReference ? input.target : new ForeignKeyReference(input.target); | ||
| this.constraint = input.constraint; | ||
| this.index = input.index; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| if (input.onDelete !== void 0) this.onDelete = input.onDelete; | ||
| if (input.onUpdate !== void 0) this.onUpdate = input.onUpdate; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/primary-key.ts | ||
| /** | ||
| * SQL Contract IR node for a table's primary-key constraint. | ||
| */ | ||
| var PrimaryKey = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/sql-index.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level secondary index. | ||
| * | ||
| * Note that this class shadows the global TypeScript `Index` lib type | ||
| * at the family-shared name; consumer files that need both should | ||
| * alias one (e.g. | ||
| * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`). | ||
| */ | ||
| var Index = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| if (input.type !== void 0) this.type = input.type; | ||
| if (input.options !== void 0) this.options = input.options; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/storage-column.ts | ||
| /** | ||
| * SQL Contract IR node for a single column entry in `StorageTable.columns`. | ||
| * | ||
| * Single concrete family-shared class — every SQL target reads the | ||
| * same column shape today, so there is no per-target subclass. The | ||
| * class type accepts any caller that constructs via | ||
| * `new StorageColumn(input)`; literal construction sites must pass | ||
| * through the constructor or the family-base hydration walker. | ||
| * | ||
| * The column's `name` is not on the class — columns are keyed by name | ||
| * in the parent `StorageTable.columns: Record<string, StorageColumn>` | ||
| * map, so a `name` field would be redundant with the key. | ||
| */ | ||
| var StorageColumn = class extends SqlNode { | ||
| nativeType; | ||
| codecId; | ||
| nullable; | ||
| constructor(input) { | ||
| super(); | ||
| this.nativeType = input.nativeType; | ||
| this.codecId = input.codecId; | ||
| this.nullable = input.nullable; | ||
| if (input.typeParams !== void 0) this.typeParams = input.typeParams; | ||
| if (input.typeRef !== void 0) this.typeRef = input.typeRef; | ||
| if (input.default !== void 0) this.default = input.default; | ||
| if (input.control !== void 0) this.control = input.control; | ||
| if (input.valueSet !== void 0) this.valueSet = input.valueSet; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/unique-constraint.ts | ||
| /** | ||
| * SQL Contract IR node for a table-level unique constraint. | ||
| */ | ||
| var UniqueConstraint = class extends SqlNode { | ||
| columns; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = input.columns; | ||
| if (input.name !== void 0) this.name = input.name; | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/storage-table.ts | ||
| /** | ||
| * SQL Contract IR node for a single table entry in a namespace's | ||
| * `tables` map. | ||
| * | ||
| * The constructor normalises nested IR-class fields (columns, primary | ||
| * key, uniques, indexes, foreign keys) into the appropriate class | ||
| * instances so downstream walks see a uniform AST regardless of whether | ||
| * the input was a JSON literal or an already-constructed class. | ||
| * | ||
| * The table's `name` is not on the class — tables are keyed by name in | ||
| * the parent namespace's `tables: Record<string, StorageTable>` map. | ||
| */ | ||
| var StorageTable = class extends SqlNode { | ||
| columns; | ||
| uniques; | ||
| indexes; | ||
| foreignKeys; | ||
| constructor(input) { | ||
| super(); | ||
| this.columns = Object.freeze(Object.fromEntries(Object.entries(input.columns).map(([name, col]) => [name, col instanceof StorageColumn ? col : new StorageColumn(col)]))); | ||
| if (input.primaryKey !== void 0) this.primaryKey = input.primaryKey instanceof PrimaryKey ? input.primaryKey : new PrimaryKey(input.primaryKey); | ||
| this.uniques = Object.freeze(input.uniques.map((u) => u instanceof UniqueConstraint ? u : new UniqueConstraint(u))); | ||
| this.indexes = Object.freeze(input.indexes.map((i) => i instanceof Index ? i : new Index(i))); | ||
| this.foreignKeys = Object.freeze(input.foreignKeys.map((fk) => fk instanceof ForeignKey ? fk : new ForeignKey(fk))); | ||
| if (input.control !== void 0) this.control = input.control; | ||
| if (input.checks !== void 0 && input.checks.length > 0) this.checks = Object.freeze(input.checks.map((cc) => new CheckConstraint(cc))); | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/storage-value-set.ts | ||
| /** | ||
| * SQL Contract IR node for a value-set entry in a namespace's `valueSet` | ||
| * map (`SqlNamespace.entries.valueSet`). | ||
| * | ||
| * A value-set records the ordered set of permitted codec-encoded values for | ||
| * an enum-like column restriction. It does not carry a `codecId` — the | ||
| * column that references it already holds the codec; the value-set holds | ||
| * only the permitted values. | ||
| * | ||
| * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope | ||
| * carries the discriminator and the serializer hydration walker can | ||
| * dispatch on it. This follows the per-leaf enumerable-kind convention | ||
| * established in the SQL-node comment (future polymorphic dispatch on | ||
| * namespace entries needs the discriminator in JSON). | ||
| * | ||
| * The entry's name is not on the class — value-sets are keyed by name in | ||
| * the parent namespace's `valueSet: Record<string, StorageValueSet>` map. | ||
| */ | ||
| var StorageValueSet = class extends SqlNode { | ||
| kind = "valueSet"; | ||
| values; | ||
| constructor(input) { | ||
| super(); | ||
| this.values = Object.freeze([...input.values]); | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/entity-kinds.ts | ||
| const tableEntityKind = { | ||
| kind: "table", | ||
| schema: StorageTableSchema, | ||
| construct: (input) => new StorageTable(input) | ||
| }; | ||
| const valueSetEntityKind = { | ||
| kind: "valueSet", | ||
| schema: StorageValueSetSchema, | ||
| construct: (input) => new StorageValueSet(input) | ||
| }; | ||
| /** | ||
| * Assembles the `kind → descriptor` registry for SQL namespaces: the built-in | ||
| * `table` and `valueSet` kinds plus any target `packKinds`. This builds the | ||
| * lookup table — it does not touch contract data. `hydrateNamespaceEntities` | ||
| * later consumes this registry to turn a namespace's raw entries into IR | ||
| * instances, and `createSqlContractSchema` derives validation from the same | ||
| * registry. Throws on a duplicate kind. | ||
| */ | ||
| function composeSqlEntityKinds(packKinds = []) { | ||
| const kinds = new Map([["table", tableEntityKind], ["valueSet", valueSetEntityKind]]); | ||
| for (const descriptor of packKinds) { | ||
| if (kinds.has(descriptor.kind)) throw new Error(`composeSqlEntityKinds: duplicate entity kind "${descriptor.kind}" — each kind may be registered only once`); | ||
| kinds.set(descriptor.kind, descriptor); | ||
| } | ||
| return kinds; | ||
| } | ||
| //#endregion | ||
| export { StorageTableSchema as C, ReferentialActionSchema as S, ColumnDefaultSchema as _, StorageTable as a, ForeignKeySourceSchema as b, Index as c, ForeignKeyReference as d, CheckConstraint as f, ColumnDefaultLiteralSchema as g, ColumnDefaultFunctionSchema as h, StorageValueSet as i, PrimaryKey as l, CheckConstraintSchema as m, tableEntityKind as n, UniqueConstraint as o, SqlNode as p, valueSetEntityKind as r, StorageColumn as s, composeSqlEntityKinds as t, ForeignKey as u, ForeignKeyReferenceSchema as v, StorageValueSetSchema as w, IndexSchema as x, ForeignKeySchema as y }; | ||
| //# sourceMappingURL=entity-kinds-Cl36zL5j.mjs.map |
| {"version":3,"file":"entity-kinds-Cl36zL5j.mjs","names":[],"sources":["../src/ir/storage-entry-schemas.ts","../src/ir/sql-node.ts","../src/ir/check-constraint.ts","../src/ir/foreign-key-reference.ts","../src/ir/foreign-key.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts","../src/ir/storage-value-set.ts","../src/entity-kinds.ts"],"sourcesContent":["import { type Type, type } from 'arktype';\nimport type { ForeignKeyInput, ReferentialAction } from './foreign-key';\nimport type { ForeignKeyReferenceInput } from './foreign-key-reference';\nimport type { PrimaryKeyInput } from './primary-key';\nimport type { UniqueConstraintInput } from './unique-constraint';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\n\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst ControlPolicySchema = type(\"'managed' | 'tolerated' | 'external' | 'observed'\");\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst StorageValueSetRefSchema = type({\n plane: \"'storage'\",\n namespaceId: 'string',\n entityKind: \"'valueSet'\",\n entityName: 'string',\n 'spaceId?': 'string',\n});\n\nconst StorageColumnSchema = type({\n '+': 'reject',\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n 'control?': ControlPolicySchema,\n 'valueSet?': StorageValueSetRefSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\n});\n\n/**\n * Storage value-set entry under `storage.namespaces[id].entries.valueSet[name]`.\n * Carries a `kind: 'valueSet'` discriminator (enumerable, survives JSON) and an\n * ordered `values` array of codec-encoded permitted values.\n */\nexport const StorageValueSetSchema = type({\n kind: \"'valueSet'\",\n values: type('string | number | boolean | null | unknown[] | Record<string, unknown>')\n .array()\n .readonly(),\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKeyInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraintInput>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nexport const IndexSchema = type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n 'type?': 'string',\n 'options?': 'Record<string, unknown>',\n});\n\nexport const ForeignKeyReferenceSchema = type({\n '+': 'reject',\n namespaceId: 'string',\n tableName: 'string',\n columns: type.string.array().readonly(),\n 'spaceId?': 'string',\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ForeignKeySourceSchema = type({\n '+': 'reject',\n namespaceId: 'string',\n tableName: 'string',\n columns: type.string.array().readonly(),\n}) satisfies Type<ForeignKeyReferenceInput>;\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKeyInput>().type({\n source: ForeignKeySourceSchema,\n target: ForeignKeyReferenceSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nexport const CheckConstraintSchema = type({\n '+': 'reject',\n name: 'string',\n column: 'string',\n valueSet: StorageValueSetRefSchema,\n});\n\nexport const StorageTableSchema = type({\n '+': 'reject',\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n 'control?': ControlPolicySchema,\n 'checks?': CheckConstraintSchema.array().readonly(),\n});\n","import { IRNodeBase } from '@prisma-next/framework-components/ir';\n\n/**\n * SQL family IR node base. Carries the family-level `kind` discriminator\n * `'sql'` and inherits the framework's `freezeNode` affordance.\n *\n * Single family-level discriminator (not per-leaf) reflects the fact that\n * SQL IR has no polymorphic dispatch today — verifiers and serializers\n * walk by structural position (`storage.tables[name].columns[name]`),\n * not by inspecting `kind`. The abstract bar for per-leaf discriminators\n * isn't earned until a future polymorphic consumer arrives.\n *\n * `kind` is installed as a non-enumerable own property on every instance,\n * which keeps three things clean simultaneously:\n *\n * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope\n * shape (no `kind` field), so emitted contract.json files and the\n * `validateSqlContractFully` arktype schemas stay unchanged.\n * - Test assertions that use `toEqual({...})` against the pre-lift flat\n * shape continue to pass — only enumerable own properties are\n * compared.\n * - Direct access (`node.kind`) and runtime narrowing\n * (`if (node.kind === 'sql')`) still work, so future polymorphic\n * dispatch can begin reading `kind` without a runtime change.\n *\n * Future per-leaf overrides land cleanly: a class that gains a\n * polymorphic-dispatch consumer (e.g. an enum type instance walked\n * alongside other types) overrides `kind` with its narrower literal\n * at that leaf level. Per-leaf overrides will use enumerable kind\n * (matching the Mongo per-class-discriminator precedent) because they\n * encode dispatch-relevant information that callers need to see in\n * JSON envelopes; the family-level `'sql'` is uniform across all SQL\n * IR and carries no dispatch-relevant information.\n */\nexport abstract class SqlNode extends IRNodeBase {\n readonly kind?: string;\n\n constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql',\n writable: false,\n enumerable: false,\n // configurable so per-leaf subclasses (e.g. StorageValueSet)\n // can override `kind` with their narrower\n // enumerable literal via a class-field initializer. SqlNode\n // itself never needs to mutate the property again, so\n // configurability has no surface impact at this layer.\n configurable: true,\n });\n }\n}\n","import type { ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link CheckConstraint}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface CheckConstraintInput {\n readonly name: string;\n readonly column: string;\n readonly valueSet: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a table-level check constraint that restricts\n * a column to the permitted values of a value-set.\n *\n * The constraint is **structured** (names a column and a value-set\n * reference), not a raw SQL expression. Each target renders its own DDL\n * from the structured form, keeping the contract target-agnostic.\n *\n * Construction is idempotent: passing an existing `CheckConstraint`\n * instance as input produces a new instance with identical fields.\n * The constructor does not use `instanceof` for input discrimination —\n * it reads plain named properties, which is sufficient since\n * `CheckConstraintInput` is a structural type.\n */\nexport class CheckConstraint extends SqlNode {\n readonly name: string;\n readonly column: string;\n readonly valueSet: ValueSetRef;\n\n constructor(input: CheckConstraintInput) {\n super();\n this.name = input.name;\n this.column = input.column;\n this.valueSet = input.valueSet;\n freezeNode(this);\n }\n}\n","import { asNamespaceId, type NamespaceId } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Input for a foreign-key reference (one side of a foreign-key declaration).\n *\n * When `spaceId` is absent the reference is local — the referenced table lives\n * in the same contract-space. When `spaceId` is present the reference is\n * cross-space — the referenced table lives in a different contract-space\n * identified by `spaceId`.\n *\n * Presence-based discrimination keeps local FK JSON byte-identical to\n * contracts authored before cross-space support was added.\n */\nexport interface ForeignKeyReferenceInput {\n readonly namespaceId: string;\n readonly tableName: string;\n readonly columns: readonly string[];\n readonly spaceId?: string;\n}\n\n/**\n * SQL Contract IR node for one side (source or target) of a foreign-key\n * declaration. Carries the full coordinate: namespace, table, and columns.\n *\n * Cross-space discrimination is based on `spaceId` presence: absent means\n * local (same contract-space); present means cross-space (the referenced\n * table lives in the contract-space identified by `spaceId`).\n *\n * For local references `spaceId` is absent from JSON, keeping the serialized\n * shape byte-identical to contracts authored before cross-space support was\n * added. For cross-space references `spaceId` appears in JSON so round-trips\n * are lossless.\n *\n * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir`\n * as the sentinel `namespaceId` for single-namespace (unbound) references.\n */\nexport class ForeignKeyReference extends SqlNode {\n readonly namespaceId: NamespaceId;\n readonly tableName: string;\n readonly columns: readonly string[];\n declare readonly spaceId?: string;\n\n constructor(input: ForeignKeyReferenceInput) {\n super();\n this.namespaceId = asNamespaceId(input.namespaceId);\n this.tableName = input.tableName;\n this.columns = input.columns;\n if (input.spaceId !== undefined) this.spaceId = input.spaceId;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { ForeignKeyReference, type ForeignKeyReferenceInput } from './foreign-key-reference';\nimport { SqlNode } from './sql-node';\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport interface ForeignKeyInput {\n readonly source: ForeignKeyReference | ForeignKeyReferenceInput;\n readonly target: ForeignKeyReference | ForeignKeyReferenceInput;\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n}\n\n/**\n * SQL Contract IR node for a table-level foreign-key declaration.\n *\n * Each FK carries explicit `source` and `target` {@link ForeignKeyReference}\n * coordinates (namespace, table, columns). For single-namespace contracts the\n * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides.\n *\n * The nested references are normalised to {@link ForeignKeyReference}\n * instances inside the constructor so downstream walks see a uniform AST\n * regardless of whether the input was a JSON literal or an already-constructed\n * class instance.\n */\nexport class ForeignKey extends SqlNode {\n readonly source: ForeignKeyReference;\n readonly target: ForeignKeyReference;\n readonly constraint: boolean;\n readonly index: boolean;\n declare readonly name?: string;\n declare readonly onDelete?: ReferentialAction;\n declare readonly onUpdate?: ReferentialAction;\n\n constructor(input: ForeignKeyInput) {\n super();\n this.source =\n input.source instanceof ForeignKeyReference\n ? input.source\n : new ForeignKeyReference(input.source);\n this.target =\n input.target instanceof ForeignKeyReference\n ? input.target\n : new ForeignKeyReference(input.target);\n this.constraint = input.constraint;\n this.index = input.index;\n if (input.name !== undefined) this.name = input.name;\n if (input.onDelete !== undefined) this.onDelete = input.onDelete;\n if (input.onUpdate !== undefined) this.onUpdate = input.onUpdate;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface PrimaryKeyInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table's primary-key constraint.\n */\nexport class PrimaryKey extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: PrimaryKeyInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface IndexInput {\n readonly columns: readonly string[];\n readonly name?: string;\n readonly type?: string;\n readonly options?: Record<string, unknown>;\n}\n\n/**\n * SQL Contract IR node for a table-level secondary index.\n *\n * Note that this class shadows the global TypeScript `Index` lib type\n * at the family-shared name; consumer files that need both should\n * alias one (e.g.\n * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`).\n */\nexport class Index extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n declare readonly type?: string;\n declare readonly options?: Record<string, unknown>;\n\n constructor(input: IndexInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n if (input.type !== undefined) this.type = input.type;\n if (input.options !== undefined) this.options = input.options;\n freezeNode(this);\n }\n}\n","import type { ColumnDefault, ControlPolicy, ValueSetRef } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageColumn}. Mirrors\n * the on-disk storage JSON envelope exactly so the family-base\n * serializer's hydration walker can hand an arktype-validated literal\n * straight to `new`.\n *\n * `typeParams` and `typeRef` remain mutually exclusive (one or the\n * other, not both); the constructor preserves whichever caller-side\n * choice the input encodes.\n */\nexport interface StorageColumnInput {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n readonly typeParams?: Record<string, unknown>;\n readonly typeRef?: string;\n readonly default?: ColumnDefault;\n readonly control?: ControlPolicy;\n readonly valueSet?: ValueSetRef;\n}\n\n/**\n * SQL Contract IR node for a single column entry in `StorageTable.columns`.\n *\n * Single concrete family-shared class — every SQL target reads the\n * same column shape today, so there is no per-target subclass. The\n * class type accepts any caller that constructs via\n * `new StorageColumn(input)`; literal construction sites must pass\n * through the constructor or the family-base hydration walker.\n *\n * The column's `name` is not on the class — columns are keyed by name\n * in the parent `StorageTable.columns: Record<string, StorageColumn>`\n * map, so a `name` field would be redundant with the key.\n */\nexport class StorageColumn extends SqlNode {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n declare readonly typeParams?: Record<string, unknown>;\n declare readonly typeRef?: string;\n declare readonly default?: ColumnDefault;\n declare readonly control?: ControlPolicy;\n declare readonly valueSet?: ValueSetRef;\n\n constructor(input: StorageColumnInput) {\n super();\n this.nativeType = input.nativeType;\n this.codecId = input.codecId;\n this.nullable = input.nullable;\n if (input.typeParams !== undefined) this.typeParams = input.typeParams;\n if (input.typeRef !== undefined) this.typeRef = input.typeRef;\n if (input.default !== undefined) this.default = input.default;\n if (input.control !== undefined) this.control = input.control;\n if (input.valueSet !== undefined) this.valueSet = input.valueSet;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\nexport interface UniqueConstraintInput {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\n/**\n * SQL Contract IR node for a table-level unique constraint.\n */\nexport class UniqueConstraint extends SqlNode {\n readonly columns: readonly string[];\n declare readonly name?: string;\n\n constructor(input: UniqueConstraintInput) {\n super();\n this.columns = input.columns;\n if (input.name !== undefined) this.name = input.name;\n freezeNode(this);\n }\n}\n","import type { ControlPolicy } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { CheckConstraint, type CheckConstraintInput } from './check-constraint';\nimport { ForeignKey, type ForeignKeyInput } from './foreign-key';\nimport { PrimaryKey, type PrimaryKeyInput } from './primary-key';\nimport { Index, type IndexInput } from './sql-index';\nimport { SqlNode } from './sql-node';\nimport { StorageColumn, type StorageColumnInput } from './storage-column';\nimport { UniqueConstraint, type UniqueConstraintInput } from './unique-constraint';\n\nexport interface StorageTableInput {\n readonly columns: Record<string, StorageColumn | StorageColumnInput>;\n readonly primaryKey?: PrimaryKey | PrimaryKeyInput;\n readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>;\n readonly indexes: ReadonlyArray<Index | IndexInput>;\n readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>;\n readonly control?: ControlPolicy;\n readonly checks?: ReadonlyArray<CheckConstraint | CheckConstraintInput>;\n}\n\n/**\n * SQL Contract IR node for a single table entry in a namespace's\n * `tables` map.\n *\n * The constructor normalises nested IR-class fields (columns, primary\n * key, uniques, indexes, foreign keys) into the appropriate class\n * instances so downstream walks see a uniform AST regardless of whether\n * the input was a JSON literal or an already-constructed class.\n *\n * The table's `name` is not on the class — tables are keyed by name in\n * the parent namespace's `tables: Record<string, StorageTable>` map.\n */\nexport class StorageTable extends SqlNode {\n readonly columns: Readonly<Record<string, StorageColumn>>;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n declare readonly primaryKey?: PrimaryKey;\n declare readonly control?: ControlPolicy;\n declare readonly checks?: ReadonlyArray<CheckConstraint>;\n\n constructor(input: StorageTableInput) {\n super();\n this.columns = Object.freeze(\n Object.fromEntries(\n Object.entries(input.columns).map(([name, col]) => [\n name,\n col instanceof StorageColumn ? col : new StorageColumn(col),\n ]),\n ),\n );\n if (input.primaryKey !== undefined) {\n this.primaryKey =\n input.primaryKey instanceof PrimaryKey\n ? input.primaryKey\n : new PrimaryKey(input.primaryKey);\n }\n this.uniques = Object.freeze(\n input.uniques.map((u) => (u instanceof UniqueConstraint ? u : new UniqueConstraint(u))),\n );\n this.indexes = Object.freeze(input.indexes.map((i) => (i instanceof Index ? i : new Index(i))));\n this.foreignKeys = Object.freeze(\n input.foreignKeys.map((fk) => (fk instanceof ForeignKey ? fk : new ForeignKey(fk))),\n );\n if (input.control !== undefined) this.control = input.control;\n if (input.checks !== undefined && input.checks.length > 0) {\n this.checks = Object.freeze(input.checks.map((cc) => new CheckConstraint(cc)));\n }\n freezeNode(this);\n }\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from './sql-node';\n\n/**\n * Hydration / construction input shape for {@link StorageValueSet}.\n * Mirrors the on-disk storage JSON envelope so the serializer hydration\n * walker can hand a validated literal straight to `new`.\n */\nexport interface StorageValueSetInput {\n readonly kind: 'valueSet';\n /** Ordered permitted values, codec-encoded. Declaration order is preserved. */\n readonly values: readonly JsonValue[];\n}\n\n/**\n * SQL Contract IR node for a value-set entry in a namespace's `valueSet`\n * map (`SqlNamespace.entries.valueSet`).\n *\n * A value-set records the ordered set of permitted codec-encoded values for\n * an enum-like column restriction. It does not carry a `codecId` — the\n * column that references it already holds the codec; the value-set holds\n * only the permitted values.\n *\n * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope\n * carries the discriminator and the serializer hydration walker can\n * dispatch on it. This follows the per-leaf enumerable-kind convention\n * established in the SQL-node comment (future polymorphic dispatch on\n * namespace entries needs the discriminator in JSON).\n *\n * The entry's name is not on the class — value-sets are keyed by name in\n * the parent namespace's `valueSet: Record<string, StorageValueSet>` map.\n */\nexport class StorageValueSet extends SqlNode {\n override readonly kind = 'valueSet' as const;\n readonly values: readonly JsonValue[];\n\n constructor(input: StorageValueSetInput) {\n super();\n this.values = Object.freeze([...input.values]);\n freezeNode(this);\n }\n}\n","import type {\n AnyEntityKindDescriptor,\n EntityKindDescriptor,\n} from '@prisma-next/framework-components/ir';\nimport { StorageTableSchema, StorageValueSetSchema } from './ir/storage-entry-schemas';\nimport { StorageTable, type StorageTableInput } from './ir/storage-table';\nimport { StorageValueSet, type StorageValueSetInput } from './ir/storage-value-set';\n\nexport const tableEntityKind: EntityKindDescriptor<StorageTableInput, StorageTable> = {\n kind: 'table',\n schema: StorageTableSchema,\n construct: (input) => new StorageTable(input),\n};\n\nexport const valueSetEntityKind: EntityKindDescriptor<StorageValueSetInput, StorageValueSet> = {\n kind: 'valueSet',\n schema: StorageValueSetSchema,\n construct: (input) => new StorageValueSet(input),\n};\n\n/**\n * Assembles the `kind → descriptor` registry for SQL namespaces: the built-in\n * `table` and `valueSet` kinds plus any target `packKinds`. This builds the\n * lookup table — it does not touch contract data. `hydrateNamespaceEntities`\n * later consumes this registry to turn a namespace's raw entries into IR\n * instances, and `createSqlContractSchema` derives validation from the same\n * registry. Throws on a duplicate kind.\n */\nexport function composeSqlEntityKinds(\n packKinds: readonly AnyEntityKindDescriptor[] = [],\n): ReadonlyMap<string, AnyEntityKindDescriptor> {\n const kinds = new Map<string, AnyEntityKindDescriptor>([\n ['table', tableEntityKind],\n ['valueSet', valueSetEntityKind],\n ]);\n for (const descriptor of packKinds) {\n if (kinds.has(descriptor.kind)) {\n throw new Error(\n `composeSqlEntityKinds: duplicate entity kind \"${descriptor.kind}\" — each kind may be registered only once`,\n );\n }\n kinds.set(descriptor.kind, descriptor);\n }\n return kinds;\n}\n"],"mappings":";;;;AAYA,MAAM,oBAAoB,KAAK,WAAW;AAC1C,MAAM,qBAAqB,KAAK,YAAY;AAC5C,MAAM,sBAAsB,KAAK,mDAAmD;AAEpF,MAAa,6BAA6B,KAAK,QAA8B,CAAC,CAAC,KAAK;CAClF,MAAM;CACN,OAAO;AACT,CAAC;AAED,MAAa,8BAA8B,KAAK,QAA+B,CAAC,C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,OAAO,IAAI,gBAAgB,EAAE,CAAC,CAAC;EAE/E,WAAW,IAAI;CACjB;AACF;;;;;;;;;;;;;;;;;;;;;ACrCA,IAAa,kBAAb,cAAqC,QAAQ;CAC3C,OAAyB;CACzB;CAEA,YAAY,OAA6B;EACvC,MAAM;EACN,KAAK,SAAS,OAAO,OAAO,CAAC,GAAG,MAAM,MAAM,CAAC;EAC7C,WAAW,IAAI;CACjB;AACF;;;AClCA,MAAa,kBAAyE;CACpF,MAAM;CACN,QAAQ;CACR,YAAY,UAAU,IAAI,aAAa,KAAK;AAC9C;AAEA,MAAa,qBAAkF;CAC7F,MAAM;CACN,QAAQ;CACR,YAAY,UAAU,IAAI,gBAAgB,KAAK;AACjD;;;;;;;;;AAUA,SAAgB,sBACd,YAAgD,CAAC,GACH;CAC9C,MAAM,QAAQ,IAAI,IAAqC,CACrD,CAAC,SAAS,eAAe,GACzB,CAAC,YAAY,kBAAkB,CACjC,CAAC;CACD,KAAK,MAAM,cAAc,WAAW;EAClC,IAAI,MAAM,IAAI,WAAW,IAAI,GAC3B,MAAM,IAAI,MACR,iDAAiD,WAAW,KAAK,0CACnE;EAEF,MAAM,IAAI,WAAW,MAAM,UAAU;CACvC;CACA,OAAO;AACT"} |
| import { IRNodeBase } from "@prisma-next/framework-components/ir"; | ||
| import { NamespaceId } from "@prisma-next/contract/types"; | ||
| //#region src/ir/sql-node.d.ts | ||
| /** | ||
| * SQL family IR node base. Carries the family-level `kind` discriminator | ||
| * `'sql'` and inherits the framework's `freezeNode` affordance. | ||
| * | ||
| * Single family-level discriminator (not per-leaf) reflects the fact that | ||
| * SQL IR has no polymorphic dispatch today — verifiers and serializers | ||
| * walk by structural position (`storage.tables[name].columns[name]`), | ||
| * not by inspecting `kind`. The abstract bar for per-leaf discriminators | ||
| * isn't earned until a future polymorphic consumer arrives. | ||
| * | ||
| * `kind` is installed as a non-enumerable own property on every instance, | ||
| * which keeps three things clean simultaneously: | ||
| * | ||
| * - `JSON.stringify(node)` produces the canonical pre-lift JSON envelope | ||
| * shape (no `kind` field), so emitted contract.json files and the | ||
| * `validateSqlContractFully` arktype schemas stay unchanged. | ||
| * - Test assertions that use `toEqual({...})` against the pre-lift flat | ||
| * shape continue to pass — only enumerable own properties are | ||
| * compared. | ||
| * - Direct access (`node.kind`) and runtime narrowing | ||
| * (`if (node.kind === 'sql')`) still work, so future polymorphic | ||
| * dispatch can begin reading `kind` without a runtime change. | ||
| * | ||
| * Future per-leaf overrides land cleanly: a class that gains a | ||
| * polymorphic-dispatch consumer (e.g. an enum type instance walked | ||
| * alongside other types) overrides `kind` with its narrower literal | ||
| * at that leaf level. Per-leaf overrides will use enumerable kind | ||
| * (matching the Mongo per-class-discriminator precedent) because they | ||
| * encode dispatch-relevant information that callers need to see in | ||
| * JSON envelopes; the family-level `'sql'` is uniform across all SQL | ||
| * IR and carries no dispatch-relevant information. | ||
| */ | ||
| declare abstract class SqlNode extends IRNodeBase { | ||
| readonly kind?: string; | ||
| constructor(); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/foreign-key-reference.d.ts | ||
| /** | ||
| * Input for a foreign-key reference (one side of a foreign-key declaration). | ||
| * | ||
| * When `spaceId` is absent the reference is local — the referenced table lives | ||
| * in the same contract-space. When `spaceId` is present the reference is | ||
| * cross-space — the referenced table lives in a different contract-space | ||
| * identified by `spaceId`. | ||
| * | ||
| * Presence-based discrimination keeps local FK JSON byte-identical to | ||
| * contracts authored before cross-space support was added. | ||
| */ | ||
| interface ForeignKeyReferenceInput { | ||
| readonly namespaceId: string; | ||
| readonly tableName: string; | ||
| readonly columns: readonly string[]; | ||
| readonly spaceId?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for one side (source or target) of a foreign-key | ||
| * declaration. Carries the full coordinate: namespace, table, and columns. | ||
| * | ||
| * Cross-space discrimination is based on `spaceId` presence: absent means | ||
| * local (same contract-space); present means cross-space (the referenced | ||
| * table lives in the contract-space identified by `spaceId`). | ||
| * | ||
| * For local references `spaceId` is absent from JSON, keeping the serialized | ||
| * shape byte-identical to contracts authored before cross-space support was | ||
| * added. For cross-space references `spaceId` appears in JSON so round-trips | ||
| * are lossless. | ||
| * | ||
| * Use `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir` | ||
| * as the sentinel `namespaceId` for single-namespace (unbound) references. | ||
| */ | ||
| declare class ForeignKeyReference extends SqlNode { | ||
| readonly namespaceId: NamespaceId; | ||
| readonly tableName: string; | ||
| readonly columns: readonly string[]; | ||
| readonly spaceId?: string; | ||
| constructor(input: ForeignKeyReferenceInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/foreign-key.d.ts | ||
| type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'; | ||
| interface ForeignKeyInput { | ||
| readonly source: ForeignKeyReference | ForeignKeyReferenceInput; | ||
| readonly target: ForeignKeyReference | ForeignKeyReferenceInput; | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */ | ||
| readonly constraint: boolean; | ||
| /** Whether to emit a backing index for the FK columns. */ | ||
| readonly index: boolean; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level foreign-key declaration. | ||
| * | ||
| * Each FK carries explicit `source` and `target` {@link ForeignKeyReference} | ||
| * coordinates (namespace, table, columns). For single-namespace contracts the | ||
| * sentinel `UNBOUND_NAMESPACE_ID` appears on both sides. | ||
| * | ||
| * The nested references are normalised to {@link ForeignKeyReference} | ||
| * instances inside the constructor so downstream walks see a uniform AST | ||
| * regardless of whether the input was a JSON literal or an already-constructed | ||
| * class instance. | ||
| */ | ||
| declare class ForeignKey extends SqlNode { | ||
| readonly source: ForeignKeyReference; | ||
| readonly target: ForeignKeyReference; | ||
| readonly constraint: boolean; | ||
| readonly index: boolean; | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| constructor(input: ForeignKeyInput); | ||
| } | ||
| //#endregion | ||
| export { ForeignKeyReferenceInput as a, ForeignKeyReference as i, ForeignKeyInput as n, SqlNode as o, ReferentialAction as r, ForeignKey as t }; | ||
| //# sourceMappingURL=foreign-key-BATxB95l.d.mts.map |
| {"version":3,"file":"foreign-key-BATxB95l.d.mts","names":[],"sources":["../src/ir/sql-node.ts","../src/ir/foreign-key-reference.ts","../src/ir/foreign-key.ts"],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;ACnBA;;;;;;;;;AAIkB;AAmBlB;;;;;;;uBDJsB,OAAA,SAAgB,UAAU;EAAA,SACrC,IAAA;;;;;;;AADX;;;;;;;;;UCnBiB,wBAAA;EAAA,SACN,WAAA;EAAA,SACA,SAAA;EAAA,SACA,OAAA;EAAA,SACA,OAAA;AAAA;;;;;;;AAAO;AAmBlB;;;;;;;;;cAAa,mBAAA,SAA4B,OAAA;EAAA,SAC9B,WAAA,EAAa,WAAA;EAAA,SACb,SAAA;EAAA,SACA,OAAA;EAAA,SACQ,OAAA;cAEL,KAAA,EAAO,wBAAA;AAAA;;;KCxCT,iBAAA;AAAA,UAEK,eAAA;EAAA,SACN,MAAA,EAAQ,mBAAA,GAAsB,wBAAA;EAAA,SAC9B,MAAA,EAAQ,mBAAA,GAAsB,wBAAA;EAAA,SAC9B,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAA;EFwBX;EAAA,SEtBA,UAAA;;WAEA,KAAA;AAAA;;;ADAX;;;;;;;;;AAIkB;cCWL,UAAA,SAAmB,OAAA;EAAA,SACrB,MAAA,EAAQ,mBAAA;EAAA,SACR,MAAA,EAAQ,mBAAA;EAAA,SACR,UAAA;EAAA,SACA,KAAA;EAAA,SACQ,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAA;cAEhB,KAAA,EAAO,eAAA;AAAA"} |
| import { o as SqlNode } from "./foreign-key-BATxB95l.mjs"; | ||
| import { r as StorageTable, t as StorageValueSet } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { Namespace, Storage, StorageType } from "@prisma-next/framework-components/ir"; | ||
| import { StorageHashBase } from "@prisma-next/contract/types"; | ||
| //#region src/ir/storage-type-instance.d.ts | ||
| /** | ||
| * Sentinel kind for the legacy codec-triple shape persisted under | ||
| * `SqlStorage.types`. Plain JSON-clean object literals carry this | ||
| * discriminator so the polymorphic slot dispatch can route them down | ||
| * the codec path while target-specific IR class instances (e.g. the | ||
| * Postgres enum class) keep their own narrower `kind` literal. | ||
| */ | ||
| declare const CODEC_INSTANCE_KIND: "codec-instance"; | ||
| /** | ||
| * Structural sub-interface of {@link StorageType} for codec-typed entries | ||
| * in `SqlStorage.types`. These are plain object literals — there is no | ||
| * runtime IR class, the JSON envelope round-trips through the slot | ||
| * unchanged. The `kind: 'codec-instance'` discriminator is the dispatch | ||
| * key that distinguishes codec-typed entries from any class-instance | ||
| * kinds a target pack contributes to the polymorphic slot. | ||
| */ | ||
| interface StorageTypeInstance extends StorageType { | ||
| readonly kind: typeof CODEC_INSTANCE_KIND; | ||
| readonly codecId: string; | ||
| readonly nativeType: string; | ||
| readonly typeParams: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * Construction-time input for a codec-triple entry. Symmetric with the | ||
| * structural runtime shape minus the `kind` discriminator — callers may | ||
| * omit `kind`; the helper {@link toStorageTypeInstance} stamps it on. | ||
| * `typeParams` may be omitted on input; the constructor normalises a | ||
| * missing value to `{}` so the in-memory shape is always present. | ||
| */ | ||
| interface StorageTypeInstanceInput { | ||
| readonly codecId: string; | ||
| readonly nativeType: string; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * Stamp the codec-instance `kind` discriminator on a caller-supplied | ||
| * codec triple. Idempotent: input that already carries the discriminator | ||
| * passes through unchanged. Missing `typeParams` is normalised to `{}`. | ||
| */ | ||
| declare function toStorageTypeInstance(input: StorageTypeInstanceInput): StorageTypeInstance; | ||
| /** | ||
| * Type-guard for codec-typed entries on the polymorphic | ||
| * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from | ||
| * any class-instance kinds a target pack contributes. | ||
| */ | ||
| declare function isStorageTypeInstance(value: unknown): value is StorageTypeInstance; | ||
| //#endregion | ||
| //#region src/ir/sql-storage.d.ts | ||
| /** | ||
| * Polymorphic value type for document-scoped `SqlStorage.types` entries | ||
| * (codec aliases / parameterised native type registrations). | ||
| * | ||
| * Postgres native enum registrations live under the postgres-specific | ||
| * `entries.type` slot on `PostgresSchema` (target layer), not here. | ||
| */ | ||
| type SqlStorageTypeEntry = StorageTypeInstance | StorageTypeInstanceInput; | ||
| interface SqlNamespaceTablesInput { | ||
| readonly id: string; | ||
| readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>; | ||
| } | ||
| interface SqlStorageInput<THash extends string = string> { | ||
| readonly storageHash: StorageHashBase<THash>; | ||
| readonly types?: Record<string, SqlStorageTypeEntry>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespace>>; | ||
| } | ||
| /** | ||
| * SQL Contract IR root node for the `storage` field. | ||
| * | ||
| * Single concrete family-shared class — both Postgres and SQLite | ||
| * consume this class today. Per-target storage subclasses are | ||
| * introduced when each target's namespace shape earns its | ||
| * target-specific concretion (target-specific derived fields, | ||
| * target-specific storage extensions). | ||
| * | ||
| * Honours the framework `Storage` interface: every SQL IR carries a | ||
| * `namespaces` map keyed by namespace id. Callers must supply fully | ||
| * constructed `Namespace` instances — construction discipline lives | ||
| * in the authoring builders and deserializer hydration paths. | ||
| * | ||
| * The constructor normalises optional `types` into class instances. | ||
| * `types` is polymorphic per Decision 18 Option B: codec-triple inputs | ||
| * are stamped with `kind: 'codec-instance'`; hydration of raw JSON | ||
| * class-instance entries (carrying their narrower `kind` literal) is | ||
| * the per-target serializer's responsibility (so the family base does | ||
| * not import target-specific subclasses). | ||
| */ | ||
| /** | ||
| * The typed `entries` shape for SQL family namespaces. The open dictionary | ||
| * is intersected with optional known-kind maps so that `ns.entries.table` | ||
| * and `ns.entries.valueSet` resolve without a cast, while unknown pack- | ||
| * contributed kinds remain valid (the `Record` part allows any string key). | ||
| */ | ||
| type SqlNamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>> & { | ||
| readonly table?: Readonly<Record<string, StorageTable>>; | ||
| readonly valueSet?: Readonly<Record<string, StorageValueSet>>; | ||
| }; | ||
| /** | ||
| * SQL family namespace. `entries` is the open ADR 224 dictionary — | ||
| * `entries[entityKind][entityName]` addresses any entity. Emitted | ||
| * contract literals satisfy this structurally (no prototype getters | ||
| * needed). For typed access to specific kinds, use the class getters | ||
| * on the concretion or `ns.entries.table` / `ns.entries.valueSet` directly. | ||
| */ | ||
| type SqlNamespace = Namespace & { | ||
| readonly entries: SqlNamespaceEntries; | ||
| /** | ||
| * Render a dialect-qualified table reference for runtime SQL emission. | ||
| * Present on materialised target concretions (`PostgresSchema`, | ||
| * `SqliteDatabase`, …) and family placeholders; omitted on emitted | ||
| * contract structural namespace literals (methods are not serialised). | ||
| */ | ||
| qualifyTable?(tableName: string): string; | ||
| }; | ||
| declare class SqlStorage<THash extends string = string> extends SqlNode implements Storage { | ||
| readonly storageHash: StorageHashBase<THash>; | ||
| readonly namespaces: Readonly<Record<string, SqlNamespace>>; | ||
| readonly types?: Readonly<Record<string, StorageTypeInstance>>; | ||
| constructor(input: SqlStorageInput<THash>); | ||
| } | ||
| //#endregion | ||
| export { SqlStorageInput as a, StorageTypeInstance as c, toStorageTypeInstance as d, SqlStorage as i, StorageTypeInstanceInput as l, SqlNamespaceEntries as n, SqlStorageTypeEntry as o, SqlNamespaceTablesInput as r, CODEC_INSTANCE_KIND as s, SqlNamespace as t, isStorageTypeInstance as u }; | ||
| //# sourceMappingURL=sql-storage-Dga0jwP2.d.mts.map |
| {"version":3,"file":"sql-storage-Dga0jwP2.d.mts","names":[],"sources":["../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts"],"mappings":";;;;;;;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AA;EAAA,SAC7B,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,YAAA;EAAA,SAC5B,KAAA,GAAQ,QAAA,CAAS,MAAA,SAAe,mBAAA;cAErC,KAAA,EAAO,eAAA,CAAgB,KAAA;AAAA"} |
| import { n as ForeignKeyInput, o as SqlNode, t as ForeignKey } from "./foreign-key-BATxB95l.mjs"; | ||
| import { ColumnDefault, ControlPolicy, JsonValue, ValueSetRef } from "@prisma-next/contract/types"; | ||
| //#region src/ir/check-constraint.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link CheckConstraint}. | ||
| * Mirrors the on-disk storage JSON envelope so the serializer hydration | ||
| * walker can hand a validated literal straight to `new`. | ||
| */ | ||
| interface CheckConstraintInput { | ||
| readonly name: string; | ||
| readonly column: string; | ||
| readonly valueSet: ValueSetRef; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level check constraint that restricts | ||
| * a column to the permitted values of a value-set. | ||
| * | ||
| * The constraint is **structured** (names a column and a value-set | ||
| * reference), not a raw SQL expression. Each target renders its own DDL | ||
| * from the structured form, keeping the contract target-agnostic. | ||
| * | ||
| * Construction is idempotent: passing an existing `CheckConstraint` | ||
| * instance as input produces a new instance with identical fields. | ||
| * The constructor does not use `instanceof` for input discrimination — | ||
| * it reads plain named properties, which is sufficient since | ||
| * `CheckConstraintInput` is a structural type. | ||
| */ | ||
| declare class CheckConstraint extends SqlNode { | ||
| readonly name: string; | ||
| readonly column: string; | ||
| readonly valueSet: ValueSetRef; | ||
| constructor(input: CheckConstraintInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/primary-key.d.ts | ||
| interface PrimaryKeyInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table's primary-key constraint. | ||
| */ | ||
| declare class PrimaryKey extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| constructor(input: PrimaryKeyInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/sql-index.d.ts | ||
| interface IndexInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| readonly type?: string; | ||
| readonly options?: Record<string, unknown>; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level secondary index. | ||
| * | ||
| * Note that this class shadows the global TypeScript `Index` lib type | ||
| * at the family-shared name; consumer files that need both should | ||
| * alias one (e.g. | ||
| * `import { Index as SqlIndexNode } from '@prisma-next/sql-contract/types'`). | ||
| */ | ||
| declare class Index extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| readonly type?: string; | ||
| readonly options?: Record<string, unknown>; | ||
| constructor(input: IndexInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-column.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link StorageColumn}. Mirrors | ||
| * the on-disk storage JSON envelope exactly so the family-base | ||
| * serializer's hydration walker can hand an arktype-validated literal | ||
| * straight to `new`. | ||
| * | ||
| * `typeParams` and `typeRef` remain mutually exclusive (one or the | ||
| * other, not both); the constructor preserves whichever caller-side | ||
| * choice the input encodes. | ||
| */ | ||
| interface StorageColumnInput { | ||
| readonly nativeType: string; | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| readonly typeRef?: string; | ||
| readonly default?: ColumnDefault; | ||
| readonly control?: ControlPolicy; | ||
| readonly valueSet?: ValueSetRef; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a single column entry in `StorageTable.columns`. | ||
| * | ||
| * Single concrete family-shared class — every SQL target reads the | ||
| * same column shape today, so there is no per-target subclass. The | ||
| * class type accepts any caller that constructs via | ||
| * `new StorageColumn(input)`; literal construction sites must pass | ||
| * through the constructor or the family-base hydration walker. | ||
| * | ||
| * The column's `name` is not on the class — columns are keyed by name | ||
| * in the parent `StorageTable.columns: Record<string, StorageColumn>` | ||
| * map, so a `name` field would be redundant with the key. | ||
| */ | ||
| declare class StorageColumn extends SqlNode { | ||
| readonly nativeType: string; | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| readonly typeParams?: Record<string, unknown>; | ||
| readonly typeRef?: string; | ||
| readonly default?: ColumnDefault; | ||
| readonly control?: ControlPolicy; | ||
| readonly valueSet?: ValueSetRef; | ||
| constructor(input: StorageColumnInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/unique-constraint.d.ts | ||
| interface UniqueConstraintInput { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a table-level unique constraint. | ||
| */ | ||
| declare class UniqueConstraint extends SqlNode { | ||
| readonly columns: readonly string[]; | ||
| readonly name?: string; | ||
| constructor(input: UniqueConstraintInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-table.d.ts | ||
| interface StorageTableInput { | ||
| readonly columns: Record<string, StorageColumn | StorageColumnInput>; | ||
| readonly primaryKey?: PrimaryKey | PrimaryKeyInput; | ||
| readonly uniques: ReadonlyArray<UniqueConstraint | UniqueConstraintInput>; | ||
| readonly indexes: ReadonlyArray<Index | IndexInput>; | ||
| readonly foreignKeys: ReadonlyArray<ForeignKey | ForeignKeyInput>; | ||
| readonly control?: ControlPolicy; | ||
| readonly checks?: ReadonlyArray<CheckConstraint | CheckConstraintInput>; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a single table entry in a namespace's | ||
| * `tables` map. | ||
| * | ||
| * The constructor normalises nested IR-class fields (columns, primary | ||
| * key, uniques, indexes, foreign keys) into the appropriate class | ||
| * instances so downstream walks see a uniform AST regardless of whether | ||
| * the input was a JSON literal or an already-constructed class. | ||
| * | ||
| * The table's `name` is not on the class — tables are keyed by name in | ||
| * the parent namespace's `tables: Record<string, StorageTable>` map. | ||
| */ | ||
| declare class StorageTable extends SqlNode { | ||
| readonly columns: Readonly<Record<string, StorageColumn>>; | ||
| readonly uniques: ReadonlyArray<UniqueConstraint>; | ||
| readonly indexes: ReadonlyArray<Index>; | ||
| readonly foreignKeys: ReadonlyArray<ForeignKey>; | ||
| readonly primaryKey?: PrimaryKey; | ||
| readonly control?: ControlPolicy; | ||
| readonly checks?: ReadonlyArray<CheckConstraint>; | ||
| constructor(input: StorageTableInput); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-value-set.d.ts | ||
| /** | ||
| * Hydration / construction input shape for {@link StorageValueSet}. | ||
| * Mirrors the on-disk storage JSON envelope so the serializer hydration | ||
| * walker can hand a validated literal straight to `new`. | ||
| */ | ||
| interface StorageValueSetInput { | ||
| readonly kind: 'valueSet'; | ||
| /** Ordered permitted values, codec-encoded. Declaration order is preserved. */ | ||
| readonly values: readonly JsonValue[]; | ||
| } | ||
| /** | ||
| * SQL Contract IR node for a value-set entry in a namespace's `valueSet` | ||
| * map (`SqlNamespace.entries.valueSet`). | ||
| * | ||
| * A value-set records the ordered set of permitted codec-encoded values for | ||
| * an enum-like column restriction. It does not carry a `codecId` — the | ||
| * column that references it already holds the codec; the value-set holds | ||
| * only the permitted values. | ||
| * | ||
| * The node's `kind` is enumerable (`'valueSet'`) so the JSON envelope | ||
| * carries the discriminator and the serializer hydration walker can | ||
| * dispatch on it. This follows the per-leaf enumerable-kind convention | ||
| * established in the SQL-node comment (future polymorphic dispatch on | ||
| * namespace entries needs the discriminator in JSON). | ||
| * | ||
| * The entry's name is not on the class — value-sets are keyed by name in | ||
| * the parent namespace's `valueSet: Record<string, StorageValueSet>` map. | ||
| */ | ||
| declare class StorageValueSet extends SqlNode { | ||
| readonly kind: "valueSet"; | ||
| readonly values: readonly JsonValue[]; | ||
| constructor(input: StorageValueSetInput); | ||
| } | ||
| //#endregion | ||
| export { UniqueConstraint as a, StorageColumnInput as c, PrimaryKey as d, PrimaryKeyInput as f, StorageTableInput as i, Index as l, CheckConstraintInput as m, StorageValueSetInput as n, UniqueConstraintInput as o, CheckConstraint as p, StorageTable as r, StorageColumn as s, StorageValueSet as t, IndexInput as u }; | ||
| //# sourceMappingURL=storage-value-set-WnYsIFM8.d.mts.map |
| {"version":3,"file":"storage-value-set-WnYsIFM8.d.mts","names":[],"sources":["../src/ir/check-constraint.ts","../src/ir/primary-key.ts","../src/ir/sql-index.ts","../src/ir/storage-column.ts","../src/ir/unique-constraint.ts","../src/ir/storage-table.ts","../src/ir/storage-value-set.ts"],"mappings":";;;;;;AASA;;;UAAiB,oBAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA;EAAA,SACA,QAAA,EAAU,WAAW;AAAA;;AAAA;AAiBhC;;;;;;;;;;;;cAAa,eAAA,SAAwB,OAAA;EAAA,SAC1B,IAAA;EAAA,SACA,MAAA;EAAA,SACA,QAAA,EAAU,WAAA;cAEP,KAAA,EAAO,oBAAA;AAAA;;;UC/BJ,eAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;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;;;;;;;AFKK;AAiBhC;cEXa,KAAA,SAAc,OAAA;EAAA,SAChB,OAAA;EAAA,SACQ,IAAA;EAAA,SACA,IAAA;EAAA,SACA,OAAA,GAAU,MAAA;cAEf,KAAA,EAAO,UAAA;AAAA;;;;;AFfrB;;;;;;;;UGKiB,kBAAA;EAAA,SACN,UAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA,GAAa,MAAA;EAAA,SACb,OAAA;EAAA,SACA,OAAA,GAAU,aAAA;EAAA,SACV,OAAA,GAAU,aAAA;EAAA,SACV,QAAA,GAAW,WAAA;AAAA;;;;;;;;;;AHYmB;;;;cGI5B,aAAA,SAAsB,OAAA;EAAA,SACxB,UAAA;EAAA,SACA,OAAA;EAAA,SACA,QAAA;EAAA,SACQ,UAAA,GAAa,MAAA;EAAA,SACb,OAAA;EAAA,SACA,OA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lNode, t as composeSqlEntityKinds } from "./entity-kinds-Cl36zL5j.mjs"; | ||
| import { NamespaceBase, UNBOUND_NAMESPACE_ID, freezeNode, hydrateNamespaceEntities } from "@prisma-next/framework-components/ir"; | ||
| import { blindCast } from "@prisma-next/utils/casts"; | ||
| //#region src/ir/sql-unbound-namespace.ts | ||
| /** | ||
| * Family-layer placeholder for the SQL unbound-namespace singleton — | ||
| * the late-bound slot whose binding the target resolves at connection | ||
| * time rather than at authoring time. | ||
| * | ||
| * SQL contracts honour the framework `Storage.namespaces` invariant from | ||
| * the moment they appear in the IR. Today `SqlStorage` is family-shared | ||
| * (Postgres + SQLite consume the same class); a per-target namespace | ||
| * concretion (`PostgresSchema.unbound`, `SqliteUnboundDatabase.instance`) | ||
| * earns its existence when each target's namespace shape lands. Until | ||
| * then the family ships a single placeholder singleton so the JSON | ||
| * envelope and runtime walk are honest at every layer. | ||
| * | ||
| * The `kind` discriminator is installed as a non-enumerable own property | ||
| * so the JSON envelope reads `{ "id": "__unbound__", "entries": { … } }` | ||
| * — symmetric with the family-level non-enumerable `kind` on `SqlNode` | ||
| * and bounded to the minimum data the framework `Namespace` interface | ||
| * promises. | ||
| * | ||
| * **Freeze-trap warning.** The leaf constructor calls | ||
| * `freezeNode(this)` after installing `kind`. The leaf-class shape | ||
| * works today only because `NamespaceBase` does NOT freeze in its | ||
| * constructor — the `Object.defineProperty(this, 'kind', …)` call after | ||
| * `super()` succeeds because the instance is still mutable at that | ||
| * point. Subclasses that add instance fields will still hit the freeze | ||
| * trap once leaf-class `freezeNode(this)` runs; and if a future | ||
| * framework change lifts the freeze to `NamespaceBase`, even the | ||
| * `defineProperty` here would silently fail. To add subclass instance | ||
| * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each | ||
| * leaf calls explicitly at the end of its own constructor. | ||
| */ | ||
| var SqlUnboundNamespace = class SqlUnboundNamespace extends NamespaceBase { | ||
| static instance = new SqlUnboundNamespace(); | ||
| id = UNBOUND_NAMESPACE_ID; | ||
| entries = Object.freeze({ table: blindCast(Object.freeze({})) }); | ||
| constructor() { | ||
| super(); | ||
| Object.defineProperty(this, "kind", { | ||
| value: "sql-namespace", | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| freezeNode(this); | ||
| } | ||
| get table() { | ||
| return blindCast(this.entries["table"]); | ||
| } | ||
| qualifyTable(tableName) { | ||
| return `"${tableName}"`; | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/ir/build-sql-namespace.ts | ||
| const SQL_NAMESPACE_KIND = "sql-namespace"; | ||
| function isMaterializedSqlNamespace(ns) { | ||
| if (typeof ns !== "object" || ns === null) return false; | ||
| const proto = Object.getPrototypeOf(ns); | ||
| if (proto === Object.prototype || proto === null) return false; | ||
| return ns.kind === SQL_NAMESPACE_KIND; | ||
| } | ||
| var SqlBoundNamespace = class SqlBoundNamespace extends NamespaceBase { | ||
| id; | ||
| entries; | ||
| static fromTablesInput(input) { | ||
| const tableKind = input.entries["table"]; | ||
| const tableCount = tableKind !== void 0 ? Object.keys(tableKind).length : 0; | ||
| const valueSetKind = input.entries["valueSet"]; | ||
| const hasValueSets = valueSetKind !== void 0 && Object.keys(valueSetKind).length > 0; | ||
| const hasUnknownKinds = Object.keys(input.entries).some((kind) => kind !== "table" && kind !== "valueSet"); | ||
| if (input.id === UNBOUND_NAMESPACE_ID && tableCount === 0 && !hasValueSets && !hasUnknownKinds) return SqlUnboundNamespace.instance; | ||
| return new SqlBoundNamespace(input); | ||
| } | ||
| constructor(input) { | ||
| super(); | ||
| this.id = input.id; | ||
| const dispatched = hydrateNamespaceEntities(input.entries, composeSqlEntityKinds(), "carry"); | ||
| this.entries = Object.freeze(blindCast(dispatched)); | ||
| Object.defineProperty(this, "kind", { | ||
| value: SQL_NAMESPACE_KIND, | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true | ||
| }); | ||
| freezeNode(this); | ||
| } | ||
| get table() { | ||
| return this.entries.table ?? Object.freeze({}); | ||
| } | ||
| get valueSet() { | ||
| return this.entries.valueSet; | ||
| } | ||
| qualifyTable(tableName) { | ||
| if (this.id === UNBOUND_NAMESPACE_ID) return `"${tableName}"`; | ||
| return `"${this.id}"."${tableName}"`; | ||
| } | ||
| }; | ||
| function buildSqlNamespace(input) { | ||
| return SqlBoundNamespace.fromTablesInput(input); | ||
| } | ||
| function buildSqlNamespaceMap(namespaces) { | ||
| return Object.fromEntries(Object.entries(namespaces).map(([nsKey, ns]) => [nsKey, isMaterializedSqlNamespace(ns) ? ns : SqlBoundNamespace.fromTablesInput(blindCast(ns))])); | ||
| } | ||
| //#endregion | ||
| //#region src/ir/storage-type-instance.ts | ||
| /** | ||
| * Sentinel kind for the legacy codec-triple shape persisted under | ||
| * `SqlStorage.types`. Plain JSON-clean object literals carry this | ||
| * discriminator so the polymorphic slot dispatch can route them down | ||
| * the codec path while target-specific IR class instances (e.g. the | ||
| * Postgres enum class) keep their own narrower `kind` literal. | ||
| */ | ||
| const CODEC_INSTANCE_KIND = "codec-instance"; | ||
| /** | ||
| * Stamp the codec-instance `kind` discriminator on a caller-supplied | ||
| * codec triple. Idempotent: input that already carries the discriminator | ||
| * passes through unchanged. Missing `typeParams` is normalised to `{}`. | ||
| */ | ||
| function toStorageTypeInstance(input) { | ||
| return { | ||
| kind: CODEC_INSTANCE_KIND, | ||
| codecId: input.codecId, | ||
| nativeType: input.nativeType, | ||
| typeParams: input.typeParams ?? {} | ||
| }; | ||
| } | ||
| /** | ||
| * Type-guard for codec-typed entries on the polymorphic | ||
| * `SqlStorage.types` slot. Distinguishes `StorageTypeInstance` from | ||
| * any class-instance kinds a target pack contributes. | ||
| */ | ||
| function isStorageTypeInstance(value) { | ||
| if (typeof value !== "object" || value === null) return false; | ||
| return value.kind === CODEC_INSTANCE_KIND; | ||
| } | ||
| //#endregion | ||
| //#region src/ir/sql-storage.ts | ||
| var SqlStorage = class extends SqlNode { | ||
| storageHash; | ||
| namespaces; | ||
| constructor(input) { | ||
| super(); | ||
| this.storageHash = input.storageHash; | ||
| this.namespaces = Object.freeze(input.namespaces); | ||
| if (input.types !== void 0) this.types = Object.freeze(Object.fromEntries(Object.entries(input.types).map(([name, ti]) => [name, normaliseTypeEntry(name, ti)]))); | ||
| freezeNode(this); | ||
| } | ||
| }; | ||
| /** | ||
| * Strict polymorphic-slot dispatch for `SqlStorage.types` entries. | ||
| * Every entry must carry a `kind: 'codec-instance'` discriminator or | ||
| * be an already-constructed `StorageTypeInstance`. Untagged or | ||
| * unrecognised inputs throw a diagnostic naming the entry and its | ||
| * `kind`, so format drift surfaces loudly at the deserializer | ||
| * boundary instead of slipping past the seam and corrupting | ||
| * downstream IR walks. | ||
| * | ||
| * Codec-triple authors that have an untagged shape on hand can call | ||
| * `toStorageTypeInstance(...)` (which stamps the `'codec-instance'` | ||
| * discriminator) before constructing `SqlStorage`. On-disk reads | ||
| * cross `familyInstance.deserializeContract` first; the structural | ||
| * arktype schema rejects untagged entries earlier, so this throw | ||
| * only fires for in-memory authoring bugs. | ||
| */ | ||
| function normaliseTypeEntry(name, entry) { | ||
| if (isStorageTypeInstance(entry)) { | ||
| if ("typeParams" in entry) return entry; | ||
| return toStorageTypeInstance(entry); | ||
| } | ||
| const rawKind = entry.kind; | ||
| const kindDescription = rawKind === void 0 ? "missing `kind` discriminator" : `unrecognised \`kind\` discriminator ${JSON.stringify(rawKind)}`; | ||
| 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.`); | ||
| } | ||
| //#endregion | ||
| //#region src/types.ts | ||
| const DEFAULT_FK_CONSTRAINT = true; | ||
| const DEFAULT_FK_INDEX = true; | ||
| function applyFkDefaults(fk, overrideDefaults) { | ||
| return { | ||
| constraint: fk.constraint ?? overrideDefaults?.constraint ?? true, | ||
| index: fk.index ?? overrideDefaults?.index ?? true | ||
| }; | ||
| } | ||
| //#endregion | ||
| export { CODEC_INSTANCE_KIND as a, buildSqlNamespace as c, SqlStorage as i, buildSqlNamespaceMap as l, DEFAULT_FK_INDEX as n, isStorageTypeInstance as o, applyFkDefaults as r, toStorageTypeInstance as s, DEFAULT_FK_CONSTRAINT as t, SqlUnboundNamespace as u }; | ||
| //# sourceMappingURL=types-B-eiQXff.mjs.map |
| {"version":3,"file":"types-B-eiQXff.mjs","names":[],"sources":["../src/ir/sql-unbound-namespace.ts","../src/ir/build-sql-namespace.ts","../src/ir/storage-type-instance.ts","../src/ir/sql-storage.ts","../src/types.ts"],"sourcesContent":["import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { SqlNamespaceEntries } from './sql-storage';\nimport type { StorageTable } from './storage-table';\n\n/**\n * Family-layer placeholder for the SQL unbound-namespace singleton —\n * the late-bound slot whose binding the target resolves at connection\n * time rather than at authoring time.\n *\n * SQL contracts honour the framework `Storage.namespaces` invariant from\n * the moment they appear in the IR. Today `SqlStorage` is family-shared\n * (Postgres + SQLite consume the same class); a per-target namespace\n * concretion (`PostgresSchema.unbound`, `SqliteUnboundDatabase.instance`)\n * earns its existence when each target's namespace shape lands. Until\n * then the family ships a single placeholder singleton so the JSON\n * envelope and runtime walk are honest at every layer.\n *\n * The `kind` discriminator is installed as a non-enumerable own property\n * so the JSON envelope reads `{ \"id\": \"__unbound__\", \"entries\": { … } }`\n * — symmetric with the family-level non-enumerable `kind` on `SqlNode`\n * and bounded to the minimum data the framework `Namespace` interface\n * promises.\n *\n * **Freeze-trap warning.** The leaf constructor calls\n * `freezeNode(this)` after installing `kind`. The leaf-class shape\n * works today only because `NamespaceBase` does NOT freeze in its\n * constructor — the `Object.defineProperty(this, 'kind', …)` call after\n * `super()` succeeds because the instance is still mutable at that\n * point. Subclasses that add instance fields will still hit the freeze\n * trap once leaf-class `freezeNode(this)` runs; and if a future\n * framework change lifts the freeze to `NamespaceBase`, even the\n * `defineProperty` here would silently fail. To add subclass instance\n * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each\n * leaf calls explicitly at the end of its own constructor.\n */\nexport class SqlUnboundNamespace extends NamespaceBase {\n static readonly instance: SqlUnboundNamespace = new SqlUnboundNamespace();\n\n readonly id = UNBOUND_NAMESPACE_ID;\n readonly entries: SqlNamespaceEntries = Object.freeze({\n table: blindCast<\n Readonly<Record<string, StorageTable>>,\n 'empty frozen map is a valid Readonly<Record<string, StorageTable>>'\n >(Object.freeze({})),\n });\n declare readonly kind: string;\n\n private constructor() {\n super();\n Object.defineProperty(this, 'kind', {\n value: 'sql-namespace',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n get table(): Readonly<Record<string, StorageTable>> {\n return blindCast<\n Readonly<Record<string, StorageTable>>,\n 'entries[table] holds only StorageTable by construction'\n >(this.entries['table']);\n }\n\n qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n}\n","import {\n freezeNode,\n hydrateNamespaceEntities,\n type Namespace,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { composeSqlEntityKinds } from '../entity-kinds';\nimport type { SqlNamespace, SqlNamespaceEntries, SqlNamespaceTablesInput } from './sql-storage';\nimport { SqlUnboundNamespace } from './sql-unbound-namespace';\nimport type { StorageTable } from './storage-table';\nimport type { StorageValueSet } from './storage-value-set';\n\nconst SQL_NAMESPACE_KIND = 'sql-namespace' as const;\n\nfunction isMaterializedSqlNamespace(ns: Namespace | SqlNamespaceTablesInput): ns is SqlNamespace {\n if (typeof ns !== 'object' || ns === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(ns);\n if (proto === Object.prototype || proto === null) {\n return false;\n }\n return (ns as Namespace).kind === SQL_NAMESPACE_KIND;\n}\n\nclass SqlBoundNamespace extends NamespaceBase {\n declare readonly kind: string;\n\n readonly id: string;\n readonly entries: SqlNamespaceEntries;\n\n static fromTablesInput(input: SqlNamespaceTablesInput): SqlNamespace {\n const tableKind = input.entries['table'];\n const tableCount = tableKind !== undefined ? Object.keys(tableKind).length : 0;\n const valueSetKind = input.entries['valueSet'];\n const hasValueSets = valueSetKind !== undefined && Object.keys(valueSetKind).length > 0;\n const hasUnknownKinds = Object.keys(input.entries).some(\n (kind) => kind !== 'table' && kind !== 'valueSet',\n );\n if (\n input.id === UNBOUND_NAMESPACE_ID &&\n tableCount === 0 &&\n !hasValueSets &&\n !hasUnknownKinds\n ) {\n return SqlUnboundNamespace.instance;\n }\n return new SqlBoundNamespace(input);\n }\n\n private constructor(input: SqlNamespaceTablesInput) {\n super();\n this.id = input.id;\n\n const dispatched = hydrateNamespaceEntities(input.entries, composeSqlEntityKinds(), 'carry');\n\n this.entries = Object.freeze(\n blindCast<\n SqlNamespaceEntries,\n 'composeSqlEntityKinds() supplies table→StorageTable and valueSet→StorageValueSet descriptors, so this open-dict result holds exactly the typed members SqlNamespaceEntries declares; the descriptor Map erases those per-kind Node types from the return.'\n >(dispatched),\n );\n Object.defineProperty(this, 'kind', {\n value: SQL_NAMESPACE_KIND,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n get table(): Readonly<Record<string, StorageTable>> {\n return this.entries.table ?? Object.freeze({});\n }\n\n get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined {\n return this.entries.valueSet;\n }\n\n qualifyTable(tableName: string): string {\n if (this.id === UNBOUND_NAMESPACE_ID) {\n return `\"${tableName}\"`;\n }\n return `\"${this.id}\".\"${tableName}\"`;\n }\n}\n\nexport function buildSqlNamespace(input: SqlNamespaceTablesInput): SqlNamespace {\n return SqlBoundNamespace.fromTablesInput(input);\n}\n\nexport function buildSqlNamespaceMap(\n namespaces: Readonly<Record<string, Namespace | SqlNamespaceTablesInput>>,\n): Readonly<Record<string, SqlNamespace>> {\n return Object.fromEntries(\n Object.entries(namespaces).map(([nsKey, ns]) => [\n nsKey,\n isMaterializedSqlNamespace(ns)\n ? ns\n : SqlBoundNamespace.fromTablesInput(\n blindCast<\n SqlNamespaceTablesInput,\n 'non-materialized SQL namespace map entry is a SqlNamespaceTablesInput'\n >(ns),\n ),\n ]),\n );\n}\n","import type { StorageType } from '@prisma-next/framework-components/ir';\n\n/**\n * Sentinel kind for the legacy codec-triple shape persisted under\n * `SqlStorage.types`. Plain JSON-clean object literals carry this\n * discriminator so the polymorphic slot dispatch can route them down\n * the codec path while target-specific IR class instances (e.g. the\n * Postgres enum class) keep their own narrower `kind` literal.\n */\nexport const CODEC_INSTANCE_KIND = 'codec-instance' as const;\n\n/**\n * Structural sub-interface of {@link StorageType} for codec-typed entries\n * in `SqlStorage.types`. These are plain object literals — there is no\n * runtime IR class, the JSON envelope round-trips through the slot\n * unchanged. The `kind: 'codec-instance'` discriminator is the dispatch\n * key that distinguishes codec-typed entries from 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 { freezeNode, type Namespace, type Storage } 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 SqlNamespaceTablesInput {\n readonly id: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\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, SqlNamespace>>;\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 * SQL family namespace. `entries` is the open ADR 224 dictionary —\n * `entries[entityKind][entityName]` addresses any entity. Emitted\n * contract literals satisfy this structurally (no prototype getters\n * needed). For typed access to specific kinds, use the class getters\n * on the concretion or `ns.entries.table` / `ns.entries.valueSet` directly.\n */\nexport type SqlNamespace = Namespace & {\n readonly entries: SqlNamespaceEntries;\n /**\n * Render a dialect-qualified table reference for runtime SQL emission.\n * Present on materialised target concretions (`PostgresSchema`,\n * `SqliteDatabase`, …) and family placeholders; omitted on emitted\n * contract structural namespace literals (methods are not serialised).\n */\n qualifyTable?(tableName: string): string;\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 = (entry as { kind?: unknown }).kind;\n const kindDescription =\n rawKind === undefined\n ? 'missing `kind` discriminator'\n : `unrecognised \\`kind\\` discriminator ${JSON.stringify(rawKind)}`;\n throw new Error(\n `storage.types[${JSON.stringify(name)}] has ${kindDescription}; expected ${JSON.stringify('codec-instance')}. 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 { buildSqlNamespace, buildSqlNamespaceMap } from './ir/build-sql-namespace';\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 type SqlNamespace,\n type SqlNamespaceEntries,\n type SqlNamespaceTablesInput,\n SqlStorage,\n type SqlStorageInput,\n type SqlStorageTypeEntry,\n} from './ir/sql-storage';\nexport { SqlUnboundNamespace } from './ir/sql-unbound-namespace';\nexport { StorageColumn, type StorageColumnInput } from './ir/storage-column';\nexport { StorageTable, type StorageTableInput } from './ir/storage-table';\nexport {\n CODEC_INSTANCE_KIND,\n isStorageTypeInstance,\n type StorageTypeInstance,\n type StorageTypeInstanceInput,\n toStorageTypeInstance,\n} from './ir/storage-type-instance';\nexport { StorageValueSet, type StorageValueSetInput } 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 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> = {\n readonly codecTypes: TCodecTypes;\n readonly queryOperationTypes: TQueryOperationTypes;\n readonly fieldOutputTypes: TFieldOutputTypes;\n readonly fieldInputTypes: TFieldInputTypes;\n};\n\nexport type CodecTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly codecTypes: infer C }\n ? C extends Record<string, { output: unknown }>\n ? C\n : Record<string, never>\n : Record<string, never>;\n\n/**\n * Dispatch hint identifying the first-argument target of an operation.\n *\n * Used by ORM column helpers to decide whether an operation is reachable on a\n * field. Either names a concrete codec identity or a set of capability traits\n * that the field's codec must carry.\n */\nexport type QueryOperationSelfSpec =\n | { readonly codecId: string; readonly traits?: never }\n | { readonly traits: readonly CodecTrait[]; readonly codecId?: never };\n\n/**\n * Structural shape an operation's impl must return: any value carrying a\n * codec-exact `returnType` descriptor. `Expression<T>` (from\n * `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`)\n * extends this. Trait-targeted returns are deliberately excluded — predicate\n * detection and result decoding both depend on knowing the concrete return\n * codec.\n */\nexport type QueryOperationReturn = {\n readonly returnType: { readonly codecId: string; readonly nullable: boolean };\n};\n\nexport type QueryOperationTypeEntry = {\n readonly self?: QueryOperationSelfSpec;\n readonly impl: (...args: never[]) => QueryOperationReturn;\n};\n\nexport type SqlQueryOperationTypes<\n _CT extends Record<string, { readonly input: unknown; readonly output: unknown }>,\n T extends Record<string, QueryOperationTypeEntry>,\n> = T;\n\nexport type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>;\n\nexport type QueryOperationTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly queryOperationTypes: infer Q }\n ? Q extends Record<string, unknown>\n ? Q\n : Record<string, never>\n : Record<string, never>;\n\nexport type TypeMapsPhantomKey = '__@prisma-next/sql-contract/typeMaps@__';\n\nexport type ContractWithTypeMaps<TContract, TTypeMaps> = TContract & {\n readonly [K in TypeMapsPhantomKey]?: TTypeMaps;\n};\n\nexport type ExtractTypeMapsFromContract<T> = TypeMapsPhantomKey extends keyof T\n ? NonNullable<T[TypeMapsPhantomKey & keyof T]>\n : never;\n\nexport type FieldOutputTypesOf<T> = [T] extends [never]\n ? Record<string, never>\n : T extends { readonly fieldOutputTypes: infer F }\n ? F extends 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 ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldOutputTypes<T> = FieldOutputTypesOf<ExtractTypeMapsFromContract<T>>;\nexport type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>;\n\nexport type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never]\n ? ExtractCodecTypes<TContract>\n : CodecTypesOf<TTypeMaps>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,sBAAb,MAAa,4BAA4B,cAAc;CACrD,OAAgB,WAAgC,IAAI,oBAAoB;CAExE,KAAc;CACd,UAAwC,OAAO,OAAO,EACpD,OAAO,UAGL,OAAO,OAAO,CAAC,CAAC,CAAC,EACrB,CAAC;CAGD,cAAsB;EACpB,MAAM;EACN,OAAO,eAAe,MAAM,QAAQ;GAClC,OAAO;GACP,UAAU;GACV,YAAY;GACZ,cAAc;EAChB,CAAC;EACD,WAAW,IAAI;CACjB;CAEA,IAAI,QAAgD;EAClD,OAAO,UAGL,KAAK,QAAQ,QAAQ;CACzB;CAEA,aAAa,WAA2B;EACtC,OAAO,IAAI,UAAU;CACvB;AACF;;;AC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BAAgB,aAAa,KAAK,UAAU,gBAAgB,EAAE,gGAC9G;AACF;;;ACtEA,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"} |
| import { r as ReferentialAction } from "./foreign-key-BATxB95l.mjs"; | ||
| import { r as StorageTable } from "./storage-value-set-WnYsIFM8.mjs"; | ||
| import { n as SqlNamespaceEntries, r as SqlNamespaceTablesInput, t as SqlNamespace } from "./sql-storage-Dga0jwP2.mjs"; | ||
| import { Namespace, NamespaceBase } from "@prisma-next/framework-components/ir"; | ||
| import { CodecTrait } from "@prisma-next/framework-components/codec"; | ||
| import { ControlDriverInstance } from "@prisma-next/framework-components/control"; | ||
| //#region src/ir/build-sql-namespace.d.ts | ||
| declare function buildSqlNamespace(input: SqlNamespaceTablesInput): SqlNamespace; | ||
| declare function buildSqlNamespaceMap(namespaces: Readonly<Record<string, Namespace | SqlNamespaceTablesInput>>): Readonly<Record<string, SqlNamespace>>; | ||
| //#endregion | ||
| //#region src/ir/sql-unbound-namespace.d.ts | ||
| /** | ||
| * Family-layer placeholder for the SQL unbound-namespace singleton — | ||
| * the late-bound slot whose binding the target resolves at connection | ||
| * time rather than at authoring time. | ||
| * | ||
| * SQL contracts honour the framework `Storage.namespaces` invariant from | ||
| * the moment they appear in the IR. Today `SqlStorage` is family-shared | ||
| * (Postgres + SQLite consume the same class); a per-target namespace | ||
| * concretion (`PostgresSchema.unbound`, `SqliteUnboundDatabase.instance`) | ||
| * earns its existence when each target's namespace shape lands. Until | ||
| * then the family ships a single placeholder singleton so the JSON | ||
| * envelope and runtime walk are honest at every layer. | ||
| * | ||
| * The `kind` discriminator is installed as a non-enumerable own property | ||
| * so the JSON envelope reads `{ "id": "__unbound__", "entries": { … } }` | ||
| * — symmetric with the family-level non-enumerable `kind` on `SqlNode` | ||
| * and bounded to the minimum data the framework `Namespace` interface | ||
| * promises. | ||
| * | ||
| * **Freeze-trap warning.** The leaf constructor calls | ||
| * `freezeNode(this)` after installing `kind`. The leaf-class shape | ||
| * works today only because `NamespaceBase` does NOT freeze in its | ||
| * constructor — the `Object.defineProperty(this, 'kind', …)` call after | ||
| * `super()` succeeds because the instance is still mutable at that | ||
| * point. Subclasses that add instance fields will still hit the freeze | ||
| * trap once leaf-class `freezeNode(this)` runs; and if a future | ||
| * framework change lifts the freeze to `NamespaceBase`, even the | ||
| * `defineProperty` here would silently fail. To add subclass instance | ||
| * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each | ||
| * leaf calls explicitly at the end of its own constructor. | ||
| */ | ||
| declare class SqlUnboundNamespace extends NamespaceBase { | ||
| static readonly instance: SqlUnboundNamespace; | ||
| readonly id: "__unbound__"; | ||
| readonly entries: SqlNamespaceEntries; | ||
| readonly kind: string; | ||
| private constructor(); | ||
| get table(): Readonly<Record<string, StorageTable>>; | ||
| qualifyTable(tableName: string): string; | ||
| } | ||
| //#endregion | ||
| //#region src/types.d.ts | ||
| interface SqlControlDriverInstance<T extends string = string> extends ControlDriverInstance<'sql', T> { | ||
| query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{ | ||
| readonly rows: Row[]; | ||
| }>; | ||
| } | ||
| type ForeignKeyOptions = { | ||
| readonly name?: string; | ||
| readonly onDelete?: ReferentialAction; | ||
| readonly onUpdate?: ReferentialAction; | ||
| }; | ||
| type SqlModelFieldStorage = { | ||
| readonly column: string; | ||
| readonly codecId?: string; | ||
| readonly nullable?: boolean; | ||
| }; | ||
| type SqlModelStorage = { | ||
| readonly table: string; | ||
| readonly namespaceId: string; | ||
| readonly fields: Record<string, SqlModelFieldStorage>; | ||
| }; | ||
| declare const DEFAULT_FK_CONSTRAINT = true; | ||
| declare const DEFAULT_FK_INDEX = true; | ||
| declare function applyFkDefaults(fk: { | ||
| constraint?: boolean | undefined; | ||
| index?: boolean | undefined; | ||
| }, overrideDefaults?: { | ||
| constraint?: boolean | undefined; | ||
| index?: boolean | undefined; | ||
| }): { | ||
| constraint: boolean; | ||
| index: boolean; | ||
| }; | ||
| type NamespacedFieldTypeMap = Record<string, Record<string, Record<string, unknown>>>; | ||
| type TypeMaps<TCodecTypes extends Record<string, { | ||
| output: unknown; | ||
| }> = Record<string, never>, TQueryOperationTypes extends Record<string, unknown> = Record<string, never>, TFieldOutputTypes extends NamespacedFieldTypeMap = Record<string, never>, TFieldInputTypes extends NamespacedFieldTypeMap = Record<string, never>> = { | ||
| readonly codecTypes: TCodecTypes; | ||
| readonly queryOperationTypes: TQueryOperationTypes; | ||
| readonly fieldOutputTypes: TFieldOutputTypes; | ||
| readonly fieldInputTypes: TFieldInputTypes; | ||
| }; | ||
| type CodecTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly codecTypes: infer C; | ||
| } ? C extends Record<string, { | ||
| output: unknown; | ||
| }> ? C : Record<string, never> : Record<string, never>; | ||
| /** | ||
| * Dispatch hint identifying the first-argument target of an operation. | ||
| * | ||
| * Used by ORM column helpers to decide whether an operation is reachable on a | ||
| * field. Either names a concrete codec identity or a set of capability traits | ||
| * that the field's codec must carry. | ||
| */ | ||
| type QueryOperationSelfSpec = { | ||
| readonly codecId: string; | ||
| readonly traits?: never; | ||
| } | { | ||
| readonly traits: readonly CodecTrait[]; | ||
| readonly codecId?: never; | ||
| }; | ||
| /** | ||
| * Structural shape an operation's impl must return: any value carrying a | ||
| * codec-exact `returnType` descriptor. `Expression<T>` (from | ||
| * `@prisma-next/sql-relational-core/expression`, with `T extends ScopeField`) | ||
| * extends this. Trait-targeted returns are deliberately excluded — predicate | ||
| * detection and result decoding both depend on knowing the concrete return | ||
| * codec. | ||
| */ | ||
| type QueryOperationReturn = { | ||
| readonly returnType: { | ||
| readonly codecId: string; | ||
| readonly nullable: boolean; | ||
| }; | ||
| }; | ||
| type QueryOperationTypeEntry = { | ||
| readonly self?: QueryOperationSelfSpec; | ||
| readonly impl: (...args: never[]) => QueryOperationReturn; | ||
| }; | ||
| type SqlQueryOperationTypes<_CT extends Record<string, { | ||
| readonly input: unknown; | ||
| readonly output: unknown; | ||
| }>, T extends Record<string, QueryOperationTypeEntry>> = T; | ||
| type QueryOperationTypesBase = Record<string, QueryOperationTypeEntry>; | ||
| type QueryOperationTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly queryOperationTypes: infer Q; | ||
| } ? Q extends Record<string, unknown> ? Q : Record<string, never> : Record<string, never>; | ||
| type TypeMapsPhantomKey = '__@prisma-next/sql-contract/typeMaps@__'; | ||
| type ContractWithTypeMaps<TContract, TTypeMaps> = TContract & { readonly [K in TypeMapsPhantomKey]?: TTypeMaps }; | ||
| type ExtractTypeMapsFromContract<T> = TypeMapsPhantomKey extends keyof T ? NonNullable<T[TypeMapsPhantomKey & keyof T]> : never; | ||
| type FieldOutputTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly fieldOutputTypes: infer F; | ||
| } ? F extends NamespacedFieldTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type FieldInputTypesOf<T> = [T] extends [never] ? Record<string, never> : T extends { | ||
| readonly fieldInputTypes: infer F; | ||
| } ? F extends NamespacedFieldTypeMap ? F : Record<string, never> : Record<string, never>; | ||
| type ExtractCodecTypes<T> = CodecTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractQueryOperationTypes<T> = QueryOperationTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractFieldOutputTypes<T> = FieldOutputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ExtractFieldInputTypes<T> = FieldInputTypesOf<ExtractTypeMapsFromContract<T>>; | ||
| type ResolveCodecTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] ? ExtractCodecTypes<TContract> : CodecTypesOf<TTypeMaps>; | ||
| //#endregion | ||
| export { TypeMaps as C, buildSqlNamespace as D, SqlUnboundNamespace as E, buildSqlNamespaceMap as O, SqlQueryOperationTypes as S, applyFkDefaults as T, QueryOperationTypesOf as _, ExtractCodecTypes as a, SqlModelFieldStorage as b, ExtractQueryOperationTypes as c, FieldOutputTypesOf as d, ForeignKeyOptions as f, QueryOperationTypesBase as g, QueryOperationTypeEntry as h, DEFAULT_FK_INDEX as i, ExtractTypeMapsFromContract as l, QueryOperationSelfSpec as m, ContractWithTypeMaps as n, ExtractFieldInputTypes as o, QueryOperationReturn as p, DEFAULT_FK_CONSTRAINT as r, ExtractFieldOutputTypes as s, CodecTypesOf as t, FieldInputTypesOf as u, ResolveCodecTypes as v, TypeMapsPhantomKey as w, SqlModelStorage as x, SqlControlDriverInstance as y }; | ||
| //# sourceMappingURL=types-B1N8w0I2.d.mts.map |
| {"version":3,"file":"types-B1N8w0I2.d.mts","names":[],"sources":["../src/ir/build-sql-namespace.ts","../src/ir/sql-unbound-namespace.ts","../src/types.ts"],"mappings":";;;;;;;;iBAyFgB,iBAAA,CAAkB,KAAA,EAAO,uBAAA,GAA0B,YAAY;AAAA,iBAI/D,oBAAA,CACd,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,SAAA,GAAY,uBAAA,KAC/C,QAAA,CAAS,MAAA,SAAe,YAAA;;;;;;;;AAN3B;;;;;;;;AAA+E;AAI/E;;;;;;;;;;;;;;;;;cCrDa,mBAAA,SAA4B,aAAA;EAAA,gBACvB,QAAA,EAAU,mBAAA;EAAA,SAEjB,EAAA;EAAA,SACA,OAAA,EAAS,mBAAA;EAAA,SAMD,IAAA;EAAA,QAEV,WAAA;EAAA,IAWH,KAAA,IAAS,QAAA,CAAS,MAAA,SAAe,YAAA;EAOrC,YAAA,CAAa,SAAA;AAAA;;;UClEE,wBAAA,oCACP,qBAAA,QAA6B,CAAA;EACrC,KAAA,OAAY,MAAA,mBACV,GAAA,UACA,MAAA,wBACC,OAAA;IAAA,SAAmB,IAAA,EAAM,GAAA;EAAA;AAAA;AAAA,KAyClB,iBAAA;EAAA,SACD,IAAA;EAAA,SACA,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;AAAA;AAAA,KAG/C,sBAAA,aACE,MAAA;EAAA,SAA0B,KAAA;EAAA,SAAyB,MAAA;AAAA,cACrD,MAAA,SAAe,uBAAA,KACvB,CAAA;AAAA,KAEQ,uBAAA,GAA0B,MAAM,SAAS,uBAAA;AAAA,KAEzC,qBAAA,OAA4B,CAAA,oBACpC,MAAA,kBACA,CAAA;EAAA,SAAqB,mBAAA;AAAA,IACnB,CAAA,SAAU,MAAA,oBACR,CAAA,GACA,MAAA,kBACF,MAAA;AAAA,KAEM,kBAAA;AAAA,KAEA,oBAAA,yBAA6C,SAAA,oBACxC,kBAAA,IAAsB,SAAA;AAAA,KAG3B,2BAAA,MAAiC,kBAAA,eAAiC,CAAA,GAC1E,WAAA,CAAY,CAAA,CAAE,kBAAA,SAA2B,CAAA;AAAA,KAGjC,kBAAA,OAAyB,CAAA,oBACjC,MAAA,kBACA,CAAA;EAAA,SAAqB,gBAAA;AAAA,IACnB,CAAA,SAAU,sBAAA,GACR,CAAA,GACA,MAAA,kBACF,MAAA;AAAA,KAEM,iBAAA,OAAwB,CAAA,oBAChC,MAAA,kBACA,CAAA;EAAA,SAAqB,eAAA;AAAA,IACnB,CAAA,SAAU,sBAAA,GACR,CAAA,GACA,MAAA,kBACF,MAAA;AAAA,KAEM,iBAAA,MAAuB,YAAA,CAAa,2BAAA,CAA4B,CAAA;AAAA,KAChE,0BAAA,MAAgC,qBAAA,CAAsB,2BAAA,CAA4B,CAAA;AAAA,KAClF,uBAAA,MAA6B,kBAAA,CAAmB,2BAAA,CAA4B,CAAA;AAAA,KAC5E,sBAAA,MAA4B,iBAAA,CAAkB,2BAAA,CAA4B,CAAA;AAAA,KAE1E,iBAAA,0BAA2C,SAAA,oBACnD,iBAAA,CAAkB,SAAA,IAClB,YAAA,CAAa,SAAA"} |
| import { | ||
| freezeNode, | ||
| hydrateNamespaceEntities, | ||
| type Namespace, | ||
| NamespaceBase, | ||
| UNBOUND_NAMESPACE_ID, | ||
| } from '@prisma-next/framework-components/ir'; | ||
| import { blindCast } from '@prisma-next/utils/casts'; | ||
| import { composeSqlEntityKinds } from '../entity-kinds'; | ||
| import type { SqlNamespace, SqlNamespaceEntries, SqlNamespaceTablesInput } from './sql-storage'; | ||
| import { SqlUnboundNamespace } from './sql-unbound-namespace'; | ||
| import type { StorageTable } from './storage-table'; | ||
| import type { StorageValueSet } from './storage-value-set'; | ||
| const SQL_NAMESPACE_KIND = 'sql-namespace' as const; | ||
| function isMaterializedSqlNamespace(ns: Namespace | SqlNamespaceTablesInput): ns is SqlNamespace { | ||
| if (typeof ns !== 'object' || ns === null) { | ||
| return false; | ||
| } | ||
| const proto = Object.getPrototypeOf(ns); | ||
| if (proto === Object.prototype || proto === null) { | ||
| return false; | ||
| } | ||
| return (ns as Namespace).kind === SQL_NAMESPACE_KIND; | ||
| } | ||
| class SqlBoundNamespace extends NamespaceBase { | ||
| declare readonly kind: string; | ||
| readonly id: string; | ||
| readonly entries: SqlNamespaceEntries; | ||
| static fromTablesInput(input: SqlNamespaceTablesInput): SqlNamespace { | ||
| const tableKind = input.entries['table']; | ||
| const tableCount = tableKind !== undefined ? Object.keys(tableKind).length : 0; | ||
| const valueSetKind = input.entries['valueSet']; | ||
| const hasValueSets = valueSetKind !== undefined && Object.keys(valueSetKind).length > 0; | ||
| const hasUnknownKinds = Object.keys(input.entries).some( | ||
| (kind) => kind !== 'table' && kind !== 'valueSet', | ||
| ); | ||
| if ( | ||
| input.id === UNBOUND_NAMESPACE_ID && | ||
| tableCount === 0 && | ||
| !hasValueSets && | ||
| !hasUnknownKinds | ||
| ) { | ||
| return SqlUnboundNamespace.instance; | ||
| } | ||
| return new SqlBoundNamespace(input); | ||
| } | ||
| private constructor(input: SqlNamespaceTablesInput) { | ||
| super(); | ||
| this.id = input.id; | ||
| const dispatched = hydrateNamespaceEntities(input.entries, composeSqlEntityKinds(), 'carry'); | ||
| this.entries = Object.freeze( | ||
| blindCast< | ||
| SqlNamespaceEntries, | ||
| 'composeSqlEntityKinds() supplies table→StorageTable and valueSet→StorageValueSet descriptors, so this open-dict result holds exactly the typed members SqlNamespaceEntries declares; the descriptor Map erases those per-kind Node types from the return.' | ||
| >(dispatched), | ||
| ); | ||
| Object.defineProperty(this, 'kind', { | ||
| value: SQL_NAMESPACE_KIND, | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true, | ||
| }); | ||
| freezeNode(this); | ||
| } | ||
| get table(): Readonly<Record<string, StorageTable>> { | ||
| return this.entries.table ?? Object.freeze({}); | ||
| } | ||
| get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined { | ||
| return this.entries.valueSet; | ||
| } | ||
| qualifyTable(tableName: string): string { | ||
| if (this.id === UNBOUND_NAMESPACE_ID) { | ||
| return `"${tableName}"`; | ||
| } | ||
| return `"${this.id}"."${tableName}"`; | ||
| } | ||
| } | ||
| export function buildSqlNamespace(input: SqlNamespaceTablesInput): SqlNamespace { | ||
| return SqlBoundNamespace.fromTablesInput(input); | ||
| } | ||
| export function buildSqlNamespaceMap( | ||
| namespaces: Readonly<Record<string, Namespace | SqlNamespaceTablesInput>>, | ||
| ): Readonly<Record<string, SqlNamespace>> { | ||
| return Object.fromEntries( | ||
| Object.entries(namespaces).map(([nsKey, ns]) => [ | ||
| nsKey, | ||
| isMaterializedSqlNamespace(ns) | ||
| ? ns | ||
| : SqlBoundNamespace.fromTablesInput( | ||
| blindCast< | ||
| SqlNamespaceTablesInput, | ||
| 'non-materialized SQL namespace map entry is a SqlNamespaceTablesInput' | ||
| >(ns), | ||
| ), | ||
| ]), | ||
| ); | ||
| } |
| import { | ||
| freezeNode, | ||
| NamespaceBase, | ||
| UNBOUND_NAMESPACE_ID, | ||
| } from '@prisma-next/framework-components/ir'; | ||
| import { blindCast } from '@prisma-next/utils/casts'; | ||
| import type { SqlNamespaceEntries } from './sql-storage'; | ||
| import type { StorageTable } from './storage-table'; | ||
| /** | ||
| * Family-layer placeholder for the SQL unbound-namespace singleton — | ||
| * the late-bound slot whose binding the target resolves at connection | ||
| * time rather than at authoring time. | ||
| * | ||
| * SQL contracts honour the framework `Storage.namespaces` invariant from | ||
| * the moment they appear in the IR. Today `SqlStorage` is family-shared | ||
| * (Postgres + SQLite consume the same class); a per-target namespace | ||
| * concretion (`PostgresSchema.unbound`, `SqliteUnboundDatabase.instance`) | ||
| * earns its existence when each target's namespace shape lands. Until | ||
| * then the family ships a single placeholder singleton so the JSON | ||
| * envelope and runtime walk are honest at every layer. | ||
| * | ||
| * The `kind` discriminator is installed as a non-enumerable own property | ||
| * so the JSON envelope reads `{ "id": "__unbound__", "entries": { … } }` | ||
| * — symmetric with the family-level non-enumerable `kind` on `SqlNode` | ||
| * and bounded to the minimum data the framework `Namespace` interface | ||
| * promises. | ||
| * | ||
| * **Freeze-trap warning.** The leaf constructor calls | ||
| * `freezeNode(this)` after installing `kind`. The leaf-class shape | ||
| * works today only because `NamespaceBase` does NOT freeze in its | ||
| * constructor — the `Object.defineProperty(this, 'kind', …)` call after | ||
| * `super()` succeeds because the instance is still mutable at that | ||
| * point. Subclasses that add instance fields will still hit the freeze | ||
| * trap once leaf-class `freezeNode(this)` runs; and if a future | ||
| * framework change lifts the freeze to `NamespaceBase`, even the | ||
| * `defineProperty` here would silently fail. To add subclass instance | ||
| * fields safely, lift `freezeNode` to a leaf-class `seal()` hook each | ||
| * leaf calls explicitly at the end of its own constructor. | ||
| */ | ||
| export class SqlUnboundNamespace extends NamespaceBase { | ||
| static readonly instance: SqlUnboundNamespace = new SqlUnboundNamespace(); | ||
| readonly id = UNBOUND_NAMESPACE_ID; | ||
| readonly entries: SqlNamespaceEntries = Object.freeze({ | ||
| table: blindCast< | ||
| Readonly<Record<string, StorageTable>>, | ||
| 'empty frozen map is a valid Readonly<Record<string, StorageTable>>' | ||
| >(Object.freeze({})), | ||
| }); | ||
| declare readonly kind: string; | ||
| private constructor() { | ||
| super(); | ||
| Object.defineProperty(this, 'kind', { | ||
| value: 'sql-namespace', | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: true, | ||
| }); | ||
| freezeNode(this); | ||
| } | ||
| get table(): Readonly<Record<string, StorageTable>> { | ||
| return blindCast< | ||
| Readonly<Record<string, StorageTable>>, | ||
| 'entries[table] holds only StorageTable by construction' | ||
| >(this.entries['table']); | ||
| } | ||
| qualifyTable(tableName: string): string { | ||
| return `"${tableName}"`; | ||
| } | ||
| } |
402999
18.93%115
30.68%4158
16.76%+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
Updated
Updated
Updated