@prisma-next/target-postgres 0.14.0-dev.80 → 0.14.0-dev.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{authoring-Bi9aa8zG.mjs → authoring-ChmUI_tC.mjs} +148 -48
- package/dist/authoring-ChmUI_tC.mjs.map +1 -0
- package/dist/{canonicalize-CAbXtVtB.d.mts → canonicalize-D1F4vUnP.d.mts} +13 -2
- package/dist/canonicalize-D1F4vUnP.d.mts.map +1 -0
- package/dist/contract-free.d.mts +1 -1
- package/dist/contract-free.mjs +2 -2
- package/dist/{control-policy-5LE2kwfb.mjs → control-policy-BfQLCrha.mjs} +4 -4
- package/dist/{control-policy-5LE2kwfb.mjs.map → control-policy-BfQLCrha.mjs.map} +1 -1
- package/dist/control.mjs +4 -4
- package/dist/{ddl-BQzITB_e.mjs → ddl-eBZav_MS.mjs} +2 -2
- package/dist/{ddl-BQzITB_e.mjs.map → ddl-eBZav_MS.mjs.map} +1 -1
- package/dist/ddl.d.mts +2 -2
- package/dist/{descriptor-meta-DzL6vXAz.mjs → descriptor-meta-DAwRBZpA.mjs} +5 -4
- package/dist/descriptor-meta-DAwRBZpA.mjs.map +1 -0
- package/dist/{diff-database-schema-DULhiCNM.mjs → diff-database-schema-jsEOfSYT.mjs} +4 -4
- package/dist/{diff-database-schema-DULhiCNM.mjs.map → diff-database-schema-jsEOfSYT.mjs.map} +1 -1
- package/dist/diff-database-schema.mjs +1 -1
- package/dist/issue-planner.mjs +1 -1
- package/dist/migration.mjs +2 -2
- package/dist/{nodes-Bc2N3tMy.d.mts → nodes-Dv5eCSq9.d.mts} +2 -2
- package/dist/{nodes-Bc2N3tMy.d.mts.map → nodes-Dv5eCSq9.d.mts.map} +1 -1
- package/dist/{op-factory-call-D6yu-PlS.mjs → op-factory-call-Dwsb1xzl.mjs} +3 -3
- package/dist/{op-factory-call-D6yu-PlS.mjs.map → op-factory-call-Dwsb1xzl.mjs.map} +1 -1
- package/dist/op-factory-call.mjs +1 -1
- package/dist/pack.d.mts +21 -0
- package/dist/pack.d.mts.map +1 -1
- package/dist/pack.mjs +1 -1
- package/dist/{planner-DwDxdYxi.mjs → planner-ChCtpEGe.mjs} +8 -8
- package/dist/{planner-DwDxdYxi.mjs.map → planner-ChCtpEGe.mjs.map} +1 -1
- package/dist/{planner-produced-postgres-migration-BGPpq56_.mjs → planner-produced-postgres-migration-Bb16yHNX.mjs} +2 -2
- package/dist/{planner-produced-postgres-migration-BGPpq56_.mjs.map → planner-produced-postgres-migration-Bb16yHNX.mjs.map} +1 -1
- package/dist/planner-produced-postgres-migration.mjs +1 -1
- package/dist/{planner-sql-checks-CDXn2uaS.mjs → planner-sql-checks-Cx0ATsPc.mjs} +2 -2
- package/dist/{planner-sql-checks-CDXn2uaS.mjs.map → planner-sql-checks-Cx0ATsPc.mjs.map} +1 -1
- package/dist/planner-sql-checks.mjs +1 -1
- package/dist/planner.mjs +2 -2
- package/dist/{postgres-contract-view-C3LPCLP_.mjs → postgres-contract-view-BiDhl5Ez.mjs} +3 -3
- package/dist/{postgres-contract-view-C3LPCLP_.mjs.map → postgres-contract-view-BiDhl5Ez.mjs.map} +1 -1
- package/dist/{postgres-migration-et1td40f.mjs → postgres-migration-Cj5Tpj1a.mjs} +3 -3
- package/dist/{postgres-migration-et1td40f.mjs.map → postgres-migration-Cj5Tpj1a.mjs.map} +1 -1
- package/dist/{postgres-schema-DYATroNx.mjs → postgres-schema-ChBj22nX.mjs} +2 -2
- package/dist/{postgres-schema-DYATroNx.mjs.map → postgres-schema-ChBj22nX.mjs.map} +1 -1
- package/dist/{resolve-ddl-schema-DpGte50u.mjs → resolve-ddl-schema-BCSMHFwl.mjs} +2 -2
- package/dist/{resolve-ddl-schema-DpGte50u.mjs.map → resolve-ddl-schema-BCSMHFwl.mjs.map} +1 -1
- package/dist/rls-canonicalize.d.mts +9 -2
- package/dist/rls-canonicalize.d.mts.map +1 -1
- package/dist/rls-canonicalize.mjs +2 -2
- package/dist/runtime.mjs +1 -1
- package/dist/schema-ir-annotations.mjs +1 -1
- package/dist/types.mjs +1 -1
- package/dist/{wire-name-rHHtr1h0.mjs → wire-name-DbQ9-2RC.mjs} +31 -2
- package/dist/wire-name-DbQ9-2RC.mjs.map +1 -0
- package/package.json +20 -20
- package/src/core/authoring.ts +253 -36
- package/src/core/descriptor-meta.ts +2 -0
- package/src/core/rls/canonicalize.ts +17 -0
- package/src/exports/rls-canonicalize.ts +6 -1
- package/dist/authoring-Bi9aa8zG.mjs.map +0 -1
- package/dist/canonicalize-CAbXtVtB.d.mts.map +0 -1
- package/dist/descriptor-meta-DzL6vXAz.mjs.map +0 -1
- package/dist/wire-name-rHHtr1h0.mjs.map +0 -1
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { a as PG_ENUM_CODEC_ID } from "./codec-ids-C_-Hj6bL.mjs";
|
|
2
2
|
import { t as PostgresNativeEnum } from "./postgres-native-enum-BwVNf0Ku.mjs";
|
|
3
|
-
import { _ as PostgresRlsEnablement, d as PostgresRlsEnablementSchema, f as PostgresRlsPolicySchema, g as PostgresRlsPolicy, m as PostgresRole, p as PostgresRoleSchema, u as PostgresNativeEnumSchema } from "./postgres-schema-
|
|
4
|
-
import {
|
|
3
|
+
import { _ as PostgresRlsEnablement, d as PostgresRlsEnablementSchema, f as PostgresRlsPolicySchema, g as PostgresRlsPolicy, m as PostgresRole, p as PostgresRoleSchema, u as PostgresNativeEnumSchema } from "./postgres-schema-ChBj22nX.mjs";
|
|
4
|
+
import { a as normalizePredicate, i as computeContentHash, r as POLICY_OPERATION_PREDICATES, t as formatRlsPolicyWireName } from "./wire-name-DbQ9-2RC.mjs";
|
|
5
5
|
import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
|
|
6
|
+
import { blindCast } from "@prisma-next/utils/casts";
|
|
6
7
|
import { temporalAuthoringPresets } from "@prisma-next/family-sql/control";
|
|
7
8
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
8
9
|
import { modelAttribute } from "@prisma-next/psl-parser";
|
|
10
|
+
import { assertDefined } from "@prisma-next/utils/assertions";
|
|
9
11
|
//#region src/core/authoring.ts
|
|
10
12
|
/**
|
|
11
13
|
* `pg.enum(<ref>)` registers as an ordinary type constructor whose sole
|
|
@@ -35,38 +37,6 @@ const POLICY_KEYWORD_OPERATION = {
|
|
|
35
37
|
policy_delete: "delete",
|
|
36
38
|
policy_all: "all"
|
|
37
39
|
};
|
|
38
|
-
/**
|
|
39
|
-
* Which predicate each RLS operation admits, mirroring Postgres: SELECT and
|
|
40
|
-
* DELETE decide row visibility/eligibility with `USING` only; INSERT validates
|
|
41
|
-
* the new row with `WITH CHECK` only; UPDATE and ALL take both. A predicate
|
|
42
|
-
* outside this set is a load-time error (see {@link lowerRlsPolicyFromBlock}).
|
|
43
|
-
*/
|
|
44
|
-
const POLICY_OPERATION_PREDICATES = {
|
|
45
|
-
select: {
|
|
46
|
-
using: true,
|
|
47
|
-
withCheck: false
|
|
48
|
-
},
|
|
49
|
-
insert: {
|
|
50
|
-
using: false,
|
|
51
|
-
withCheck: true
|
|
52
|
-
},
|
|
53
|
-
update: {
|
|
54
|
-
using: true,
|
|
55
|
-
withCheck: true
|
|
56
|
-
},
|
|
57
|
-
delete: {
|
|
58
|
-
using: true,
|
|
59
|
-
withCheck: false
|
|
60
|
-
},
|
|
61
|
-
all: {
|
|
62
|
-
using: true,
|
|
63
|
-
withCheck: true
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
function readRefParam(block, key) {
|
|
67
|
-
const param = block.parameters[key];
|
|
68
|
-
return param?.kind === "ref" ? param.identifier : void 0;
|
|
69
|
-
}
|
|
70
40
|
function readValueParam(block, key) {
|
|
71
41
|
const param = block.parameters[key];
|
|
72
42
|
return param?.kind === "value" ? param.raw : void 0;
|
|
@@ -103,11 +73,38 @@ function unwrapQuotedString(raw) {
|
|
|
103
73
|
}
|
|
104
74
|
return result;
|
|
105
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Assembles a {@link PostgresRlsPolicy} from lowered inputs: normalizes the
|
|
78
|
+
* predicates, computes the content-hash wire name, and constructs the frozen
|
|
79
|
+
* entity. The single hash-assembly body shared by the PSL block lowering
|
|
80
|
+
* ({@link lowerRlsPolicyFromBlock}) and the TS entity-handle lowering
|
|
81
|
+
* ({@link postgresLowerEntityHandles}) so the two surfaces cannot drift.
|
|
82
|
+
*/
|
|
83
|
+
function buildRlsPolicyEntity(input) {
|
|
84
|
+
const wireHash = computeContentHash({
|
|
85
|
+
...ifDefined("using", input.using !== void 0 ? normalizePredicate(input.using) : void 0),
|
|
86
|
+
...ifDefined("withCheck", input.withCheck !== void 0 ? normalizePredicate(input.withCheck) : void 0),
|
|
87
|
+
roles: input.roles,
|
|
88
|
+
operation: input.operation,
|
|
89
|
+
permissive: true
|
|
90
|
+
});
|
|
91
|
+
return new PostgresRlsPolicy({
|
|
92
|
+
name: formatRlsPolicyWireName(input.prefix, wireHash),
|
|
93
|
+
prefix: input.prefix,
|
|
94
|
+
tableName: input.tableName,
|
|
95
|
+
namespaceId: input.namespaceId,
|
|
96
|
+
operation: input.operation,
|
|
97
|
+
roles: input.roles,
|
|
98
|
+
...ifDefined("using", input.using),
|
|
99
|
+
...ifDefined("withCheck", input.withCheck),
|
|
100
|
+
permissive: true
|
|
101
|
+
});
|
|
102
|
+
}
|
|
106
103
|
function lowerRlsPolicyFromBlock(block, ctx) {
|
|
107
104
|
const prefix = block.name;
|
|
108
105
|
const operation = POLICY_KEYWORD_OPERATION[block.keyword] ?? "select";
|
|
109
|
-
const
|
|
110
|
-
|
|
106
|
+
const tableName = block.resolvedModelRefs?.["target"]?.tableName;
|
|
107
|
+
assertDefined(tableName, `lowerRlsPolicyFromBlock: policy "${block.name}" reached the factory without a resolved \`target\` ref; the interpreter resolves same-namespace model refs before invoking entity factories.`);
|
|
111
108
|
const roles = [...readListRefParams(block, "roles")].sort();
|
|
112
109
|
const usingRaw = readValueParam(block, "using");
|
|
113
110
|
const withCheckRaw = readValueParam(block, "withCheck");
|
|
@@ -124,22 +121,14 @@ function lowerRlsPolicyFromBlock(block, ctx) {
|
|
|
124
121
|
if (withCheckRaw !== void 0 && !support.withCheck) return rejectPredicate("withCheck");
|
|
125
122
|
const using = usingRaw !== void 0 ? unwrapQuotedString(usingRaw) : void 0;
|
|
126
123
|
const withCheck = withCheckRaw !== void 0 ? unwrapQuotedString(withCheckRaw) : void 0;
|
|
127
|
-
return
|
|
128
|
-
name: formatRlsPolicyWireName(prefix, computeContentHash({
|
|
129
|
-
...ifDefined("using", using !== void 0 ? normalizePredicate(using) : void 0),
|
|
130
|
-
...ifDefined("withCheck", withCheck !== void 0 ? normalizePredicate(withCheck) : void 0),
|
|
131
|
-
roles,
|
|
132
|
-
operation,
|
|
133
|
-
permissive: true
|
|
134
|
-
})),
|
|
124
|
+
return buildRlsPolicyEntity({
|
|
135
125
|
prefix,
|
|
136
126
|
tableName,
|
|
137
127
|
namespaceId: block.namespaceId,
|
|
138
128
|
operation,
|
|
139
129
|
roles,
|
|
140
130
|
...ifDefined("using", using),
|
|
141
|
-
...ifDefined("withCheck", withCheck)
|
|
142
|
-
permissive: true
|
|
131
|
+
...ifDefined("withCheck", withCheck)
|
|
143
132
|
});
|
|
144
133
|
}
|
|
145
134
|
/**
|
|
@@ -568,7 +557,118 @@ const postgresAuthoringFieldPresets = {
|
|
|
568
557
|
}
|
|
569
558
|
}
|
|
570
559
|
};
|
|
560
|
+
/**
|
|
561
|
+
* Postgres identifiers cap at 63 characters and the wire name appends a
|
|
562
|
+
* 9-character `_<8hex>` suffix, so the authored prefix is bounded at 54.
|
|
563
|
+
*/
|
|
564
|
+
const RLS_POLICY_PREFIX_MAX_LENGTH = 54;
|
|
565
|
+
/**
|
|
566
|
+
* Resolves an entity handle's `target` ref to a table coordinate of this
|
|
567
|
+
* contract, or throws the load-time diagnostic naming the handle: a
|
|
568
|
+
* cross-space target is rejected (you cannot CREATE POLICY on a table
|
|
569
|
+
* another space owns) and an unresolved target names the model.
|
|
570
|
+
*/
|
|
571
|
+
function requireLocalTarget(refs, subject) {
|
|
572
|
+
const target = refs["target"];
|
|
573
|
+
if (target !== void 0 && target.kind === "resolved") return {
|
|
574
|
+
namespaceId: target.namespaceId,
|
|
575
|
+
tableName: target.tableName
|
|
576
|
+
};
|
|
577
|
+
if (target !== void 0 && target.kind === "cross-space") throw new Error(`defineContract: ${subject} targets model "${target.modelName ?? target.tableName}", which lives in another contract space. Policies and rlsEnabled entries must target a model declared in this contract.`);
|
|
578
|
+
throw new Error(`defineContract: ${subject} targets model "${target?.modelName ?? "<anonymous>"}", which is not in the contract's models. Add the model to \`models\`.`);
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* The SQL-family entity-handle batch lowering hook for the Postgres pack
|
|
582
|
+
* (`SqlEntityHandleLoweringContribution`). Receives every `entities` handle
|
|
583
|
+
* whose kind this pack registered — batch, so the cross-entity diagnostics
|
|
584
|
+
* (duplicate prefix, policy without rlsEnabled, duplicate role) can see
|
|
585
|
+
* sibling handles — and lowers them with the same keying and hash assembly
|
|
586
|
+
* as the PSL path: `policy` keyed by prefix (wire name via
|
|
587
|
+
* {@link buildRlsPolicyEntity}), `rls` keyed by table name, `role` keyed by
|
|
588
|
+
* name and filed under the default namespace (roles are declared
|
|
589
|
+
* contract-wide; PSL has no role block to set a precedent).
|
|
590
|
+
*/
|
|
591
|
+
function postgresLowerEntityHandles(input) {
|
|
592
|
+
const enablements = /* @__PURE__ */ new Map();
|
|
593
|
+
const roles = /* @__PURE__ */ new Map();
|
|
594
|
+
const policies = [];
|
|
595
|
+
const coordinateKey = (coordinate) => `${coordinate.namespaceId} ${coordinate.tableName}`;
|
|
596
|
+
for (const { handle, refs } of input.handles) switch (handle.entityKind) {
|
|
597
|
+
case "rls": {
|
|
598
|
+
const coordinate = requireLocalTarget(refs, "an rlsEnabled entry");
|
|
599
|
+
const key = coordinateKey(coordinate);
|
|
600
|
+
if (!enablements.has(key)) enablements.set(key, {
|
|
601
|
+
coordinate,
|
|
602
|
+
entity: new PostgresRlsEnablement({
|
|
603
|
+
tableName: coordinate.tableName,
|
|
604
|
+
namespaceId: coordinate.namespaceId
|
|
605
|
+
})
|
|
606
|
+
});
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
case "role": {
|
|
610
|
+
const roleHandle = blindCast(handle);
|
|
611
|
+
if (roles.has(roleHandle.name)) throw new Error(`defineContract: role "${roleHandle.name}" is declared more than once in the entities list.`);
|
|
612
|
+
roles.set(roleHandle.name, new PostgresRole({
|
|
613
|
+
name: roleHandle.name,
|
|
614
|
+
namespaceId: UNBOUND_NAMESPACE_ID
|
|
615
|
+
}));
|
|
616
|
+
break;
|
|
617
|
+
}
|
|
618
|
+
case "policy": {
|
|
619
|
+
const policyHandle = blindCast(handle);
|
|
620
|
+
policies.push({
|
|
621
|
+
handle: policyHandle,
|
|
622
|
+
refs
|
|
623
|
+
});
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
default: throw new Error(`defineContract: the postgres pack does not lower "${handle.entityKind}" handles from the entities list.`);
|
|
627
|
+
}
|
|
628
|
+
const rows = [];
|
|
629
|
+
const seenPrefixes = /* @__PURE__ */ new Set();
|
|
630
|
+
for (const { handle: policy, refs } of policies) {
|
|
631
|
+
const prefix = policy.name;
|
|
632
|
+
if (prefix.length > RLS_POLICY_PREFIX_MAX_LENGTH) throw new Error(`defineContract: policy prefix "${prefix}" exceeds the ${RLS_POLICY_PREFIX_MAX_LENGTH}-character maximum (Postgres identifiers cap at 63 characters and the wire name appends a 9-character hash suffix).`);
|
|
633
|
+
const coordinate = requireLocalTarget(refs, `policy "${prefix}"`);
|
|
634
|
+
if (!enablements.has(coordinateKey(coordinate))) {
|
|
635
|
+
const target = refs["target"];
|
|
636
|
+
throw new Error(`defineContract: policy "${prefix}" targets model "${target?.modelName ?? coordinate.tableName}", whose table is not RLS-enabled. Add rlsEnabled(<model>) to the entities list.`);
|
|
637
|
+
}
|
|
638
|
+
const prefixKey = `${coordinate.namespaceId} ${prefix}`;
|
|
639
|
+
if (seenPrefixes.has(prefixKey)) throw new Error(`defineContract: policy prefix "${prefix}" is declared more than once in namespace "${coordinate.namespaceId}". Policy prefixes must be unique per namespace.`);
|
|
640
|
+
seenPrefixes.add(prefixKey);
|
|
641
|
+
const roleNames = [...new Set(policy.roles.map((roleHandle) => roleHandle.name))].sort();
|
|
642
|
+
rows.push({
|
|
643
|
+
namespaceId: coordinate.namespaceId,
|
|
644
|
+
entityKind: "policy",
|
|
645
|
+
key: prefix,
|
|
646
|
+
entity: buildRlsPolicyEntity({
|
|
647
|
+
prefix,
|
|
648
|
+
tableName: coordinate.tableName,
|
|
649
|
+
namespaceId: coordinate.namespaceId,
|
|
650
|
+
operation: policy.operation,
|
|
651
|
+
roles: roleNames,
|
|
652
|
+
...ifDefined("using", policy.using),
|
|
653
|
+
...ifDefined("withCheck", policy.withCheck)
|
|
654
|
+
})
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
for (const { coordinate, entity } of enablements.values()) rows.push({
|
|
658
|
+
namespaceId: coordinate.namespaceId,
|
|
659
|
+
entityKind: "rls",
|
|
660
|
+
key: coordinate.tableName,
|
|
661
|
+
entity
|
|
662
|
+
});
|
|
663
|
+
for (const [name, entity] of roles) rows.push({
|
|
664
|
+
namespaceId: UNBOUND_NAMESPACE_ID,
|
|
665
|
+
entityKind: "role",
|
|
666
|
+
key: name,
|
|
667
|
+
entity
|
|
668
|
+
});
|
|
669
|
+
return rows;
|
|
670
|
+
}
|
|
571
671
|
//#endregion
|
|
572
|
-
export { postgresAuthoringTypes as a, postgresAuthoringPslBlockDescriptors as i, postgresAuthoringFieldPresets as n, postgresAuthoringModelAttributes as r, postgresAuthoringEntityTypes as t };
|
|
672
|
+
export { postgresAuthoringTypes as a, postgresAuthoringPslBlockDescriptors as i, postgresAuthoringFieldPresets as n, postgresLowerEntityHandles as o, postgresAuthoringModelAttributes as r, postgresAuthoringEntityTypes as t };
|
|
573
673
|
|
|
574
|
-
//# sourceMappingURL=authoring-
|
|
674
|
+
//# sourceMappingURL=authoring-ChmUI_tC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authoring-ChmUI_tC.mjs","names":[],"sources":["../src/core/authoring.ts"],"sourcesContent":["import { temporalAuthoringPresets } from '@prisma-next/family-sql/control';\nimport type {\n AuthoringEntityContext,\n AuthoringEntityTypeFactoryOutput,\n AuthoringEntityTypeNamespace,\n AuthoringFieldNamespace,\n AuthoringModelAttributeContext,\n AuthoringModelAttributeDescriptorNamespace,\n AuthoringPslBlockDescriptorNamespace,\n AuthoringTypeNamespace,\n PslExtensionBlock,\n} from '@prisma-next/framework-components/authoring';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { modelAttribute } from '@prisma-next/psl-parser';\nimport type {\n EntityHandleLoweringInput,\n LoweredPackEntity,\n ResolvedEntityHandleRef,\n ResolvedPslModelRefs,\n} from '@prisma-next/sql-contract/entity-handle-lowering-hook';\nimport type { SqlValueSetDerivingEntityTypeOutput } from '@prisma-next/sql-contract/value-set-derivation-hook';\nimport { assertDefined } from '@prisma-next/utils/assertions';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PG_ENUM_CODEC_ID } from './codec-ids';\nimport { PostgresNativeEnum } from './postgres-native-enum';\nimport { PostgresRlsEnablement, type PostgresRlsEnablementInput } from './postgres-rls-enablement';\nimport { PostgresRlsPolicy, type RlsPolicyOperation } from './postgres-rls-policy';\nimport { PostgresRole } from './postgres-role';\nimport {\n PostgresNativeEnumSchema,\n PostgresRlsEnablementSchema,\n PostgresRlsPolicySchema,\n PostgresRoleSchema,\n} from './postgres-validators';\nimport {\n computeContentHash,\n normalizePredicate,\n POLICY_OPERATION_PREDICATES,\n} from './rls/canonicalize';\nimport { formatRlsPolicyWireName } from './rls/wire-name';\n\n/**\n * `pg.enum(<ref>)` registers as an ordinary type constructor whose sole\n * positional argument names a `native_enum` entity instead of carrying a\n * literal value. The interpreter resolves the ref to the `native_enum`\n * entity generically (driven by `entityRefArg`); the `pg/enum@1` codec\n * descriptor's `columnFromEntity` hook (see `codecs.ts`) converts that\n * entity into the column's `typeParams` and native type.\n */\nexport const postgresAuthoringTypes = {\n pg: {\n enum: {\n kind: 'typeConstructor',\n entityRefArg: { index: 0, entityKind: 'native_enum' },\n output: {\n codecId: PG_ENUM_CODEC_ID,\n },\n },\n },\n} as const satisfies AuthoringTypeNamespace;\n\nexport interface RlsPolicyExtensionBlock extends PslExtensionBlock {\n readonly namespaceId: string;\n /**\n * Model refs the family interpreter resolved from the block's descriptor-\n * declared `refKind: 'model'` parameters before invoking this factory\n * (keyed by parameter name). An unresolved required ref is the\n * interpreter's diagnostic; the factory is never called with one missing.\n */\n readonly resolvedModelRefs?: ResolvedPslModelRefs;\n}\n\n/** A parsed `role` block annotated with its lexical namespace id by the interpreter. */\nexport interface RoleExtensionBlock extends PslExtensionBlock {\n readonly namespaceId: string;\n}\n\n/**\n * Maps a `policy_<op>` keyword to the RLS operation it authors. The keyword\n * IS the operation (per the project's rejection of a `policy { operation = … }`\n * conditional block).\n */\nconst POLICY_KEYWORD_OPERATION: Readonly<Record<string, RlsPolicyOperation>> = {\n policy_select: 'select',\n policy_insert: 'insert',\n policy_update: 'update',\n policy_delete: 'delete',\n policy_all: 'all',\n};\n\nfunction readValueParam(block: PslExtensionBlock, key: string): string | undefined {\n const param = block.parameters[key];\n return param?.kind === 'value' ? param.raw : undefined;\n}\n\nfunction readListRefParams(block: PslExtensionBlock, key: string): string[] {\n const param = block.parameters[key];\n if (param?.kind !== 'list') return [];\n return param.items.flatMap((item) => (item.kind === 'ref' ? [item.identifier] : []));\n}\n\n/**\n * Unwraps a quoted PSL string argument, inverting the printer's\n * `escapePslString` escapes (`\\\\`, `\\\"`, `\\n`, `\\r`). An unknown escape\n * sequence is kept verbatim, matching the printer-side `unescapePslString`\n * convention.\n */\nfunction unwrapQuotedString(raw: string): string {\n if (!(raw.startsWith('\"') && raw.endsWith('\"') && raw.length >= 2)) {\n return raw;\n }\n const inner = raw.slice(1, -1);\n let result = '';\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] !== '\\\\' || i + 1 >= inner.length) {\n result += inner[i];\n continue;\n }\n const next = inner[i + 1];\n if (next === '\\\\' || next === '\"') {\n result += next;\n } else if (next === 'n') {\n result += '\\n';\n } else if (next === 'r') {\n result += '\\r';\n } else {\n result += '\\\\';\n result += next;\n }\n i++;\n }\n return result;\n}\n\n/**\n * Assembles a {@link PostgresRlsPolicy} from lowered inputs: normalizes the\n * predicates, computes the content-hash wire name, and constructs the frozen\n * entity. The single hash-assembly body shared by the PSL block lowering\n * ({@link lowerRlsPolicyFromBlock}) and the TS entity-handle lowering\n * ({@link postgresLowerEntityHandles}) so the two surfaces cannot drift.\n */\nfunction buildRlsPolicyEntity(input: {\n readonly prefix: string;\n readonly tableName: string;\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n readonly using?: string;\n readonly withCheck?: string;\n}): PostgresRlsPolicy {\n const wireHash = computeContentHash({\n ...ifDefined('using', input.using !== undefined ? normalizePredicate(input.using) : undefined),\n ...ifDefined(\n 'withCheck',\n input.withCheck !== undefined ? normalizePredicate(input.withCheck) : undefined,\n ),\n roles: input.roles,\n operation: input.operation,\n permissive: true,\n });\n\n return new PostgresRlsPolicy({\n name: formatRlsPolicyWireName(input.prefix, wireHash),\n prefix: input.prefix,\n tableName: input.tableName,\n namespaceId: input.namespaceId,\n operation: input.operation,\n roles: input.roles,\n ...ifDefined('using', input.using),\n ...ifDefined('withCheck', input.withCheck),\n permissive: true,\n });\n}\n\nfunction lowerRlsPolicyFromBlock(\n block: RlsPolicyExtensionBlock,\n ctx: AuthoringEntityContext,\n): PostgresRlsPolicy | undefined {\n const prefix = block.name;\n const operation = POLICY_KEYWORD_OPERATION[block.keyword] ?? 'select';\n // The interpreter resolves the descriptor-declared `target` model ref to\n // its storage table name before invoking this factory (an unresolved or\n // missing required ref is the interpreter's diagnostic), so a lookup miss\n // here is structurally impossible.\n const tableName = block.resolvedModelRefs?.['target']?.tableName;\n assertDefined(\n tableName,\n `lowerRlsPolicyFromBlock: policy \"${block.name}\" reached the factory without a resolved \\`target\\` ref; the interpreter resolves same-namespace model refs before invoking entity factories.`,\n );\n const roles = [...readListRefParams(block, 'roles')].sort();\n\n const usingRaw = readValueParam(block, 'using');\n const withCheckRaw = readValueParam(block, 'withCheck');\n\n // Reject a predicate the operation does not take (e.g. `using` on INSERT, or\n // `withCheck` on SELECT/DELETE). The descriptor's param set already omits it,\n // but the generic descriptor validator is not wired into the SQL-family\n // interpreter, so the lowering enforces the per-operation predicate matrix\n // directly — a wrong predicate is a load-time diagnostic, not a silent drop.\n const support = POLICY_OPERATION_PREDICATES[operation];\n const rejectPredicate = (predicate: 'using' | 'withCheck'): undefined => {\n ctx.diagnostics?.push({\n code: 'PSL_RLS_PREDICATE_NOT_FOR_OPERATION',\n message: `\\`${block.keyword}\\` policy \"${block.name}\" does not take a \\`${predicate}\\` predicate; the ${operation.toUpperCase()} operation uses ${support.using ? '`using`' : '`withCheck`'}${support.using && support.withCheck ? ' and `withCheck`' : ' only'}.`,\n sourceId: ctx.sourceId ?? 'unknown',\n span: block.parameters[predicate]?.span ?? block.span,\n });\n return undefined;\n };\n if (usingRaw !== undefined && !support.using) return rejectPredicate('using');\n if (withCheckRaw !== undefined && !support.withCheck) return rejectPredicate('withCheck');\n\n const using = usingRaw !== undefined ? unwrapQuotedString(usingRaw) : undefined;\n const withCheck = withCheckRaw !== undefined ? unwrapQuotedString(withCheckRaw) : undefined;\n\n return buildRlsPolicyEntity({\n prefix,\n tableName,\n namespaceId: block.namespaceId,\n operation,\n roles,\n ...ifDefined('using', using),\n ...ifDefined('withCheck', withCheck),\n });\n}\n\n/**\n * Lowers a `native_enum { memberName = \"value\" … @@map(\"type_name\") }` block\n * into a {@link PostgresNativeEnum}. Members must be authored as explicit\n * `key = \"value\"` pairs — a bare (value-less) member is a diagnostic, not\n * accepted (authoring-design.md §2.1). The parsed `memberName` is only used\n * to duplicate-check and report diagnostics; the lowered entity carries just\n * the member values (a native enum is value-only — the member \"name\" isn't\n * a separate authoring concept from the value). `typeName` comes from\n * `@@map` or defaults to the block name verbatim.\n */\nfunction lowerNativeEnumFromBlock(\n block: PslExtensionBlock,\n ctx: AuthoringEntityContext,\n): PostgresNativeEnum | undefined {\n const sourceId = ctx.sourceId ?? 'unknown';\n const diagnostics = ctx.diagnostics;\n\n const mapAttr = block.blockAttributes.find((a) => a.name === 'map');\n let typeName = block.name;\n if (mapAttr) {\n const rawArg = mapAttr.args[0]?.value;\n const mapped = rawArg !== undefined ? unwrapQuotedString(rawArg) : undefined;\n if (mapped === undefined) {\n diagnostics?.push({\n code: 'PSL_NATIVE_ENUM_INVALID_MAP',\n message: `native_enum \"${block.name}\" @@map attribute must have a quoted type-name argument`,\n sourceId,\n span: mapAttr.span,\n });\n return undefined;\n }\n typeName = mapped;\n }\n\n let memberError = false;\n const seenValues = new Set<string>();\n const members: string[] = [];\n for (const [memberName, paramValue] of Object.entries(block.parameters)) {\n if (paramValue.kind === 'bare') {\n diagnostics?.push({\n code: 'PSL_NATIVE_ENUM_BARE_MEMBER',\n message: `native_enum \"${block.name}\" member \"${memberName}\" has no value; members must be authored as \"${memberName} = \\\\\"value\\\\\"\"`,\n sourceId,\n span: paramValue.span,\n });\n memberError = true;\n continue;\n }\n if (paramValue.kind !== 'value') continue;\n\n let jsonValue: unknown;\n try {\n jsonValue = JSON.parse(paramValue.raw);\n } catch {\n diagnostics?.push({\n code: 'PSL_EXTENSION_INVALID_VALUE',\n message: `native_enum \"${block.name}\" member \"${memberName}\" value \"${paramValue.raw}\" is not valid JSON`,\n sourceId,\n span: paramValue.span,\n });\n memberError = true;\n continue;\n }\n if (typeof jsonValue !== 'string') {\n diagnostics?.push({\n code: 'PSL_EXTENSION_INVALID_VALUE',\n message: `native_enum \"${block.name}\" member \"${memberName}\" value must be a string`,\n sourceId,\n span: paramValue.span,\n });\n memberError = true;\n continue;\n }\n if (seenValues.has(jsonValue)) {\n diagnostics?.push({\n code: 'PSL_NATIVE_ENUM_DUPLICATE_MEMBER_VALUE',\n message: `native_enum \"${block.name}\": duplicate member value \"${jsonValue}\"`,\n sourceId,\n span: paramValue.span,\n });\n memberError = true;\n continue;\n }\n seenValues.add(jsonValue);\n members.push(jsonValue);\n }\n\n if (memberError) return undefined;\n\n if (members.length === 0) {\n diagnostics?.push({\n code: 'PSL_NATIVE_ENUM_MISSING_MEMBERS',\n message: `native_enum \"${block.name}\" must have at least one member`,\n sourceId,\n span: block.span,\n });\n return undefined;\n }\n\n // `control` stays unset — the effective grade is resolved at read time via `effectiveControlPolicy`, like `StorageTable`/`StorageColumn`.\n return new PostgresNativeEnum({ typeName, members });\n}\n\n/**\n * `native_enum`'s entity-type factory output, checked separately from the assembled\n * `postgresAuthoringEntityTypes` map below: `deriveValueSet` is SQL-family surface\n * ({@link SqlValueSetDerivingEntityTypeOutput}), not part of the framework\n * `AuthoringEntityTypeFactoryOutput` shape, so folding it directly into the map's single\n * `satisfies AuthoringEntityTypeNamespace` check would trip an excess-property error. Checking it\n * here against the intersection of both shapes keeps it structurally valid against each without\n * widening the map's own check.\n */\nconst nativeEnumEntityTypeOutput = {\n factory: lowerNativeEnumFromBlock,\n deriveValueSet: (entity: PostgresNativeEnum) => ({\n kind: 'valueSet' as const,\n values: [...entity.members],\n }),\n} satisfies AuthoringEntityTypeFactoryOutput<PslExtensionBlock, PostgresNativeEnum | undefined> &\n SqlValueSetDerivingEntityTypeOutput;\n\n/**\n * Lowers a `role <name> {}` block into a {@link PostgresRole}. Roles are\n * cluster-scoped in Postgres, so the block must be declared inside\n * `namespace unbound { … }` — any other lexical namespace (a named schema,\n * or the default bucket top-level declarations resolve to) is a load-time\n * diagnostic. The lowered entity carries the unbound coordinate.\n */\nfunction lowerRoleFromBlock(\n block: RoleExtensionBlock,\n ctx: AuthoringEntityContext,\n): PostgresRole | undefined {\n if (block.namespaceId !== UNBOUND_NAMESPACE_ID) {\n ctx.diagnostics?.push({\n code: 'PSL_ROLE_BLOCK_OUTSIDE_UNBOUND_NAMESPACE',\n message: `\\`role\\` block \"${block.name}\" must be declared inside \\`namespace unbound { }\\`, not in namespace \"${block.namespaceId}\"`,\n sourceId: ctx.sourceId ?? 'unknown',\n span: block.span,\n });\n return undefined;\n }\n return new PostgresRole({ name: block.name, namespaceId: UNBOUND_NAMESPACE_ID });\n}\n\nexport const postgresAuthoringEntityTypes = {\n role: {\n kind: 'entity',\n discriminator: 'role',\n validatorSchema: PostgresRoleSchema,\n output: {\n factory: lowerRoleFromBlock,\n },\n },\n rls: {\n kind: 'entity',\n discriminator: 'rls',\n validatorSchema: PostgresRlsEnablementSchema,\n output: {\n factory: (input: PostgresRlsEnablementInput): PostgresRlsEnablement =>\n new PostgresRlsEnablement(input),\n },\n },\n policy: {\n kind: 'entity',\n discriminator: 'policy',\n validatorSchema: PostgresRlsPolicySchema,\n output: {\n factory: lowerRlsPolicyFromBlock,\n },\n },\n native_enum: {\n kind: 'entity',\n discriminator: 'native_enum',\n validatorSchema: PostgresNativeEnumSchema,\n output: nativeEnumEntityTypeOutput,\n },\n} as const satisfies AuthoringEntityTypeNamespace;\n\n/**\n * Field presets contributed by the Postgres target pack.\n *\n * These mirror the PSL scalar-to-codec mapping used by the Postgres adapter\n * (see `createPostgresPslScalarTypeDescriptors`), so that authoring a field\n * via the TS callback surface (e.g. `field.int()`) and via the PSL scalar\n * surface (e.g. `Int`) lowers to byte-identical contracts.\n *\n * The `uuidNative` / `id.uuidv4Native` / `id.uuidv7Native` presets use the\n * native Postgres `uuid` type (codecId `pg/uuid@1`). For cross-target\n * portability use `uuidString` / `id.uuidv4String` / `id.uuidv7String` from\n * the family pack instead.\n */\n/**\n * Shared parameter descriptors for the five `policy_<op>` PSL block\n * keywords. All five share the `policy` discriminator — the parser\n * dispatches by keyword (see the framework's PSL-block SPI), and every\n * keyword's factory lowers to `PostgresRlsPolicy` via `lowerRlsPolicyFromBlock`.\n *\n * The `roles` list uses `scope:'cross-space'` because same-namespace\n * role ref resolution requires PSL namespace entries keyed by `refKind`\n * (i.e. `'role'`), which in turn requires the role block discriminator to\n * equal `'role'`. Aligning discriminator with refKind is tracked for\n * slice 4 (cross-space roles). Until then cross-space passes validation\n * unconditionally and the authored role names flow through unchanged.\n */\nconst policyTargetParam = {\n kind: 'ref',\n refKind: 'model',\n scope: 'same-namespace',\n required: true,\n} as const;\nconst policyRolesParam = {\n kind: 'list',\n of: { kind: 'ref', refKind: 'role', scope: 'cross-space' },\n} as const;\nconst policyPredicateParam = { kind: 'value', codecId: 'pg/text@1', required: true } as const;\n// A policy may only target an RLS-controlled model: the model named by\n// `target` must declare `@@rls`, or the load fails with a diagnostic naming\n// the model and the policy prefix.\nconst policyRequiresRls = { parameter: 'target', attribute: 'rls' } as const;\n\nexport const postgresAuthoringPslBlockDescriptors = {\n // The predicate param set per keyword mirrors Postgres: SELECT/DELETE take\n // USING only; INSERT takes WITH CHECK only; UPDATE/ALL take both. The\n // per-operation predicate matrix is enforced in `lowerRlsPolicyFromBlock`\n // (a wrong predicate for the operation is a load-time diagnostic there),\n // since the generic descriptor validator is not wired into the SQL-family\n // interpreter.\n policy_select: {\n kind: 'pslBlock',\n keyword: 'policy_select',\n discriminator: 'policy',\n name: { required: true },\n parameters: { target: policyTargetParam, roles: policyRolesParam, using: policyPredicateParam },\n requiresModelAttribute: policyRequiresRls,\n },\n policy_delete: {\n kind: 'pslBlock',\n keyword: 'policy_delete',\n discriminator: 'policy',\n name: { required: true },\n parameters: { target: policyTargetParam, roles: policyRolesParam, using: policyPredicateParam },\n requiresModelAttribute: policyRequiresRls,\n },\n policy_insert: {\n kind: 'pslBlock',\n keyword: 'policy_insert',\n discriminator: 'policy',\n name: { required: true },\n parameters: {\n target: policyTargetParam,\n roles: policyRolesParam,\n withCheck: policyPredicateParam,\n },\n requiresModelAttribute: policyRequiresRls,\n },\n policy_update: {\n kind: 'pslBlock',\n keyword: 'policy_update',\n discriminator: 'policy',\n name: { required: true },\n parameters: {\n target: policyTargetParam,\n roles: policyRolesParam,\n using: policyPredicateParam,\n withCheck: policyPredicateParam,\n },\n requiresModelAttribute: policyRequiresRls,\n },\n policy_all: {\n kind: 'pslBlock',\n keyword: 'policy_all',\n discriminator: 'policy',\n name: { required: true },\n parameters: {\n target: policyTargetParam,\n roles: policyRolesParam,\n using: policyPredicateParam,\n withCheck: policyPredicateParam,\n },\n requiresModelAttribute: policyRequiresRls,\n },\n /**\n * PSL block descriptor for `native_enum`.\n *\n * Reuses the existing variadic-block mechanism (the same shape the SQL\n * family's `enum` block ships): the body is an open `memberName = \"value\"`\n * list. `variadicParameters: true` opens the block to arbitrary keys\n * beyond the declared (empty) `parameters` set — the lowering factory\n * (`lowerNativeEnumFromBlock`) turns the variadic entries into ordered\n * members and rejects a bare (value-less) member.\n */\n native_enum: {\n kind: 'pslBlock',\n keyword: 'native_enum',\n discriminator: 'native_enum',\n name: { required: true },\n parameters: {},\n variadicParameters: true,\n },\n /**\n * PSL block descriptor for `role` (e.g. `role anon {}`). Name-only, no\n * parameters and no body content. Declared inside `namespace unbound { }`\n * — see {@link lowerRoleFromBlock} for the placement check and the\n * coordinate the lowered entity carries.\n */\n role: {\n kind: 'pslBlock',\n keyword: 'role',\n discriminator: 'role',\n name: { required: true },\n parameters: {},\n },\n} as const satisfies AuthoringPslBlockDescriptorNamespace;\n\n/**\n * `@@` model attributes contributed by the Postgres target pack.\n *\n * `@@rls` is argument-less: presence marks the model's table\n * RLS-controlled. It lowers to a {@link PostgresRlsEnablement} marker in\n * the namespace's `entries.rls`, keyed by the model's table name — the\n * marker (never the policy set) is what drives\n * `ENABLE`/`DISABLE ROW LEVEL SECURITY` planning.\n */\nexport const postgresAuthoringModelAttributes = {\n rls: {\n kind: 'modelAttribute',\n attribute: 'rls',\n spec: modelAttribute('rls', {}),\n lower: (_parsed: Record<never, never>, ctx: AuthoringModelAttributeContext) => ({\n key: ctx.storageName,\n entity: new PostgresRlsEnablement({\n tableName: ctx.storageName,\n namespaceId: ctx.namespaceId,\n }),\n }),\n },\n} as const satisfies AuthoringModelAttributeDescriptorNamespace;\n\nexport const postgresAuthoringFieldPresets = {\n text: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/text@1',\n nativeType: 'text',\n },\n },\n int: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/int4@1',\n nativeType: 'int4',\n },\n },\n bigint: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/int8@1',\n nativeType: 'int8',\n },\n },\n float: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/float8@1',\n nativeType: 'float8',\n },\n },\n decimal: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/numeric@1',\n nativeType: 'numeric',\n },\n },\n boolean: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/bool@1',\n nativeType: 'bool',\n },\n },\n json: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/jsonb@1',\n nativeType: 'jsonb',\n },\n },\n bytes: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/bytea@1',\n nativeType: 'bytea',\n },\n },\n dateTime: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/timestamptz@1',\n nativeType: 'timestamptz',\n },\n },\n temporal: /* @__PURE__ */ temporalAuthoringPresets({\n codecId: 'pg/timestamptz@1',\n nativeType: 'timestamptz',\n }),\n uuidNative: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n },\n },\n id: {\n uuidv4Native: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n executionDefaults: {\n onCreate: {\n kind: 'generator',\n id: 'uuidv4',\n },\n },\n id: true,\n },\n },\n uuidv7Native: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n executionDefaults: {\n onCreate: {\n kind: 'generator',\n id: 'uuidv7',\n },\n },\n id: true,\n },\n },\n },\n} as const satisfies AuthoringFieldNamespace;\n\n/**\n * Postgres identifiers cap at 63 characters and the wire name appends a\n * 9-character `_<8hex>` suffix, so the authored prefix is bounded at 54.\n */\nconst RLS_POLICY_PREFIX_MAX_LENGTH = 54;\n\ninterface RlsRoleHandleShape {\n readonly entityKind: 'role';\n readonly name: string;\n}\n\ninterface RlsPolicyHandleShape {\n readonly entityKind: 'policy';\n readonly operation: RlsPolicyOperation;\n readonly name: string;\n readonly roles: readonly { readonly name: string }[];\n readonly using?: string;\n readonly withCheck?: string;\n}\n\ninterface RlsTargetCoordinate {\n readonly namespaceId: string;\n readonly tableName: string;\n}\n\n/**\n * Resolves an entity handle's `target` ref to a table coordinate of this\n * contract, or throws the load-time diagnostic naming the handle: a\n * cross-space target is rejected (you cannot CREATE POLICY on a table\n * another space owns) and an unresolved target names the model.\n */\nfunction requireLocalTarget(\n refs: Readonly<Record<string, ResolvedEntityHandleRef>>,\n subject: string,\n): RlsTargetCoordinate {\n const target = refs['target'];\n if (target !== undefined && target.kind === 'resolved') {\n return { namespaceId: target.namespaceId, tableName: target.tableName };\n }\n if (target !== undefined && target.kind === 'cross-space') {\n throw new Error(\n `defineContract: ${subject} targets model \"${target.modelName ?? target.tableName}\", which lives in another contract space. Policies and rlsEnabled entries must target a model declared in this contract.`,\n );\n }\n throw new Error(\n `defineContract: ${subject} targets model \"${target?.modelName ?? '<anonymous>'}\", which is not in the contract's models. Add the model to \\`models\\`.`,\n );\n}\n\n/**\n * The SQL-family entity-handle batch lowering hook for the Postgres pack\n * (`SqlEntityHandleLoweringContribution`). Receives every `entities` handle\n * whose kind this pack registered — batch, so the cross-entity diagnostics\n * (duplicate prefix, policy without rlsEnabled, duplicate role) can see\n * sibling handles — and lowers them with the same keying and hash assembly\n * as the PSL path: `policy` keyed by prefix (wire name via\n * {@link buildRlsPolicyEntity}), `rls` keyed by table name, `role` keyed by\n * name and filed under the default namespace (roles are declared\n * contract-wide; PSL has no role block to set a precedent).\n */\nexport function postgresLowerEntityHandles(\n input: EntityHandleLoweringInput,\n): readonly LoweredPackEntity[] {\n const enablements = new Map<\n string,\n { coordinate: RlsTargetCoordinate; entity: PostgresRlsEnablement }\n >();\n const roles = new Map<string, PostgresRole>();\n const policies: {\n readonly handle: RlsPolicyHandleShape;\n readonly refs: Readonly<Record<string, ResolvedEntityHandleRef>>;\n }[] = [];\n const coordinateKey = (coordinate: RlsTargetCoordinate): string =>\n `${coordinate.namespaceId} ${coordinate.tableName}`;\n\n for (const { handle, refs } of input.handles) {\n switch (handle.entityKind) {\n case 'rls': {\n const coordinate = requireLocalTarget(refs, 'an rlsEnabled entry');\n const key = coordinateKey(coordinate);\n if (!enablements.has(key)) {\n enablements.set(key, {\n coordinate,\n entity: new PostgresRlsEnablement({\n tableName: coordinate.tableName,\n namespaceId: coordinate.namespaceId,\n }),\n });\n }\n break;\n }\n case 'role': {\n const roleHandle = blindCast<\n RlsRoleHandleShape,\n 'role handles are constructed only by the postgres contract-builder role() constructor, which enforces this shape'\n >(handle);\n if (roles.has(roleHandle.name)) {\n throw new Error(\n `defineContract: role \"${roleHandle.name}\" is declared more than once in the entities list.`,\n );\n }\n // Roles are cluster-scoped in Postgres, so they always land in the\n // `__unbound__` namespace — identical to a PSL `role` block\n // (`lowerRoleFromBlock`) and matching the `PostgresRole` class's own\n // contract. The declaring surface (TS entities vs PSL) does not move\n // the slot.\n roles.set(\n roleHandle.name,\n new PostgresRole({ name: roleHandle.name, namespaceId: UNBOUND_NAMESPACE_ID }),\n );\n break;\n }\n case 'policy': {\n const policyHandle = blindCast<\n RlsPolicyHandleShape,\n 'policy handles are constructed only by the postgres contract-builder policy*() constructors, which enforce this shape'\n >(handle);\n policies.push({ handle: policyHandle, refs });\n break;\n }\n default:\n throw new Error(\n `defineContract: the postgres pack does not lower \"${handle.entityKind}\" handles from the entities list.`,\n );\n }\n }\n\n const rows: LoweredPackEntity[] = [];\n const seenPrefixes = new Set<string>();\n\n for (const { handle: policy, refs } of policies) {\n const prefix = policy.name;\n if (prefix.length > RLS_POLICY_PREFIX_MAX_LENGTH) {\n throw new Error(\n `defineContract: policy prefix \"${prefix}\" exceeds the ${RLS_POLICY_PREFIX_MAX_LENGTH}-character maximum (Postgres identifiers cap at 63 characters and the wire name appends a 9-character hash suffix).`,\n );\n }\n const coordinate = requireLocalTarget(refs, `policy \"${prefix}\"`);\n if (!enablements.has(coordinateKey(coordinate))) {\n const target = refs['target'];\n throw new Error(\n `defineContract: policy \"${prefix}\" targets model \"${target?.modelName ?? coordinate.tableName}\", whose table is not RLS-enabled. Add rlsEnabled(<model>) to the entities list.`,\n );\n }\n const prefixKey = `${coordinate.namespaceId} ${prefix}`;\n if (seenPrefixes.has(prefixKey)) {\n throw new Error(\n `defineContract: policy prefix \"${prefix}\" is declared more than once in namespace \"${coordinate.namespaceId}\". Policy prefixes must be unique per namespace.`,\n );\n }\n seenPrefixes.add(prefixKey);\n\n const roleNames = [...new Set(policy.roles.map((roleHandle) => roleHandle.name))].sort();\n rows.push({\n namespaceId: coordinate.namespaceId,\n entityKind: 'policy',\n key: prefix,\n entity: buildRlsPolicyEntity({\n prefix,\n tableName: coordinate.tableName,\n namespaceId: coordinate.namespaceId,\n operation: policy.operation,\n roles: roleNames,\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n }),\n });\n }\n\n for (const { coordinate, entity } of enablements.values()) {\n rows.push({\n namespaceId: coordinate.namespaceId,\n entityKind: 'rls',\n key: coordinate.tableName,\n entity,\n });\n }\n for (const [name, entity] of roles) {\n rows.push({ namespaceId: UNBOUND_NAMESPACE_ID, entityKind: 'role', key: name, entity });\n }\n return rows;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkDA,MAAa,yBAAyB,EACpC,IAAI,EACF,MAAM;CACJ,MAAM;CACN,cAAc;EAAE,OAAO;EAAG,YAAY;CAAc;CACpD,QAAQ,EACN,SAAS,iBACX;AACF,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E,YAAY,YAAY,YAAY,OAAO,GACtD,KAAK,KAAK;EACR,aAAa,WAAW;EACxB,YAAY;EACZ,KAAK,WAAW;EAChB;CACF,CAAC;CAEH,KAAK,MAAM,CAAC,MAAM,WAAW,OAC3B,KAAK,KAAK;EAAE,aAAa;EAAsB,YAAY;EAAQ,KAAK;EAAM;CAAO,CAAC;CAExF,OAAO;AACT"}
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
//#region src/core/rls/canonicalize.d.ts
|
|
2
2
|
type RlsPolicyOperation = 'select' | 'insert' | 'update' | 'delete' | 'all';
|
|
3
|
+
/**
|
|
4
|
+
* Which predicate each RLS operation admits, mirroring Postgres: SELECT and
|
|
5
|
+
* DELETE decide row visibility/eligibility with `USING` only; INSERT
|
|
6
|
+
* validates the new row with `WITH CHECK` only; UPDATE and ALL take either
|
|
7
|
+
* or both. Single-homed here so the PSL lowering and the TS handle
|
|
8
|
+
* constructors enforce the same matrix.
|
|
9
|
+
*/
|
|
10
|
+
declare const POLICY_OPERATION_PREDICATES: Readonly<Record<RlsPolicyOperation, {
|
|
11
|
+
readonly using: boolean;
|
|
12
|
+
readonly withCheck: boolean;
|
|
13
|
+
}>>;
|
|
3
14
|
interface ContentHashParts {
|
|
4
15
|
readonly using?: string;
|
|
5
16
|
readonly withCheck?: string;
|
|
@@ -33,5 +44,5 @@ declare function normalizePredicate(sql: string): string;
|
|
|
33
44
|
*/
|
|
34
45
|
declare function computeContentHash(parts: ContentHashParts): string;
|
|
35
46
|
//#endregion
|
|
36
|
-
export { normalizePredicate as i,
|
|
37
|
-
//# sourceMappingURL=canonicalize-
|
|
47
|
+
export { normalizePredicate as a, computeContentHash as i, POLICY_OPERATION_PREDICATES as n, RlsPolicyOperation as r, ContentHashParts as t };
|
|
48
|
+
//# sourceMappingURL=canonicalize-D1F4vUnP.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonicalize-D1F4vUnP.d.mts","names":[],"sources":["../src/core/rls/canonicalize.ts"],"mappings":";KAEY,kBAAA;AAAZ;;;;AAA8B;AAS9B;;AATA,cASa,2BAAA,EAA6B,QAAA,CACxC,MAAA,CAAO,kBAAA;EAAA,SAA+B,KAAA;EAAA,SAAyB,SAAA;AAAA;AAAA,UAShD,gBAAA;EAAA,SACN,KAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;EAAA,SACA,SAAA,EAAW,kBAAkB;EAAA,SAC7B,UAAA;AAAA;;AAd+D;AAS1E;;;;;;;;;;;AAKqB;iBAiBL,kBAAA,CAAmB,GAAW;;;;AAAA;AAa9C;;;;AAA0D;iBAA1C,kBAAA,CAAmB,KAAuB,EAAhB,gBAAgB"}
|
package/dist/contract-free.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as DropDefaultAction, l as PostgresCreateSchema, r as AnyAlterTableAction, s as PostgresAlterTable, t as AddColumnAction, u as PostgresCreateTable } from "./nodes-
|
|
1
|
+
import { a as DropDefaultAction, l as PostgresCreateSchema, r as AnyAlterTableAction, s as PostgresAlterTable, t as AddColumnAction, u as PostgresCreateTable } from "./nodes-Dv5eCSq9.mjs";
|
|
2
2
|
import { t as PostgresTableSource } from "./table-source-BvFo7gVs.mjs";
|
|
3
3
|
import { DdlColumn, DdlNode, DdlTableConstraint, SelectAst } from "@prisma-next/sql-relational-core/ast";
|
|
4
4
|
import { CfExpr, ColumnDescriptor, ColumnSchema, TableHandle } from "@prisma-next/sql-relational-core/contract-free";
|
package/dist/contract-free.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as PG_TEXT_ARRAY_CODEC_ID, d as PG_INT8_CODEC_ID, m as PG_JSONB_CODEC_ID, u as PG_INT4_CODEC_ID, v as PG_TEXT_CODEC_ID, y as PG_TIMESTAMPTZ_CODEC_ID } from "./codec-ids-C_-Hj6bL.mjs";
|
|
2
|
-
import { l as PostgresTableSource } from "./postgres-schema-
|
|
3
|
-
import { C as rlsPolicyExistsAst, D as toRegclass, E as tablePrimaryKeyAst, S as rlsEnabledAst, T as tableIsEmptyAst, _ as extensionExistsAst, a as createSchema, f as columnDefaultAst, g as constraintExistsAst, h as columnTypeAst, l as dropDefaultAction, m as columnNullabilityAst, o as createTable, p as columnExistsAst, r as alterTable, t as addColumnAction, v as indexExistsAst, w as tableExistsAst, x as noNullValuesAst } from "./ddl-
|
|
2
|
+
import { l as PostgresTableSource } from "./postgres-schema-ChBj22nX.mjs";
|
|
3
|
+
import { C as rlsPolicyExistsAst, D as toRegclass, E as tablePrimaryKeyAst, S as rlsEnabledAst, T as tableIsEmptyAst, _ as extensionExistsAst, a as createSchema, f as columnDefaultAst, g as constraintExistsAst, h as columnTypeAst, l as dropDefaultAction, m as columnNullabilityAst, o as createTable, p as columnExistsAst, r as alterTable, t as addColumnAction, v as indexExistsAst, w as tableExistsAst, x as noNullValuesAst } from "./ddl-eBZav_MS.mjs";
|
|
4
4
|
import { col, fn, lit, table } from "@prisma-next/sql-relational-core/contract-free";
|
|
5
5
|
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
|
|
6
6
|
//#region src/contract-free/columns.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as isPostgresSchema } from "./postgres-schema-
|
|
1
|
+
import { r as isPostgresSchema } from "./postgres-schema-ChBj22nX.mjs";
|
|
2
2
|
import { i as quoteIdentifier } from "./sql-utils-SU4FDvIV.mjs";
|
|
3
3
|
import { n as PostgresNativeEnumSchemaNode, o as postgresNodeEntityKind, r as PostgresSchemaNodeKind, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-D6LvInCe.mjs";
|
|
4
|
-
import { A as SetDefaultCall, C as DropNativeEnumTypeCall, D as EnableRowLevelSecurityCall, E as DropTableCall, M as postgresDefaultToDdlColumnDefault, N as buildTargetDetails, O as RawSqlCall, S as DropIndexCall, _ as DisableRowLevelSecurityCall, a as AddNotNullColumnDirectCall, b as DropConstraintCall, c as AddUniqueCall, d as CreateIndexCall, f as CreateNativeEnumTypeCall, g as DataTransformCall, h as CreateTableCall, i as AddNativeEnumValueCall, j as SetNotNullCall, l as AlterColumnTypeCall, m as CreateSchemaCall, n as AddColumnCall, o as AddNotNullColumnWithTempDefaultCall, r as AddForeignKeyCall, s as AddPrimaryKeyCall, t as AddCheckConstraintCall, v as DropCheckConstraintCall, w as DropNotNullCall, x as DropDefaultCall, y as DropColumnCall } from "./op-factory-call-
|
|
5
|
-
import { t as buildExpectedFormatType } from "./planner-sql-checks-
|
|
4
|
+
import { A as SetDefaultCall, C as DropNativeEnumTypeCall, D as EnableRowLevelSecurityCall, E as DropTableCall, M as postgresDefaultToDdlColumnDefault, N as buildTargetDetails, O as RawSqlCall, S as DropIndexCall, _ as DisableRowLevelSecurityCall, a as AddNotNullColumnDirectCall, b as DropConstraintCall, c as AddUniqueCall, d as CreateIndexCall, f as CreateNativeEnumTypeCall, g as DataTransformCall, h as CreateTableCall, i as AddNativeEnumValueCall, j as SetNotNullCall, l as AlterColumnTypeCall, m as CreateSchemaCall, n as AddColumnCall, o as AddNotNullColumnWithTempDefaultCall, r as AddForeignKeyCall, s as AddPrimaryKeyCall, t as AddCheckConstraintCall, v as DropCheckConstraintCall, w as DropNotNullCall, x as DropDefaultCall, y as DropColumnCall } from "./op-factory-call-Dwsb1xzl.mjs";
|
|
5
|
+
import { t as buildExpectedFormatType } from "./planner-sql-checks-Cx0ATsPc.mjs";
|
|
6
6
|
import { n as buildColumnTypeSql, t as buildColumnDefaultSql } from "./planner-ddl-builders-BKlmGDJl.mjs";
|
|
7
7
|
import { n as resolveIdentityValue } from "./planner-identity-values-CJPha2Sz.mjs";
|
|
8
8
|
import { i as hasUniqueConstraint, n as hasForeignKey, t as buildSchemaLookupMap } from "./planner-schema-lookup-CiVaAQP-.mjs";
|
|
@@ -1282,4 +1282,4 @@ function resolvePostgresNodeIssueControlPolicySubject(issue, contract) {
|
|
|
1282
1282
|
//#endregion
|
|
1283
1283
|
export { resolvePostgresNodeIssueCreationFactoryName as a, issueSchemaName as c, postgresNodeStorageCoordinate as d, resolvePostgresNodeIssueControlPolicySubject as i, planIssues as l, resolveNamespaceIdForDdlSchema as n, coalesceSubtreeIssues as o, resolvePostgresCallControlPolicySubject as r, issueNode as s, renderPostgresSuppression as t, postgresPlannerStrategies as u };
|
|
1284
1284
|
|
|
1285
|
-
//# sourceMappingURL=control-policy-
|
|
1285
|
+
//# sourceMappingURL=control-policy-BfQLCrha.mjs.map
|