@prisma-next/sql-contract-ts 0.16.0-dev.31 → 0.16.0-dev.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/{build-contract-DbUeVkiu.mjs → build-contract-CPmjzfX3.mjs} +10 -5
- package/dist/build-contract-CPmjzfX3.mjs.map +1 -0
- package/dist/config-types.mjs +1 -1
- package/dist/contract-builder.d.mts +60 -14
- package/dist/contract-builder.d.mts.map +1 -1
- package/dist/contract-builder.mjs +35 -13
- package/dist/contract-builder.mjs.map +1 -1
- package/package.json +10 -10
- package/src/build-contract.ts +28 -8
- package/src/contract-definition.ts +24 -9
- package/src/contract-dsl.ts +88 -20
- package/src/contract-lowering.ts +20 -6
- package/dist/build-contract-DbUeVkiu.mjs.map +0 -1
package/package.json
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-contract-ts",
|
|
3
|
-
"version": "0.16.0-dev.
|
|
3
|
+
"version": "0.16.0-dev.33",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "SQL-specific TypeScript contract authoring surface for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/config": "0.16.0-dev.
|
|
10
|
-
"@prisma-next/contract": "0.16.0-dev.
|
|
11
|
-
"@prisma-next/contract-authoring": "0.16.0-dev.
|
|
12
|
-
"@prisma-next/framework-components": "0.16.0-dev.
|
|
13
|
-
"@prisma-next/sql-contract": "0.16.0-dev.
|
|
14
|
-
"@prisma-next/utils": "0.16.0-dev.
|
|
9
|
+
"@prisma-next/config": "0.16.0-dev.33",
|
|
10
|
+
"@prisma-next/contract": "0.16.0-dev.33",
|
|
11
|
+
"@prisma-next/contract-authoring": "0.16.0-dev.33",
|
|
12
|
+
"@prisma-next/framework-components": "0.16.0-dev.33",
|
|
13
|
+
"@prisma-next/sql-contract": "0.16.0-dev.33",
|
|
14
|
+
"@prisma-next/utils": "0.16.0-dev.33",
|
|
15
15
|
"arktype": "^2.2.2",
|
|
16
16
|
"pathe": "^2.0.3",
|
|
17
17
|
"ts-toolbelt": "^9.6.0"
|
|
18
18
|
},
|
|
19
19
|
"devDependencies": {
|
|
20
|
-
"@prisma-next/test-utils": "0.16.0-dev.
|
|
21
|
-
"@prisma-next/tsconfig": "0.16.0-dev.
|
|
20
|
+
"@prisma-next/test-utils": "0.16.0-dev.33",
|
|
21
|
+
"@prisma-next/tsconfig": "0.16.0-dev.33",
|
|
22
22
|
"@types/pg": "8.20.0",
|
|
23
23
|
"pg": "8.22.0",
|
|
24
|
-
"@prisma-next/tsdown": "0.16.0-dev.
|
|
24
|
+
"@prisma-next/tsdown": "0.16.0-dev.33",
|
|
25
25
|
"tsdown": "0.22.8",
|
|
26
26
|
"typescript": "5.9.3",
|
|
27
27
|
"vitest": "4.1.10"
|
package/src/build-contract.ts
CHANGED
|
@@ -36,7 +36,12 @@ import {
|
|
|
36
36
|
type ForeignKeyAuthoringInput,
|
|
37
37
|
materializeForeignKeysAndIndexes,
|
|
38
38
|
} from '@prisma-next/sql-contract/foreign-key-materialization';
|
|
39
|
-
import {
|
|
39
|
+
import {
|
|
40
|
+
type AuthoredIndexInput,
|
|
41
|
+
type ExactNameBodyWarning,
|
|
42
|
+
flushExactNameBodyWarnings,
|
|
43
|
+
lowerAuthoredIndex,
|
|
44
|
+
} from '@prisma-next/sql-contract/index-naming';
|
|
40
45
|
import { validateIndexTypes } from '@prisma-next/sql-contract/index-type-validation';
|
|
41
46
|
import {
|
|
42
47
|
createIndexTypeRegistry,
|
|
@@ -680,6 +685,10 @@ export function buildSqlContractFromDefinition(
|
|
|
680
685
|
);
|
|
681
686
|
|
|
682
687
|
const tablesByNamespace: Record<string, Record<string, StorageTableInput>> = {};
|
|
688
|
+
// Exact-name body warnings collect across the whole build and flush once
|
|
689
|
+
// (threshold-batched) — an adopted contract carries map: + body on many
|
|
690
|
+
// objects.
|
|
691
|
+
const exactNameBodyWarnings: ExactNameBodyWarning[] = [];
|
|
683
692
|
const modelNameToNamespaceId = new Map<string, string>();
|
|
684
693
|
const executionDefaults: ExecutionMutationDefault[] = [];
|
|
685
694
|
const modelsByNamespace: Record<string, Record<string, ContractModel>> = {};
|
|
@@ -921,13 +930,23 @@ export function buildSqlContractFromDefinition(
|
|
|
921
930
|
...ifDefined('name', u.name),
|
|
922
931
|
}));
|
|
923
932
|
const declaredIndexes = (semanticModel.indexes ?? []).map((i) =>
|
|
924
|
-
lowerAuthoredIndex(
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
933
|
+
lowerAuthoredIndex(
|
|
934
|
+
tableName,
|
|
935
|
+
// The blind cast defers the columns-xor-expression decision to
|
|
936
|
+
// lowerAuthoredIndex's runtime guard, which owns the diagnostic
|
|
937
|
+
// for the neither/both cases.
|
|
938
|
+
blindCast<AuthoredIndexInput, 'columns-xor-expression enforced by lowerAuthoredIndex'>({
|
|
939
|
+
...ifDefined('columns', i.columns),
|
|
940
|
+
...ifDefined('expression', i.expression),
|
|
941
|
+
where: i.where,
|
|
942
|
+
unique: i.unique,
|
|
943
|
+
map: i.map,
|
|
944
|
+
name: i.name,
|
|
945
|
+
type: i.type,
|
|
946
|
+
options: i.options,
|
|
947
|
+
}),
|
|
948
|
+
exactNameBodyWarnings,
|
|
949
|
+
),
|
|
931
950
|
);
|
|
932
951
|
const primaryKey = semanticModel.id
|
|
933
952
|
? { columns: semanticModel.id.columns, ...ifDefined('name', semanticModel.id.name) }
|
|
@@ -1334,6 +1353,7 @@ export function buildSqlContractFromDefinition(
|
|
|
1334
1353
|
};
|
|
1335
1354
|
|
|
1336
1355
|
assertStorageSemantics(definition, contract);
|
|
1356
|
+
flushExactNameBodyWarnings(exactNameBodyWarnings);
|
|
1337
1357
|
|
|
1338
1358
|
return contract;
|
|
1339
1359
|
}
|
|
@@ -55,15 +55,30 @@ export interface UniqueConstraintNode {
|
|
|
55
55
|
readonly name?: string;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
58
|
+
/** A definition-tree index's element structure — column tuple xor expression. */
|
|
59
|
+
export type IndexNodeElements =
|
|
60
|
+
| {
|
|
61
|
+
/** Column tuple. */
|
|
62
|
+
readonly columns: readonly string[];
|
|
63
|
+
readonly expression?: never;
|
|
64
|
+
}
|
|
65
|
+
| {
|
|
66
|
+
readonly columns?: never;
|
|
67
|
+
/** Opaque SQL: the entire element list of CREATE INDEX — never parsed. */
|
|
68
|
+
readonly expression: string;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export type IndexNode = IndexNodeElements & {
|
|
72
|
+
/** Opaque SQL: partial-index predicate (WHERE body, without the keyword). */
|
|
73
|
+
readonly where: string | undefined;
|
|
74
|
+
readonly unique: boolean | undefined;
|
|
75
|
+
/** Exact physical name (`map:`) — adopted verbatim, no wire hash. */
|
|
76
|
+
readonly map: string | undefined;
|
|
77
|
+
/** Managed wire-name prefix (`name:`) — lowers to `<name>_<8hex>`. */
|
|
78
|
+
readonly name: string | undefined;
|
|
79
|
+
readonly type: string | undefined;
|
|
80
|
+
readonly options: Record<string, unknown> | undefined;
|
|
81
|
+
};
|
|
67
82
|
|
|
68
83
|
export interface ForeignKeyNode {
|
|
69
84
|
readonly columns: readonly string[];
|
package/src/contract-dsl.ts
CHANGED
|
@@ -770,20 +770,39 @@ type ConstraintOptions<Name extends string | undefined = string | undefined> = {
|
|
|
770
770
|
|
|
771
771
|
export type IndexTypeMap = Record<string, { readonly options: unknown }>;
|
|
772
772
|
|
|
773
|
+
type IndexOptionsBase<Name extends string | undefined> = {
|
|
774
|
+
readonly name?: Name;
|
|
775
|
+
/** Exact physical name — adopted verbatim, no wire hash. Xor `name`. */
|
|
776
|
+
readonly map?: string;
|
|
777
|
+
/** Opaque SQL: partial-index predicate (WHERE body, without the keyword). */
|
|
778
|
+
readonly where?: string;
|
|
779
|
+
readonly unique?: boolean;
|
|
780
|
+
};
|
|
781
|
+
|
|
773
782
|
type IndexInput<
|
|
774
783
|
Name extends string | undefined,
|
|
775
784
|
IndexTypes extends IndexTypeMap,
|
|
776
785
|
> = keyof IndexTypes extends never
|
|
777
|
-
?
|
|
786
|
+
? IndexOptionsBase<Name>
|
|
778
787
|
:
|
|
779
|
-
| (
|
|
788
|
+
| (IndexOptionsBase<Name> & { readonly type?: never; readonly options?: never })
|
|
780
789
|
| {
|
|
781
|
-
readonly [K in keyof IndexTypes & string]:
|
|
790
|
+
readonly [K in keyof IndexTypes & string]: IndexOptionsBase<Name> & {
|
|
782
791
|
readonly type: K;
|
|
783
792
|
readonly options: IndexTypes[K]['options'];
|
|
784
793
|
};
|
|
785
794
|
}[keyof IndexTypes & string];
|
|
786
795
|
|
|
796
|
+
/**
|
|
797
|
+
* The expression overload's input: the whole CREATE INDEX element list as
|
|
798
|
+
* one opaque string. `name` or `map` is required — enforced at lowering
|
|
799
|
+
* with the same diagnostics as PSL.
|
|
800
|
+
*/
|
|
801
|
+
type ExpressionIndexInput<
|
|
802
|
+
Name extends string | undefined,
|
|
803
|
+
IndexTypes extends IndexTypeMap,
|
|
804
|
+
> = IndexInput<Name, IndexTypes> & { readonly expression: string };
|
|
805
|
+
|
|
787
806
|
type ForeignKeyOptions<Name extends string | undefined = string | undefined> =
|
|
788
807
|
ConstraintOptions<Name> & {
|
|
789
808
|
readonly onDelete?: 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';
|
|
@@ -811,13 +830,28 @@ export type UniqueConstraint<FieldNames extends readonly string[] = readonly str
|
|
|
811
830
|
readonly name?: string;
|
|
812
831
|
};
|
|
813
832
|
|
|
833
|
+
/** An authored index constraint's element structure — field tuple xor expression. */
|
|
834
|
+
export type IndexConstraintElements<FieldNames extends readonly string[] = readonly string[]> =
|
|
835
|
+
| {
|
|
836
|
+
/** Field-name tuple. */
|
|
837
|
+
readonly fields: FieldNames;
|
|
838
|
+
readonly expression?: never;
|
|
839
|
+
}
|
|
840
|
+
| {
|
|
841
|
+
readonly fields?: never;
|
|
842
|
+
/** Opaque SQL: the entire CREATE INDEX element list — never parsed. */
|
|
843
|
+
readonly expression: string;
|
|
844
|
+
};
|
|
845
|
+
|
|
814
846
|
export type IndexConstraint<
|
|
815
847
|
FieldNames extends readonly string[] = readonly string[],
|
|
816
848
|
Name extends string | undefined = string | undefined,
|
|
817
|
-
> = {
|
|
849
|
+
> = IndexConstraintElements<FieldNames> & {
|
|
818
850
|
readonly kind: 'index';
|
|
819
|
-
readonly
|
|
851
|
+
readonly where?: string;
|
|
852
|
+
readonly unique?: boolean;
|
|
820
853
|
readonly name?: Name;
|
|
854
|
+
readonly map?: string;
|
|
821
855
|
readonly type?: string;
|
|
822
856
|
readonly options?: Record<string, unknown>;
|
|
823
857
|
};
|
|
@@ -979,23 +1013,55 @@ function createConstraintsDsl<IndexTypes extends IndexTypeMap = Record<never, ne
|
|
|
979
1013
|
fields: { readonly [K in keyof FieldNames]: ColumnRef<FieldNames[K] & string> },
|
|
980
1014
|
options?: IndexInput<Name, IndexTypes>,
|
|
981
1015
|
): IndexConstraint<FieldNames, Name>;
|
|
1016
|
+
function index<Name extends string | undefined = undefined>(
|
|
1017
|
+
options: ExpressionIndexInput<Name, IndexTypes>,
|
|
1018
|
+
): IndexConstraint<never, Name>;
|
|
982
1019
|
function index(
|
|
983
|
-
|
|
1020
|
+
fieldsOrOptions:
|
|
1021
|
+
| ColumnRef
|
|
1022
|
+
| readonly ColumnRef[]
|
|
1023
|
+
| {
|
|
1024
|
+
readonly expression: string;
|
|
1025
|
+
readonly name?: string;
|
|
1026
|
+
readonly map?: string;
|
|
1027
|
+
readonly where?: string;
|
|
1028
|
+
readonly unique?: boolean;
|
|
1029
|
+
readonly type?: string;
|
|
1030
|
+
readonly options?: unknown;
|
|
1031
|
+
},
|
|
984
1032
|
options?: {
|
|
985
1033
|
readonly name?: string;
|
|
1034
|
+
readonly map?: string;
|
|
1035
|
+
readonly where?: string;
|
|
1036
|
+
readonly unique?: boolean;
|
|
986
1037
|
readonly type?: string;
|
|
987
1038
|
readonly options?: unknown;
|
|
988
1039
|
},
|
|
989
1040
|
): IndexConstraint {
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1041
|
+
const isExpressionForm =
|
|
1042
|
+
!Array.isArray(fieldsOrOptions) &&
|
|
1043
|
+
typeof fieldsOrOptions === 'object' &&
|
|
1044
|
+
'expression' in fieldsOrOptions;
|
|
1045
|
+
const opts = isExpressionForm ? fieldsOrOptions : options;
|
|
1046
|
+
const carried = {
|
|
1047
|
+
kind: 'index' as const,
|
|
1048
|
+
...(opts?.name !== undefined ? { name: opts.name } : {}),
|
|
1049
|
+
...(opts?.map !== undefined ? { map: opts.map } : {}),
|
|
1050
|
+
...(opts?.where !== undefined ? { where: opts.where } : {}),
|
|
1051
|
+
...(opts?.unique !== undefined ? { unique: opts.unique } : {}),
|
|
1052
|
+
...(opts?.type !== undefined ? { type: opts.type } : {}),
|
|
1053
|
+
...(opts?.options !== undefined
|
|
1054
|
+
? {
|
|
1055
|
+
options: blindCast<
|
|
1056
|
+
Record<string, unknown>,
|
|
1057
|
+
'the public overloads type options as the pack-declared options object; the loose implementation signature erases it to unknown'
|
|
1058
|
+
>(opts.options),
|
|
1059
|
+
}
|
|
997
1060
|
: {}),
|
|
998
1061
|
};
|
|
1062
|
+
return isExpressionForm
|
|
1063
|
+
? { ...carried, expression: fieldsOrOptions.expression }
|
|
1064
|
+
: { ...carried, fields: normalizeFieldRefInput(fieldsOrOptions) };
|
|
999
1065
|
}
|
|
1000
1066
|
|
|
1001
1067
|
function foreignKey<
|
|
@@ -1089,13 +1155,15 @@ type AttributeContext<Fields extends Record<string, ScalarFieldBuilder>> = {
|
|
|
1089
1155
|
readonly constraints: Pick<ConstraintsDsl, 'id' | 'unique'>;
|
|
1090
1156
|
};
|
|
1091
1157
|
|
|
1092
|
-
type PackAwareIndex<IndexTypes extends IndexTypeMap> =
|
|
1093
|
-
FieldNames extends readonly string[],
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1158
|
+
type PackAwareIndex<IndexTypes extends IndexTypeMap> = {
|
|
1159
|
+
<FieldNames extends readonly string[], Name extends string | undefined = undefined>(
|
|
1160
|
+
fields: { readonly [K in keyof FieldNames]: ColumnRef<FieldNames[K] & string> },
|
|
1161
|
+
options?: IndexInput<Name, IndexTypes>,
|
|
1162
|
+
): IndexConstraint<FieldNames, Name>;
|
|
1163
|
+
<Name extends string | undefined = undefined>(
|
|
1164
|
+
options: ExpressionIndexInput<Name, IndexTypes>,
|
|
1165
|
+
): IndexConstraint<never, Name>;
|
|
1166
|
+
};
|
|
1099
1167
|
|
|
1100
1168
|
type PackAwareSqlConstraints<IndexTypes extends IndexTypeMap> = {
|
|
1101
1169
|
readonly foreignKey: ConstraintsDsl['foreignKey'];
|
package/src/contract-lowering.ts
CHANGED
|
@@ -810,12 +810,26 @@ function resolveModelNode(
|
|
|
810
810
|
columns: mapFieldNamesToColumnNames(spec.modelName, unique.fields, spec.fieldToColumn),
|
|
811
811
|
...(unique.name ? { name: unique.name } : {}),
|
|
812
812
|
})) satisfies readonly UniqueConstraintNode[];
|
|
813
|
-
const indexes = (spec.sqlSpec?.indexes ?? []).map((index) =>
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
813
|
+
const indexes = (spec.sqlSpec?.indexes ?? []).map((index): IndexNode => {
|
|
814
|
+
const carried = {
|
|
815
|
+
where: index.where,
|
|
816
|
+
unique: index.unique,
|
|
817
|
+
name: index.name,
|
|
818
|
+
map: index.map,
|
|
819
|
+
type: index.type,
|
|
820
|
+
options: index.options,
|
|
821
|
+
};
|
|
822
|
+
return index.expression !== undefined
|
|
823
|
+
? { ...carried, expression: index.expression }
|
|
824
|
+
: {
|
|
825
|
+
...carried,
|
|
826
|
+
columns: mapFieldNamesToColumnNames(
|
|
827
|
+
spec.modelName,
|
|
828
|
+
index.fields ?? [],
|
|
829
|
+
spec.fieldToColumn,
|
|
830
|
+
),
|
|
831
|
+
};
|
|
832
|
+
});
|
|
819
833
|
const foreignKeys = resolveForeignKeyNodes(spec, allSpecs, extensions);
|
|
820
834
|
const relations = Object.entries(spec.relations).map(([relationName, relationBuilder]) =>
|
|
821
835
|
resolveRelationNode(relationName, relationBuilder.build(), spec, allSpecs, extensions),
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-contract-DbUeVkiu.mjs","names":[],"sources":["../src/contract-errors.ts","../src/build-contract.ts"],"sourcesContent":["import type { StructuredError, StructuredErrorOptions } from '@prisma-next/utils/structured-error';\nimport { structuredError } from '@prisma-next/utils/structured-error';\n\nexport type ContractCode = `CONTRACT.${ContractSubcode}`;\n\ntype ContractSubcode =\n | 'VALIDATION_FAILED'\n | 'NAME_DUPLICATE'\n | 'MODEL_UNKNOWN'\n | 'PACK_CONTRIBUTION_INVALID'\n | 'PACK_FAMILY_MISMATCH'\n | 'PACK_TARGET_MISMATCH'\n | 'PACK_REF_INVALID'\n | 'PACK_MISSING'\n | 'NAMESPACE_INVALID'\n | 'NAMESPACE_UNSUPPORTED'\n | 'NAMESPACE_UNKNOWN'\n | 'ARGUMENT_INVALID'\n | 'FOREIGN_KEY_INVALID'\n | 'RELATION_INVALID'\n | 'IDENTITY_INVALID'\n | 'CONSTRAINT_INVALID'\n | 'DEFAULT_INVALID'\n | 'ENUM_INVALID'\n | 'TYPE_UNKNOWN'\n | 'FIELD_UNKNOWN'\n | 'MODEL_TOKEN_INVALID'\n | 'MODULE_EXPORT_MISSING'\n | 'ENTITY_KIND_UNKNOWN'\n | 'ENTITY_KIND_INVALID'\n | 'TABLE_MISMATCH';\n\nexport function contractError(\n code: ContractCode,\n message: string,\n options?: StructuredErrorOptions,\n): StructuredError {\n return structuredError(code, message, options);\n}\n","import {\n computeExecutionHash,\n computeProfileHash,\n computeStorageHash,\n} from '@prisma-next/contract/hashing';\nimport {\n asNamespaceId,\n type ColumnDefault,\n type Contract,\n type ContractEnum,\n type ContractField,\n type ContractModel,\n type ContractRelation,\n type ContractRelationThrough,\n type ContractValueObject,\n type CrossReference,\n coreHash,\n crossRef,\n type ExecutionMutationDefault,\n type JsonValue,\n type StorageHashBase,\n type ValueSetRef,\n} from '@prisma-next/contract/types';\nimport { type CapabilityMatrix, mergeCapabilityMatrices } from '@prisma-next/contract-authoring';\nimport type {\n AuthoringContributions,\n AuthoringEntityTypeDescriptor,\n AuthoringEntityTypeNamespace,\n} from '@prisma-next/framework-components/authoring';\nimport { isAuthoringEntityTypeDescriptor } from '@prisma-next/framework-components/authoring';\nimport type { CodecLookup, ColumnTypeDescriptor } from '@prisma-next/framework-components/codec';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { sqlContractCanonicalizationHooks } from '@prisma-next/sql-contract/canonicalization-hooks';\nimport { tableEntityKind, valueSetEntityKind } from '@prisma-next/sql-contract/entity-kinds';\nimport {\n type ForeignKeyAuthoringInput,\n materializeForeignKeysAndIndexes,\n} from '@prisma-next/sql-contract/foreign-key-materialization';\nimport { lowerAuthoredIndex } from '@prisma-next/sql-contract/index-naming';\nimport { validateIndexTypes } from '@prisma-next/sql-contract/index-type-validation';\nimport {\n createIndexTypeRegistry,\n type IndexTypeMap,\n type IndexTypeRegistration,\n} from '@prisma-next/sql-contract/index-types';\nimport {\n applyFkDefaults,\n type CheckConstraintInput,\n type SqlNamespaceInput,\n SqlStorage,\n type SqlStorageInput,\n type StorageColumn,\n type StorageTableInput,\n type StorageTypeInstance,\n type StorageValueSetInput,\n toStorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { validateStorageSemantics } from '@prisma-next/sql-contract/validators';\nimport { deriveValueSetFromEntity } from '@prisma-next/sql-contract/value-set-derivation-hook';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { InternalError } from '@prisma-next/utils/internal-error';\nimport type {\n ContractDefinition,\n FieldNode,\n ModelNode,\n RelationNode,\n ValueObjectFieldNode,\n} from './contract-definition';\nimport { contractError } from './contract-errors';\n\ntype DomainFieldRef =\n | { readonly kind: 'scalar'; readonly many?: boolean }\n | { readonly kind: 'valueObject'; readonly name: string; readonly many?: boolean };\n\nfunction encodeViaCodec(value: unknown, codecId: string, codecLookup?: CodecLookup): JsonValue {\n const codec = codecLookup?.get(codecId);\n if (codec) {\n return codec.encodeJson(value);\n }\n return blindCast<\n JsonValue,\n 'no codec lookup at build time: literal/enum member value is already JSON-safe'\n >(value);\n}\n\nfunction encodeColumnDefault(\n defaultInput: ColumnDefault,\n codecId: string,\n codecLookup?: CodecLookup,\n many = false,\n): ColumnDefault {\n if (defaultInput.kind === 'function') {\n return { kind: 'function', expression: defaultInput.expression };\n }\n if (many) {\n if (!Array.isArray(defaultInput.value)) {\n throw new InternalError(\n `Literal default on a list column must be an array; received ${typeof defaultInput.value}. ` +\n 'A scalar default on a list field must be rejected at the authoring surface.',\n );\n }\n return {\n kind: 'literal',\n value: defaultInput.value.map((element) => encodeViaCodec(element, codecId, codecLookup)),\n };\n }\n return {\n kind: 'literal',\n value: encodeViaCodec(defaultInput.value, codecId, codecLookup),\n };\n}\n\nfunction assertStorageSemantics(\n definition: ContractDefinition,\n contract: Contract<SqlStorage>,\n): void {\n const semanticErrors = validateStorageSemantics(contract.storage);\n if (semanticErrors.length > 0) {\n throw contractError(\n 'CONTRACT.VALIDATION_FAILED',\n `Contract semantic validation failed: ${semanticErrors.join('; ')}`,\n { meta: { errors: semanticErrors } },\n );\n }\n\n const indexTypeRegistry = createIndexTypeRegistry();\n const packsToRegister: ReadonlyArray<{ readonly id?: string; readonly indexTypes?: unknown }> = [\n definition.target,\n ...Object.values(definition.extensions ?? {}),\n ];\n for (const pack of packsToRegister) {\n const registration = pack.indexTypes;\n if (registration === undefined) continue;\n if (\n typeof registration !== 'object' ||\n registration === null ||\n !Array.isArray((registration as { entries?: unknown }).entries)\n ) {\n throw contractError(\n 'CONTRACT.PACK_CONTRIBUTION_INVALID',\n `Pack \"${pack.id ?? '<unknown>'}\" declares \"indexTypes\" but its value is not an IndexTypeRegistration (expected an object with an \"entries\" array; got ${typeof registration}).`,\n { meta: { packId: pack.id, contribution: 'indexTypes', reason: 'invalid-shape' } },\n );\n }\n for (const entry of (registration as IndexTypeRegistration<IndexTypeMap>).entries) {\n indexTypeRegistry.register(entry);\n }\n }\n validateIndexTypes(contract, indexTypeRegistry);\n}\n\nfunction assertKnownTargetModel(\n modelsByName: ReadonlyMap<string, ModelNode>,\n modelsByCoordinate: ReadonlyMap<string, ModelNode>,\n sourceModelName: string,\n targetModelName: string,\n targetNamespaceId: string | undefined,\n context: string,\n): ModelNode {\n const targetModel =\n targetNamespaceId !== undefined && targetNamespaceId.length > 0\n ? modelsByCoordinate.get(`${targetNamespaceId}:${targetModelName}`)\n : modelsByName.get(targetModelName);\n if (!targetModel) {\n const qualified =\n targetNamespaceId !== undefined && targetNamespaceId.length > 0\n ? `${targetNamespaceId}.${targetModelName}`\n : targetModelName;\n throw contractError(\n 'CONTRACT.MODEL_UNKNOWN',\n `${context} on model \"${sourceModelName}\" references unknown model \"${qualified}\"`,\n { meta: { sourceModel: sourceModelName, targetModel: qualified, context } },\n );\n }\n return targetModel;\n}\n\nfunction assertTargetTableMatches(\n sourceModelName: string,\n targetModel: ModelNode,\n referencedTableName: string,\n context: string,\n): void {\n if (targetModel.tableName !== referencedTableName) {\n throw contractError(\n 'CONTRACT.TABLE_MISMATCH',\n `${context} on model \"${sourceModelName}\" references table \"${referencedTableName}\" but model \"${targetModel.modelName}\" maps to \"${targetModel.tableName}\"`,\n {\n meta: {\n sourceModel: sourceModelName,\n referencedTable: referencedTableName,\n mappedTable: targetModel.tableName,\n context,\n },\n },\n );\n }\n}\n\nfunction isValueObjectField(\n field: FieldNode | ValueObjectFieldNode,\n): field is ValueObjectFieldNode {\n return 'valueObjectName' in field;\n}\n\n/**\n * Resolves a deferred entity-ref column descriptor (e.g. a `pg.enum(handle)`\n * column) against the field's now-known owning namespace: attaches the\n * storage `valueSet` ref the collected entity's derived value-set is stored\n * under. `nativeType` / `typeParams.typeName` stay bare here — schema\n * qualification (e.g. `auth.aal_level`) is a target concern applied in the\n * next step, `qualifyColumnDescriptor`. A descriptor with no `entityRef` (the\n * ordinary case) passes through unchanged.\n */\nfunction resolveEntityRefDescriptor(\n descriptor: ColumnTypeDescriptor,\n namespaceId: string,\n): ColumnTypeDescriptor {\n const entityRef = descriptor.entityRef;\n if (entityRef === undefined) return descriptor;\n\n return {\n ...descriptor,\n valueSet: {\n plane: 'storage',\n entityKind: 'valueSet',\n namespaceId,\n entityName: entityRef.entityName,\n },\n };\n}\n\n/**\n * A target's contract-construction-time column-type qualifier, contributed\n * through `target.authoring.qualifyColumnType`. Given a column's bare type\n * info and its owning `namespaceId`, it returns the type info the target's\n * schema semantics require (e.g. Postgres schema-qualifies a native-enum\n * column's type name to `auth.aal_level`). The dispatch keys off the codec\n * id, so every codec — including ones needing no change — is passed through\n * and the caller stays codec-blind. Targets without the hook leave every\n * column bare.\n */\ntype ColumnTypeQualifier = (\n input: {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n },\n namespaceId: string,\n) => { readonly nativeType: string; readonly typeParams?: Record<string, unknown> };\n\n/**\n * Structural check for a target that contributes a `qualifyColumnType` hook\n * on its authoring contributions. Duck-typed (mirroring\n * `contract-psl`'s `hasColumnFromEntityHook`) so the SQL family stays blind\n * to the target's qualification logic and no framework/family interface has\n * to name the hook.\n */\nfunction hasColumnTypeQualifier(\n authoring: AuthoringContributions,\n): authoring is AuthoringContributions & { readonly qualifyColumnType: ColumnTypeQualifier } {\n return 'qualifyColumnType' in authoring && typeof authoring.qualifyColumnType === 'function';\n}\n\nfunction resolveColumnTypeQualifier(\n target: ContractDefinition['target'],\n): ColumnTypeQualifier | undefined {\n const authoring = target.authoring;\n if (authoring === undefined) return undefined;\n return hasColumnTypeQualifier(authoring) ? authoring.qualifyColumnType : undefined;\n}\n\n/**\n * Applies the target's `qualifyColumnType` hook to a scalar column descriptor\n * at construction, so the storage column and the domain field (which derives\n * its `type.typeParams` from the storage column) are both built already\n * qualified in a single pass. A descriptor whose codec the target leaves\n * unchanged passes through untouched.\n */\nfunction qualifyColumnDescriptor(\n descriptor: ColumnTypeDescriptor,\n namespaceId: string,\n qualify: ColumnTypeQualifier | undefined,\n): ColumnTypeDescriptor {\n if (qualify === undefined) return descriptor;\n const qualified = qualify(\n {\n codecId: descriptor.codecId,\n nativeType: descriptor.nativeType,\n ...ifDefined('typeParams', descriptor.typeParams),\n },\n namespaceId,\n );\n if (\n qualified.nativeType === descriptor.nativeType &&\n qualified.typeParams === descriptor.typeParams\n ) {\n return descriptor;\n }\n return {\n ...descriptor,\n nativeType: qualified.nativeType,\n ...ifDefined('typeParams', qualified.typeParams),\n };\n}\n\ntype CollectedColumnEntities = Record<string, Record<string, Record<string, unknown>>>;\n\n/**\n * Records a deferred column's entity-ref into the namespace-scoped collection\n * accumulator (`namespaceId → entityKind → entityName`) — folded into the same\n * namespace assembly `deriveEntityValueSets`/`entries.<kind>` step as the\n * entities-channel attachments, so a column-collected entity gets its\n * value-set the same way an entities-channel one does.\n *\n * The same handle reused by many columns in one namespace is normal (a native\n * enum type backs any number of columns) and records the identical entity once.\n * Two *different* entity instances sharing a name+kind in one namespace is a\n * name collision — the emitted `entries.valueSet.<name>` could only reflect one\n * of them, silently mismatching the other column's type/cast. PSL hard-errors\n * on the equivalent (`PSL_DUPLICATE_DECLARATION`); the TS path rejects it too.\n */\nfunction collectEntityFromColumn(\n collected: CollectedColumnEntities,\n namespaceId: string,\n entityRef: NonNullable<ColumnTypeDescriptor['entityRef']>,\n): void {\n const forNs = collected[namespaceId] ?? {};\n const forKind = forNs[entityRef.entityKind] ?? {};\n const existing = forKind[entityRef.entityName];\n if (existing !== undefined && existing !== entityRef.entity) {\n throw contractError(\n 'CONTRACT.NAME_DUPLICATE',\n `buildSqlContractFromDefinition: two different \"${entityRef.entityKind}\" entities named \"${entityRef.entityName}\" in namespace \"${namespaceId}\" — pack-entity names must be unique per namespace.`,\n { meta: { kind: entityRef.entityKind, name: entityRef.entityName, namespaceId } },\n );\n }\n forKind[entityRef.entityName] = entityRef.entity;\n forNs[entityRef.entityKind] = forKind;\n collected[namespaceId] = forNs;\n}\n\n/**\n * Merges a namespace's entities-channel attachments (lowered from the\n * `entities` handle list, carried on `ContractDefinition.attachedEntities`)\n * with the entities collected from that namespace's deferred entity-ref\n * columns. A column-collected entity that shadows a *different* attached\n * entity of the same kind+name (or vice-versa) is the same name-collision bug\n * `collectEntityFromColumn` guards against across columns, so it is rejected\n * the same way — by entity identity, so the same handle attached and used by\n * a column does not throw.\n */\nfunction mergeColumnAndAttachedEntities(\n namespaceId: string,\n attached: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined,\n columnCollected: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined,\n): Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined {\n if (attached === undefined) return columnCollected;\n if (columnCollected === undefined) return attached;\n const kinds = new Set([...Object.keys(attached), ...Object.keys(columnCollected)]);\n const result: Record<string, Readonly<Record<string, unknown>>> = {};\n for (const kind of kinds) {\n const attachedForKind = attached[kind];\n const columnForKind = columnCollected[kind];\n for (const [name, entity] of Object.entries(columnForKind ?? {})) {\n const existing = attachedForKind?.[name];\n if (existing !== undefined && existing !== entity) {\n throw contractError(\n 'CONTRACT.NAME_DUPLICATE',\n `buildSqlContractFromDefinition: two different \"${kind}\" entities named \"${name}\" in namespace \"${namespaceId}\" — a column-referenced entity conflicts with an attached one; pack-entity names must be unique per namespace.`,\n { meta: { kind, name, namespaceId } },\n );\n }\n }\n result[kind] = { ...attachedForKind, ...columnForKind };\n }\n return result;\n}\n\nconst JSONB_CODEC_ID = 'pg/jsonb@1';\nconst JSONB_NATIVE_TYPE = 'jsonb';\n\nfunction resolveModelNamespaceId(\n model: ModelNode,\n modelNameToNamespaceId: ReadonlyMap<string, string>,\n defaultNamespaceId: string,\n): string {\n if (model.namespaceId !== undefined && model.namespaceId.length > 0) {\n return model.namespaceId;\n }\n return modelNameToNamespaceId.get(model.modelName) ?? defaultNamespaceId;\n}\n\nfunction buildThroughDescriptor(\n through: NonNullable<RelationNode['through']>,\n tableNamespaceByName: ReadonlyMap<string, string>,\n targetModel: ModelNode,\n modelName: string,\n fieldName: string,\n defaultNamespaceId: string,\n): ContractRelationThrough {\n if (!tableNamespaceByName.has(through.table)) {\n throw contractError(\n 'CONTRACT.MODEL_UNKNOWN',\n `buildSqlContractFromDefinition: junction table \"${through.table}\" for relation \"${modelName}.${fieldName}\" is not a declared model.`,\n { meta: { sourceModel: modelName, relationName: fieldName, junctionTable: through.table } },\n );\n }\n // Junction table names are unique per namespace, not globally. Prefer the\n // junction's own declared namespace (carried on the through node); fall back to\n // the target's default namespace. Resolving by bare table name would pick the\n // wrong namespace when the same junction table name exists in two namespaces.\n const namespaceId = through.namespaceId ?? defaultNamespaceId;\n\n return {\n table: through.table,\n namespaceId,\n parentColumns: through.parentColumns,\n childColumns: through.childColumns,\n targetColumns: targetColumnsForJunction(targetModel, fieldName),\n };\n}\n\nfunction targetColumnsForJunction(targetModel: ModelNode, fieldName: string): readonly string[] {\n const primaryKeyColumns = targetModel.id?.columns;\n if (primaryKeyColumns && primaryKeyColumns.length > 0) {\n return primaryKeyColumns;\n }\n const firstUnique = targetModel.uniques?.find((u) => u.columns.length > 0);\n if (firstUnique) {\n return firstUnique.columns;\n }\n throw contractError(\n 'CONTRACT.IDENTITY_INVALID',\n `M:N target model \"${targetModel.modelName}\" (relation field \"${fieldName}\") has no primary id or unique key to derive junction targetColumns.`,\n { meta: { modelName: targetModel.modelName, reason: 'no-key-for-junction-target-columns' } },\n );\n}\n\nfunction buildStorageColumn(\n field: FieldNode | ValueObjectFieldNode,\n storageValueSetRef: ValueSetRef | undefined,\n codecLookup?: CodecLookup,\n): StorageColumn {\n if (isValueObjectField(field)) {\n const encodedDefault =\n field.default !== undefined\n ? encodeColumnDefault(field.default, JSONB_CODEC_ID, codecLookup)\n : undefined;\n\n return {\n nativeType: JSONB_NATIVE_TYPE,\n codecId: JSONB_CODEC_ID,\n nullable: field.nullable,\n ...ifDefined('default', encodedDefault),\n };\n }\n\n const codecId = field.descriptor.codecId;\n const encodedDefault =\n field.default !== undefined\n ? encodeColumnDefault(field.default, codecId, codecLookup, field.many === true)\n : undefined;\n\n // `storageValueSetRef` (derived from an `enumTypeHandle`) takes precedence\n // when present — the established domain-enum path. `field.descriptor.valueSet`\n // is the fallback: set by an entity-ref type constructor (e.g. `pg.enum(Ref)`)\n // that resolved the field's type against a value-set-deriving entity with no\n // domain enum involved. A field carries at most one of the two in practice.\n const valueSet = storageValueSetRef ?? field.descriptor.valueSet;\n\n return {\n nativeType: field.descriptor.nativeType,\n codecId,\n nullable: field.nullable,\n ...(field.many ? { many: true as const } : {}),\n ...ifDefined('typeParams', field.descriptor.typeParams),\n ...ifDefined('default', encodedDefault),\n ...ifDefined('typeRef', field.descriptor.typeRef),\n ...ifDefined('valueSet', valueSet),\n };\n}\n\nfunction buildDomainField(\n field: FieldNode | ValueObjectFieldNode,\n column: StorageColumn,\n domainValueSetRef: ValueSetRef | undefined,\n): ContractField {\n if (isValueObjectField(field)) {\n return {\n type: { kind: 'valueObject', name: field.valueObjectName },\n nullable: field.nullable,\n ...(field.many ? { many: true } : {}),\n };\n }\n\n return {\n type: {\n kind: 'scalar',\n codecId: column.codecId,\n ...ifDefined('typeParams', column.typeParams),\n },\n nullable: column.nullable,\n ...(field.many ? { many: true } : {}),\n ...ifDefined('valueSet', domainValueSetRef),\n };\n}\n\nfunction collectStorageNamespaceCoordinateIds(definition: ContractDefinition): Set<string> {\n const ids = new Set<string>();\n ids.add(definition.target.defaultNamespaceId);\n for (const id of definition.namespaces ?? []) {\n if (id.length > 0) {\n ids.add(id);\n }\n }\n for (const model of definition.models) {\n if (model.namespaceId !== undefined && model.namespaceId.length > 0) {\n ids.add(model.namespaceId);\n }\n }\n for (const id of Object.keys(definition.attachedEntities ?? {})) {\n if (id.length > 0) {\n ids.add(id);\n }\n }\n return ids;\n}\n\n/**\n * Entry kinds the framework assembler itself manages (`table` from models,\n * `valueSet` from `enums` and attached-entity value-set derivation). A\n * pack-attached entity claiming one of these would silently clobber or be\n * clobbered by the managed slot, so it is rejected outright.\n */\nconst MANAGED_ENTRY_KINDS = new Set([tableEntityKind.kind, valueSetEntityKind.kind]);\n\nfunction assertNoManagedEntityKinds(\n namespaceId: string,\n entitiesForNs: Readonly<Record<string, unknown>> | undefined,\n): void {\n if (entitiesForNs === undefined) return;\n for (const kind of Object.keys(entitiesForNs)) {\n if (MANAGED_ENTRY_KINDS.has(kind)) {\n throw contractError(\n 'CONTRACT.ENTITY_KIND_INVALID',\n `buildSqlContractFromDefinition: attached entity in namespace \"${namespaceId}\" declares entry kind \"${kind}\", which is managed by the framework (table/valueSet) and cannot be attached.`,\n { meta: { entityKind: kind, namespaceId } },\n );\n }\n }\n}\n\n/**\n * Walks the flat `entityTypes` namespace tree contributed by the target pack\n * and every extension pack, indexing descriptors by their `discriminator` —\n * the same string a pack entity's entries-map key (`entries.<kind>`) uses.\n * Mirrors `contract-psl`'s `buildEntityTypesByDiscriminator`, recomposed here\n * from the packs `ContractDefinition` already carries (`target` +\n * `extensions`) since the TS assembler has no single pre-merged\n * `AuthoringContributions` input to read the way the PSL interpreter does.\n */\nfunction collectEntityTypeDescriptorsByDiscriminator(\n definition: ContractDefinition,\n): ReadonlyMap<string, AuthoringEntityTypeDescriptor> {\n const result = new Map<string, AuthoringEntityTypeDescriptor>();\n const walk = (namespace: AuthoringEntityTypeNamespace): void => {\n for (const value of Object.values(namespace)) {\n if (isAuthoringEntityTypeDescriptor(value)) {\n result.set(value.discriminator, value);\n } else {\n walk(value);\n }\n }\n };\n const components = [definition.target, ...Object.values(definition.extensions ?? {})];\n for (const component of components) {\n const entityTypes = component.authoring?.entityTypes;\n if (entityTypes !== undefined) {\n walk(entityTypes);\n }\n }\n return result;\n}\n\n/**\n * Derives value-sets for every pack entity declared in one namespace,\n * reusing the same `SqlValueSetDerivingEntityTypeOutput.deriveValueSet` hook\n * `contract-psl`'s `lowerExtensionBlocksForNamespace` folds into\n * `entries.valueSet` on the PSL path — so a TS-attached entity (e.g. a\n * native enum) gets its value-set the same way. Entity kinds with no\n * registered descriptor, or whose descriptor output doesn't derive a\n * value-set, contribute nothing.\n */\nfunction deriveEntityValueSets(\n entitiesForNs: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined,\n entityTypesByDiscriminator: ReadonlyMap<string, AuthoringEntityTypeDescriptor>,\n): Record<string, StorageValueSetInput> | undefined {\n if (entitiesForNs === undefined) return undefined;\n let result: Record<string, StorageValueSetInput> | undefined;\n for (const [kind, entitiesByName] of Object.entries(entitiesForNs)) {\n const descriptor = entityTypesByDiscriminator.get(kind);\n if (descriptor === undefined) continue;\n for (const [name, entity] of Object.entries(entitiesByName)) {\n const derivedValueSet = deriveValueSetFromEntity(descriptor.output, entity);\n if (derivedValueSet === undefined) continue;\n result ??= {};\n result[name] = derivedValueSet;\n }\n }\n return result;\n}\n\n/**\n * Merges a namespace's `enumType()`-derived value-sets with its pack-entity-\n * derived value-sets. Both land in the same `entries.valueSet[name]` slot —\n * which drives value-set → codec typing and the domain-enum CHECK — so a\n * same-named entry in both would let one silently overwrite the other and\n * corrupt whichever column resolves against it. The same collision class the\n * `mergeColumnAndAttachedEntities` guard rejects; the PSL path already hard-errors\n * on the equivalent (`interpretPslDocumentToSqlContract`). Reject it here too.\n */\nfunction mergeNamespaceValueSets(\n namespaceId: string,\n enumValueSets: Record<string, StorageValueSetInput> | undefined,\n packValueSets: Record<string, StorageValueSetInput> | undefined,\n): Record<string, StorageValueSetInput> {\n if (enumValueSets !== undefined && packValueSets !== undefined) {\n for (const name of Object.keys(packValueSets)) {\n if (Object.hasOwn(enumValueSets, name)) {\n throw contractError(\n 'CONTRACT.NAME_DUPLICATE',\n `buildSqlContractFromDefinition: value-set \"${name}\" in namespace \"${namespaceId}\" is derived from both an enum and a pack entity — names must be unique per namespace.`,\n { meta: { kind: 'valueSet', name, namespaceId } },\n );\n }\n }\n }\n return { ...enumValueSets, ...packValueSets };\n}\n\nfunction ensureUnboundNamespaceSlot(\n namespaces: SqlStorageInput['namespaces'],\n createNamespace: ContractDefinition['createNamespace'],\n): SqlStorageInput['namespaces'] {\n if (Object.hasOwn(namespaces, UNBOUND_NAMESPACE_ID)) {\n return namespaces;\n }\n const unboundInput: SqlNamespaceInput = {\n id: UNBOUND_NAMESPACE_ID,\n entries: { table: {} },\n };\n const unbound = createNamespace(unboundInput);\n return {\n [UNBOUND_NAMESPACE_ID]: unbound,\n ...namespaces,\n };\n}\n\nexport function buildSqlContractFromDefinition(\n definition: ContractDefinition,\n codecLookup?: CodecLookup,\n): Contract<SqlStorage> {\n const target = definition.target.targetId;\n const defaultNamespaceId = definition.target.defaultNamespaceId;\n const qualifyColumnType = resolveColumnTypeQualifier(definition.target);\n const targetFamily = 'sql';\n const resolveNamespaceId = (m: ModelNode): string =>\n m.namespaceId !== undefined && m.namespaceId.length > 0 ? m.namespaceId : defaultNamespaceId;\n const modelsByName = new Map(definition.models.map((m) => [m.modelName, m]));\n const tableNamespaceByName = new Map(\n definition.models.map((m) => [\n m.tableName,\n m.namespaceId !== undefined && m.namespaceId.length > 0 ? m.namespaceId : defaultNamespaceId,\n ]),\n );\n const modelsByCoordinate = new Map(\n definition.models.map((m) => [`${resolveNamespaceId(m)}:${m.modelName}`, m]),\n );\n\n const tablesByNamespace: Record<string, Record<string, StorageTableInput>> = {};\n const modelNameToNamespaceId = new Map<string, string>();\n const executionDefaults: ExecutionMutationDefault[] = [];\n const modelsByNamespace: Record<string, Record<string, ContractModel>> = {};\n const collectedColumnEntities: CollectedColumnEntities = {};\n const rootEntries: Array<{\n readonly tableName: string;\n readonly namespaceId: string;\n readonly ref: CrossReference;\n }> = [];\n\n for (const semanticModel of definition.models) {\n const tableName = semanticModel.tableName;\n const namespaceId =\n semanticModel.namespaceId !== undefined && semanticModel.namespaceId.length > 0\n ? semanticModel.namespaceId\n : defaultNamespaceId;\n modelNameToNamespaceId.set(semanticModel.modelName, namespaceId);\n // STI variants share the base table; the base model already owns this\n // table name and its root, so the variant contributes neither.\n if (!semanticModel.sharesBaseTable) {\n rootEntries.push({\n tableName,\n namespaceId,\n ref: crossRef(semanticModel.modelName, namespaceId),\n });\n }\n\n // --- Build storage table ---\n\n const columns: Record<string, StorageColumn> = {};\n const fieldToColumn: Record<string, string> = {};\n const domainFields: Record<string, ContractField> = {};\n const domainFieldRefs: Record<string, DomainFieldRef> = {};\n const checksForTable: CheckConstraintInput[] = [];\n\n for (const field of semanticModel.fields) {\n const executionDefaultPhases =\n field.executionDefaults?.onCreate || field.executionDefaults?.onUpdate\n ? field.executionDefaults\n : undefined;\n if (executionDefaultPhases) {\n if (field.default !== undefined) {\n throw contractError(\n 'CONTRACT.DEFAULT_INVALID',\n `Field \"${semanticModel.modelName}.${field.fieldName}\" cannot define both default and executionDefaults.`,\n {\n meta: {\n modelName: semanticModel.modelName,\n fieldName: field.fieldName,\n reason: 'default-and-executionDefaults',\n },\n },\n );\n }\n if (field.nullable) {\n throw contractError(\n 'CONTRACT.DEFAULT_INVALID',\n `Field \"${semanticModel.modelName}.${field.fieldName}\" cannot be nullable when executionDefaults are present.`,\n {\n meta: {\n modelName: semanticModel.modelName,\n fieldName: field.fieldName,\n reason: 'nullable-with-executionDefaults',\n },\n },\n );\n }\n }\n\n const enumHandle = !isValueObjectField(field) ? field.enumTypeHandle : undefined;\n // Authored enums are always registered under the contract's defaultNamespaceId\n // (see the enum registration loop below), so refs must point there regardless\n // of which namespace the consuming model lives in.\n const storageValueSetRef: ValueSetRef | undefined =\n enumHandle !== undefined\n ? {\n plane: 'storage',\n entityKind: 'valueSet',\n namespaceId: defaultNamespaceId,\n entityName: enumHandle.enumName,\n }\n : undefined;\n const domainValueSetRef: ValueSetRef | undefined =\n enumHandle !== undefined\n ? {\n plane: 'domain',\n entityKind: 'enum',\n namespaceId: defaultNamespaceId,\n entityName: enumHandle.enumName,\n }\n : undefined;\n\n // A field authored through a deferred entity-ref column helper (e.g.\n // `pg.enum(handle)`) carries `descriptor.entityRef`: the referenced\n // entity is collected into `collectedColumnEntities` (folded into the\n // same `entries.<kind>` + `entries.valueSet` assembly an entities-channel\n // attachment goes through) and the descriptor is resolved\n // against this field's now-known `namespaceId` — the builder call that\n // produced it ran before the enclosing model associated one. The\n // descriptor is then handed to the target's `qualifyColumnType` hook,\n // which schema-qualifies a native-enum column's type name for its\n // namespace. Keying off the codec id (inside the hook) catches both the\n // TS `pg.enum(handle)` path (via `entityRef`) and the PSL `pg.enum(Ref)`\n // path (resolved inline in the interpreter, no `entityRef`). Because the\n // storage column is built from this qualified descriptor and the domain\n // field derives its `type.typeParams` from that column, both come out\n // qualified in this single pass.\n let resolvedField: FieldNode | ValueObjectFieldNode = field;\n if (!isValueObjectField(field)) {\n let descriptor = field.descriptor;\n const entityRef = descriptor.entityRef;\n if (entityRef !== undefined) {\n collectEntityFromColumn(collectedColumnEntities, namespaceId, entityRef);\n descriptor = resolveEntityRefDescriptor(descriptor, namespaceId);\n }\n descriptor = qualifyColumnDescriptor(descriptor, namespaceId, qualifyColumnType);\n if (descriptor !== field.descriptor) {\n resolvedField = { ...field, descriptor };\n }\n }\n\n const column = buildStorageColumn(resolvedField, storageValueSetRef, codecLookup);\n columns[field.columnName] = column;\n fieldToColumn[field.fieldName] = field.columnName;\n\n // A domain enum (`storageValueSetRef`, from an `enumType()` handle) is\n // stored as a plain scalar column (`text`, `int4`, …) with no native\n // type of its own to enforce membership, so it needs an explicit\n // CHECK — scalar or array, since a `text[]` array has no element-level\n // enforcement either. A value set resolved by an entity-ref type\n // constructor (`field.descriptor.valueSet`, e.g. `pg.enum(Ref)`) binds\n // the column to a codec/native-type pairing that IS the storage-level\n // enforcement (a Postgres native enum type, or another target's\n // equivalent) — including array columns, since the target enforces\n // membership on every element of a native-typed array — so no CHECK\n // for those.\n if (column.valueSet !== undefined && storageValueSetRef !== undefined) {\n checksForTable.push({\n name: `${tableName}_${field.columnName}_check`,\n column: field.columnName,\n valueSet: column.valueSet,\n });\n }\n\n domainFields[field.fieldName] = buildDomainField(field, column, domainValueSetRef);\n\n if (isValueObjectField(field)) {\n domainFieldRefs[field.fieldName] = {\n kind: 'valueObject',\n name: field.valueObjectName,\n ...(field.many ? { many: true } : {}),\n };\n } else if (field.many) {\n domainFieldRefs[field.fieldName] = { kind: 'scalar', many: true };\n }\n\n if (executionDefaultPhases) {\n executionDefaults.push({\n ref: { namespace: namespaceId, table: tableName, column: field.columnName },\n ...ifDefined('onCreate', executionDefaultPhases.onCreate),\n ...ifDefined('onUpdate', executionDefaultPhases.onUpdate),\n });\n }\n }\n\n const authoringForeignKeys: readonly ForeignKeyAuthoringInput[] = (\n semanticModel.foreignKeys ?? []\n ).map((fk) => {\n if (fk.references.spaceId !== undefined) {\n // Cross-space FK: the target lives in a different contract space.\n // Skip local model lookup and carry the spaceId coordinate through.\n const targetNamespaceId = fk.references.namespaceId ?? defaultNamespaceId;\n return {\n source: { namespaceId: asNamespaceId(namespaceId), tableName, columns: fk.columns },\n target: {\n namespaceId: asNamespaceId(targetNamespaceId),\n tableName: fk.references.table,\n columns: fk.references.columns,\n spaceId: fk.references.spaceId,\n },\n ...applyFkDefaults(\n {\n ...ifDefined('constraint', fk.constraint),\n ...ifDefined('index', fk.index),\n },\n definition.foreignKeyDefaults,\n ),\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n };\n }\n\n const targetModel = assertKnownTargetModel(\n modelsByName,\n modelsByCoordinate,\n semanticModel.modelName,\n fk.references.model,\n fk.references.namespaceId,\n 'Foreign key',\n );\n assertTargetTableMatches(\n semanticModel.modelName,\n targetModel,\n fk.references.table,\n 'Foreign key',\n );\n const targetNamespaceId =\n fk.references.namespaceId ??\n (targetModel.namespaceId !== undefined && targetModel.namespaceId.length > 0\n ? targetModel.namespaceId\n : defaultNamespaceId);\n return {\n source: { namespaceId: asNamespaceId(namespaceId), tableName, columns: fk.columns },\n target: {\n namespaceId: asNamespaceId(targetNamespaceId),\n tableName: fk.references.table,\n columns: fk.references.columns,\n },\n ...applyFkDefaults(\n {\n ...ifDefined('constraint', fk.constraint),\n ...ifDefined('index', fk.index),\n },\n definition.foreignKeyDefaults,\n ),\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n };\n });\n\n // STI variants share the base table: their columns are already\n // materialised onto the base `ModelNode`, so the variant builds a domain\n // model (below) but no storage table of its own.\n if (!semanticModel.sharesBaseTable) {\n const uniques = (semanticModel.uniques ?? []).map((u) => ({\n columns: u.columns,\n ...ifDefined('name', u.name),\n }));\n const declaredIndexes = (semanticModel.indexes ?? []).map((i) =>\n lowerAuthoredIndex(tableName, {\n columns: i.columns,\n map: i.map,\n name: i.name,\n type: i.type,\n options: i.options,\n }),\n );\n const primaryKey = semanticModel.id\n ? { columns: semanticModel.id.columns, ...ifDefined('name', semanticModel.id.name) }\n : undefined;\n // FK1: lower each FK's `constraint`/`index` authoring intent into\n // discrete persisted entities here — the one place a table's full\n // constraint context (its own declared indexes/uniques/primary key)\n // is available. A `constraint: false` FK contributes no\n // `foreignKeys[]` entry; an `index: true` FK not already backed by a\n // declared index/unique/primary-key contributes a named `indexes[]`\n // entry. This authoring pipeline is shared by both the TS DSL and the\n // PSL interpreter (which calls `buildSqlContractFromDefinition`\n // directly), so both authoring surfaces materialize identically.\n const { foreignKeys, indexes } = materializeForeignKeysAndIndexes(\n tableName,\n authoringForeignKeys,\n declaredIndexes,\n uniques,\n primaryKey,\n );\n\n const tableInput: StorageTableInput = {\n columns,\n ...ifDefined('control', semanticModel.control),\n uniques,\n indexes,\n foreignKeys,\n ...(primaryKey ? { primaryKey } : {}),\n ...(checksForTable.length > 0 ? { checks: checksForTable } : {}),\n };\n\n let nsTables = tablesByNamespace[namespaceId];\n if (nsTables === undefined) {\n nsTables = {};\n tablesByNamespace[namespaceId] = nsTables;\n }\n if (nsTables[tableName] !== undefined) {\n throw contractError(\n 'CONTRACT.NAME_DUPLICATE',\n `buildSqlContractFromDefinition: duplicate table \"${tableName}\" in namespace \"${namespaceId}\".`,\n { meta: { kind: 'table', name: tableName, namespaceId } },\n );\n }\n nsTables[tableName] = tableInput;\n }\n\n // --- Build contract model ---\n\n const storageFields: Record<string, { readonly column: string }> = {};\n for (const [fieldName, columnName] of Object.entries(fieldToColumn)) {\n storageFields[fieldName] = { column: columnName };\n }\n\n const columnToField = new Map(\n Object.entries(fieldToColumn).map(([field, col]) => [col, field]),\n );\n const modelRelations: Record<string, ContractRelation> = {};\n for (const relation of semanticModel.relations ?? []) {\n // Cross-space relations have `spaceId` set — the target model lives in\n // a different contract space, so skip local model lookup and validation.\n if (relation.spaceId !== undefined) {\n const targetNamespaceId = relation.namespaceId ?? defaultNamespaceId;\n modelRelations[relation.fieldName] = {\n to: crossRef(relation.toModel, targetNamespaceId, relation.spaceId),\n // Cross-space belongsTo relations are always N:1 (the FK-owning side).\n cardinality: 'N:1',\n on: {\n localFields: relation.on.parentColumns.map((col) => columnToField.get(col) ?? col),\n // For cross-space targets the lowering carries field names directly\n // (no fieldToColumn map available for the remote model).\n targetFields: relation.on.childColumns,\n },\n };\n continue;\n }\n\n const targetModel = assertKnownTargetModel(\n modelsByName,\n modelsByCoordinate,\n semanticModel.modelName,\n relation.toModel,\n relation.toNamespaceId,\n 'Relation',\n );\n assertTargetTableMatches(semanticModel.modelName, targetModel, relation.toTable, 'Relation');\n\n const targetColumnToField = new Map(\n targetModel.fields.map((f) => [f.columnName, f.fieldName]),\n );\n\n const to = crossRef(\n relation.toModel,\n relation.toNamespaceId !== undefined && relation.toNamespaceId.length > 0\n ? relation.toNamespaceId\n : resolveModelNamespaceId(targetModel, modelNameToNamespaceId, defaultNamespaceId),\n );\n const on = {\n localFields: relation.on.parentColumns.map((col) => columnToField.get(col) ?? col),\n targetFields: relation.on.childColumns.map((col) => targetColumnToField.get(col) ?? col),\n };\n\n if (relation.cardinality === 'N:M') {\n if (!relation.through) {\n throw contractError(\n 'CONTRACT.RELATION_INVALID',\n `Relation \"${semanticModel.modelName}.${relation.fieldName}\" with cardinality \"N:M\" requires through metadata`,\n {\n meta: {\n modelName: semanticModel.modelName,\n relationName: relation.fieldName,\n reason: 'many-to-many-missing-through',\n },\n },\n );\n }\n modelRelations[relation.fieldName] = {\n to,\n cardinality: 'N:M',\n on,\n through: buildThroughDescriptor(\n relation.through,\n tableNamespaceByName,\n targetModel,\n semanticModel.modelName,\n relation.fieldName,\n defaultNamespaceId,\n ),\n };\n } else {\n modelRelations[relation.fieldName] = { to, cardinality: relation.cardinality, on };\n }\n }\n\n let namespaceModels = modelsByNamespace[namespaceId];\n if (namespaceModels === undefined) {\n namespaceModels = {};\n modelsByNamespace[namespaceId] = namespaceModels;\n }\n namespaceModels[semanticModel.modelName] = {\n storage: {\n table: tableName,\n namespaceId,\n fields: storageFields,\n },\n fields: domainFields,\n relations: modelRelations,\n };\n }\n\n // --- Assemble contract ---\n\n // Aggregate roots are keyed by bare storage table name. When two models in\n // different namespaces map to the same bare table name, the bare key would\n // collide (last write wins, silently dropping a root), so those entries fall\n // back to a namespace-qualified key. Single-namespace contracts never\n // collide and keep their bare keys unchanged.\n const rootTableNameCounts = new Map<string, number>();\n for (const entry of rootEntries) {\n rootTableNameCounts.set(entry.tableName, (rootTableNameCounts.get(entry.tableName) ?? 0) + 1);\n }\n const roots: Record<string, CrossReference> = {};\n for (const entry of rootEntries) {\n const key =\n (rootTableNameCounts.get(entry.tableName) ?? 0) > 1\n ? `${entry.namespaceId}.${entry.tableName}`\n : entry.tableName;\n roots[key] = entry.ref;\n }\n\n // Normalise raw codec-triple inputs to the `kind: 'codec-instance'`\n // discriminator shape before hashing so the storageHash matches the\n // persisted JSON envelope produced from the SqlStorage class instance\n // (which always carries the discriminator).\n const rawStorageTypes = definition.storageTypes ?? {};\n const documentTypes: Record<string, StorageTypeInstance> = Object.fromEntries(\n Object.entries(rawStorageTypes).map(([name, entry]) => {\n if ((entry as { kind?: unknown }).kind === 'codec-instance') return [name, entry];\n return [\n name,\n toStorageTypeInstance({\n codecId: entry.codecId,\n nativeType: entry.nativeType,\n typeParams: (entry as { typeParams?: Record<string, unknown> }).typeParams ?? {},\n }),\n ];\n }),\n );\n const namespaceCoordinateIds = collectStorageNamespaceCoordinateIds(definition);\n\n // Build per-namespace registries for `enumType()` handles.\n // All authored enums target the contract's default namespace.\n const domainEnumsByNs: Record<string, Record<string, ContractEnum>> = {};\n const storageValueSetsByNs: Record<string, Record<string, StorageValueSetInput>> = {};\n for (const [enumName, handle] of Object.entries(definition.enums ?? {})) {\n if (enumName !== handle.enumName) {\n throw contractError(\n 'CONTRACT.ENUM_INVALID',\n `enum declaration key \"${enumName}\" must match enumType name \"${handle.enumName}\". Aliases are not supported.`,\n {\n meta: {\n enumName: handle.enumName,\n declarationKey: enumName,\n reason: 'key-name-mismatch',\n },\n },\n );\n }\n const nsId = defaultNamespaceId;\n let domainSlot = domainEnumsByNs[nsId];\n if (domainSlot === undefined) {\n domainSlot = {};\n domainEnumsByNs[nsId] = domainSlot;\n }\n domainSlot[enumName] = {\n codecId: handle.codecId,\n members: handle.enumMembers.map((m) => ({\n name: m.name,\n value: encodeViaCodec(m.value, handle.codecId, codecLookup),\n })),\n };\n\n let storageSlot = storageValueSetsByNs[nsId];\n if (storageSlot === undefined) {\n storageSlot = {};\n storageValueSetsByNs[nsId] = storageSlot;\n }\n storageSlot[enumName] = {\n kind: 'valueSet',\n values: handle.values.map((v) => encodeViaCodec(v, handle.codecId, codecLookup)),\n };\n }\n\n const { createNamespace } = definition;\n const entityTypesByDiscriminator = collectEntityTypeDescriptorsByDiscriminator(definition);\n const namespaces: SqlStorageInput['namespaces'] = Object.fromEntries(\n [...namespaceCoordinateIds].sort().map((id) => {\n const entitiesForNs = mergeColumnAndAttachedEntities(\n id,\n definition.attachedEntities?.[id],\n collectedColumnEntities[id],\n );\n assertNoManagedEntityKinds(id, entitiesForNs);\n\n const enumValueSetEntries = storageValueSetsByNs[id];\n const packValueSetEntries = deriveEntityValueSets(entitiesForNs, entityTypesByDiscriminator);\n const valueSetEntries =\n enumValueSetEntries !== undefined || packValueSetEntries !== undefined\n ? mergeNamespaceValueSets(id, enumValueSetEntries, packValueSetEntries)\n : undefined;\n\n const nsInput: SqlNamespaceInput = {\n id,\n entries: {\n table: tablesByNamespace[id] ?? {},\n ...entitiesForNs,\n ...(valueSetEntries !== undefined && Object.keys(valueSetEntries).length > 0\n ? { valueSet: valueSetEntries }\n : {}),\n },\n };\n return [id, createNamespace(nsInput)];\n }),\n );\n const storageWithoutHash = {\n ...(Object.keys(documentTypes).length > 0 ? { types: documentTypes } : {}),\n namespaces:\n defaultNamespaceId === UNBOUND_NAMESPACE_ID\n ? ensureUnboundNamespaceSlot(namespaces, createNamespace)\n : namespaces,\n };\n const storageHash: StorageHashBase<string> = definition.storageHash\n ? coreHash(definition.storageHash)\n : computeStorageHash({\n target,\n targetFamily,\n storage: storageWithoutHash as Record<string, unknown>,\n ...sqlContractCanonicalizationHooks,\n });\n const storage = new SqlStorage({ ...storageWithoutHash, storageHash });\n\n const executionSection =\n executionDefaults.length > 0\n ? {\n mutations: {\n defaults: executionDefaults.sort((a, b) => {\n const tableCompare = a.ref.table.localeCompare(b.ref.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n return a.ref.column.localeCompare(b.ref.column);\n }),\n },\n }\n : undefined;\n\n const extensionNamespaces = definition.extensions\n ? Object.values(definition.extensions).map((pack) => pack.id)\n : undefined;\n\n const extensions: Record<string, unknown> = { ...(definition.extensions || {}) };\n if (extensionNamespaces) {\n for (const namespace of extensionNamespaces) {\n if (!Object.hasOwn(extensions, namespace)) {\n extensions[namespace] = {};\n }\n }\n }\n\n const extensionPackCapabilitySources = definition.extensions\n ? Object.values(definition.extensions).map(\n (pack) => pack.capabilities as CapabilityMatrix | undefined,\n )\n : [];\n const capabilities = mergeCapabilityMatrices(\n definition.target.capabilities as CapabilityMatrix | undefined,\n ...extensionPackCapabilitySources,\n );\n // Internal `profileHash` computation is unchanged from `origin/main`: it\n // continues to fingerprint the author-declared capability subset. With\n // `capabilities` removed from the `defineContract` input that subset is\n // now always empty, so the hash naturally stabilises at `hash({})`.\n const profileHash = computeProfileHash({\n target,\n targetFamily,\n capabilities: {},\n });\n\n const executionWithHash = executionSection\n ? {\n ...executionSection,\n executionHash: computeExecutionHash({ target, targetFamily, execution: executionSection }),\n }\n : undefined;\n\n const valueObjects: Record<string, ContractValueObject> | undefined =\n definition.valueObjects && definition.valueObjects.length > 0\n ? Object.fromEntries(\n definition.valueObjects.map((vo) => [\n vo.name,\n {\n fields: Object.fromEntries(\n vo.fields.map((f) => [\n f.fieldName,\n isValueObjectField(f)\n ? {\n type: { kind: 'valueObject' as const, name: f.valueObjectName },\n nullable: f.nullable,\n ...(f.many ? { many: true } : {}),\n }\n : {\n type: {\n kind: 'scalar' as const,\n codecId: f.descriptor.codecId,\n ...ifDefined('typeParams', f.descriptor.typeParams),\n },\n nullable: f.nullable,\n },\n ]),\n ),\n },\n ]),\n )\n : undefined;\n\n const domainNamespaceIds = new Set(Object.keys(modelsByNamespace));\n if (domainNamespaceIds.size === 0) {\n domainNamespaceIds.add(defaultNamespaceId);\n }\n if (valueObjects !== undefined) {\n domainNamespaceIds.add(defaultNamespaceId);\n }\n for (const nsId of Object.keys(domainEnumsByNs)) {\n domainNamespaceIds.add(nsId);\n }\n const domainNamespaces = Object.fromEntries(\n [...domainNamespaceIds].sort().map((namespaceId) => {\n const modelsInNs = modelsByNamespace[namespaceId] ?? {};\n const enumsInNs = domainEnumsByNs[namespaceId];\n const namespaceSlice = {\n models: modelsInNs,\n ...(namespaceId === defaultNamespaceId && valueObjects !== undefined\n ? { valueObjects }\n : {}),\n ...(enumsInNs !== undefined && Object.keys(enumsInNs).length > 0\n ? { enum: enumsInNs }\n : {}),\n };\n return [namespaceId, namespaceSlice];\n }),\n );\n\n const contract: Contract<SqlStorage> = {\n target,\n targetFamily,\n ...ifDefined('defaultControlPolicy', definition.defaultControlPolicy),\n domain: { namespaces: domainNamespaces },\n roots,\n storage,\n ...(executionWithHash ? { execution: executionWithHash } : {}),\n extensions,\n capabilities,\n profileHash,\n meta: {},\n };\n\n assertStorageSemantics(definition, contract);\n\n return contract;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,MACA,SACA,SACiB;CACjB,OAAO,gBAAgB,MAAM,SAAS,OAAO;AAC/C;;;ACqCA,SAAS,eAAe,OAAgB,SAAiB,aAAsC;CAC7F,MAAM,QAAQ,aAAa,IAAI,OAAO;CACtC,IAAI,OACF,OAAO,MAAM,WAAW,KAAK;CAE/B,OAAO,UAGL,KAAK;AACT;AAEA,SAAS,oBACP,cACA,SACA,aACA,OAAO,OACQ;CACf,IAAI,aAAa,SAAS,YACxB,OAAO;EAAE,MAAM;EAAY,YAAY,aAAa;CAAW;CAEjE,IAAI,MAAM;EACR,IAAI,CAAC,MAAM,QAAQ,aAAa,KAAK,GACnC,MAAM,IAAI,cACR,+DAA+D,OAAO,aAAa,MAAM,8EAE3F;EAEF,OAAO;GACL,MAAM;GACN,OAAO,aAAa,MAAM,KAAK,YAAY,eAAe,SAAS,SAAS,WAAW,CAAC;EAC1F;CACF;CACA,OAAO;EACL,MAAM;EACN,OAAO,eAAe,aAAa,OAAO,SAAS,WAAW;CAChE;AACF;AAEA,SAAS,uBACP,YACA,UACM;CACN,MAAM,iBAAiB,yBAAyB,SAAS,OAAO;CAChE,IAAI,eAAe,SAAS,GAC1B,M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