viborm 1.5.1 → 1.7.0
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 +4 -2
- package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DNY4JWFC.mjs} +1 -1
- package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DNY4JWFC.mjs.map} +1 -1
- package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-BMss0hKo.mjs} +2 -2
- package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-BMss0hKo.mjs.map} +1 -1
- package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-Bz3WtMBa.mjs} +1 -1
- package/dist/{adapter-result-parser-B63ouFIz.mjs.map → adapter-result-parser-Bz3WtMBa.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BU1R9byi.mjs → array-literal-DfgmVxKI.mjs} +1 -1
- package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-DfgmVxKI.mjs.map} +1 -1
- package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-DWMYN0fw.mjs} +2 -2
- package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-DWMYN0fw.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-Bjgx1lMC.mjs +2 -0
- package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-Bjgx1lMC.mjs.map} +1 -1
- package/dist/builder-B4n-7I7Q.mjs +2 -0
- package/dist/{builder-ClblW6Lj.mjs.map → builder-B4n-7I7Q.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-B6J5VbLv.mjs} +1 -1
- package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-B6J5VbLv.mjs.map} +1 -1
- package/dist/chain-DVuRxjPO.mjs +2 -0
- package/dist/chain-DVuRxjPO.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/{client-DyIsSin0.d.mts → client-7ApJka0M.d.mts} +3 -3
- package/dist/client-Yqn0LqmI.mjs +2 -0
- package/dist/client-Yqn0LqmI.mjs.map +1 -0
- package/dist/{client-C1MxqFtt.mjs → client-l7dSOul5.mjs} +13 -13
- package/dist/client-l7dSOul5.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-DXbsDHLj.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-DXbsDHLj.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/{current-CKQ4EgeM.mjs → current-nScH-oH5.mjs} +1 -1
- package/dist/{current-CKQ4EgeM.mjs.map → current-nScH-oH5.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-DfVmz14E.mjs → datetime-physical-codec-DTdvABny.mjs} +2 -2
- package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-DTdvABny.mjs.map} +1 -1
- package/dist/driver-CK_IKqDa.mjs +2 -0
- package/dist/{driver-aqfbJdZC.mjs.map → driver-CK_IKqDa.mjs.map} +1 -1
- package/dist/{driver-DpQbSOUD.mjs → driver-DaBNytbz.mjs} +2 -2
- package/dist/{driver-DpQbSOUD.mjs.map → driver-DaBNytbz.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-D--MVRCY.mjs +2 -0
- package/dist/error-mapping-D--MVRCY.mjs.map +1 -0
- package/dist/every-6VrIclsx.mjs +2 -0
- package/dist/{every-BUf842ai.mjs.map → every-6VrIclsx.mjs.map} +1 -1
- package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-CfvH8Fxa.mjs} +2 -2
- package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-CfvH8Fxa.mjs.map} +1 -1
- package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-DvHcWF3g.mjs} +2 -2
- package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-DvHcWF3g.mjs.map} +1 -1
- package/dist/geo-point-codec-CIZxuIvE.mjs +2 -0
- package/dist/geo-point-codec-CIZxuIvE.mjs.map +1 -0
- package/dist/{hydration-BK6vRndL.mjs → hydration-BUBkHlCK.mjs} +2 -2
- package/dist/{hydration-BK6vRndL.mjs.map → hydration-BUBkHlCK.mjs.map} +1 -1
- package/dist/identifier-conversion-BXrBYgAq.mjs +2 -0
- package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-BXrBYgAq.mjs.map} +1 -1
- package/dist/{identity-Bu6jbgym.mjs → identity-BtuwgqhS.mjs} +2 -2
- package/dist/{identity-Bu6jbgym.mjs.map → identity-BtuwgqhS.mjs.map} +1 -1
- package/dist/{index-Ci8b13Lm.d.mts → index-CsO6vG2h.d.mts} +71 -14
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/insert-value-Cbp_bNxj.mjs +2 -0
- package/dist/insert-value-Cbp_bNxj.mjs.map +1 -0
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-Dw9UB49x.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-Dw9UB49x.mjs.map} +1 -1
- package/dist/{json-number-CAfNAqDB.mjs → json-number-ChtP7ZeY.mjs} +1 -1
- package/dist/{json-number-CAfNAqDB.mjs.map → json-number-ChtP7ZeY.mjs.map} +1 -1
- package/dist/{key-DJXcPZR_.mjs → key-Cz83fdLO.mjs} +2 -2
- package/dist/{key-DJXcPZR_.mjs.map → key-Cz83fdLO.mjs.map} +1 -1
- package/dist/keys-EP1Eq2eD.mjs +2 -0
- package/dist/keys-EP1Eq2eD.mjs.map +1 -0
- package/dist/{libsql-Dmtj0O4E.mjs → libsql-ClGi2zY2.mjs} +3 -3
- package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-ClGi2zY2.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-b-dafk9S.mjs → memory-B1GnzgZr.mjs} +2 -2
- package/dist/{memory-b-dafk9S.mjs.map → memory-B1GnzgZr.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-DsXZ_pHE.mjs +2 -0
- package/dist/model-DsXZ_pHE.mjs.map +1 -0
- package/dist/mysql-adapter-D-Dq2FN9.mjs +2 -0
- package/dist/mysql-adapter-D-Dq2FN9.mjs.map +1 -0
- package/dist/{mysql-DAaUSeBw.mjs → mysql-hoo290Dd.mjs} +6 -6
- package/dist/{mysql-DAaUSeBw.mjs.map → mysql-hoo290Dd.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/{native-types-BbKWN3JV.mjs → native-types-CQH05hcr.mjs} +1 -1
- package/dist/{native-types-BbKWN3JV.mjs.map → native-types-CQH05hcr.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-23DWxZVY.mjs +2 -0
- package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
- package/dist/{object-store-BHyP-LEI.d.mts → object-store-9VfS-3sY.d.mts} +4 -4
- package/dist/{object-store-I1MyfM72.mjs → object-store-DdgcT8d9.mjs} +2 -2
- package/dist/{object-store-I1MyfM72.mjs.map → object-store-DdgcT8d9.mjs.map} +1 -1
- package/dist/on.d.mts +80 -0
- package/dist/on.mjs +2 -0
- package/dist/on.mjs.map +1 -0
- package/dist/ordering.d.mts +101 -0
- package/dist/ordering.mjs +11 -0
- package/dist/ordering.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CAZ_LauY.mjs → physical-t_gDjUCD.mjs} +2 -2
- package/dist/{physical-CAZ_LauY.mjs.map → physical-t_gDjUCD.mjs.map} +1 -1
- package/dist/pinned-session-De2rDjdO.mjs +2 -0
- package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-De2rDjdO.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-BDLdDieE.d.mts → planner-Cc3ABIUU.d.mts} +22 -1
- package/dist/{postgres-HaFcFACt.mjs → postgres-CqcP_qv-.mjs} +44 -37
- package/dist/postgres-CqcP_qv-.mjs.map +1 -0
- package/dist/postgres-adapter-CYZAL2uo.mjs +2 -0
- package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-CYZAL2uo.mjs.map} +1 -1
- package/dist/postgres-adapter-_o6EWuxW.mjs +2 -0
- package/dist/postgres-adapter-_o6EWuxW.mjs.map +1 -0
- package/dist/postgres-result-D94PyZ78.mjs +2 -0
- package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-D94PyZ78.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-kO9B3KCF.mjs} +2 -2
- package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-kO9B3KCF.mjs.map} +1 -1
- package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
- package/dist/query-CTna5P9o.mjs.map +1 -0
- package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-5hindjxU.mjs} +1 -1
- package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-5hindjxU.mjs.map} +1 -1
- package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-Dkgy-xcy.mjs} +1 -1
- package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-Dkgy-xcy.mjs.map} +1 -1
- package/dist/result-shape-uaCsF_SZ.mjs +2 -0
- package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-uaCsF_SZ.mjs.map} +1 -1
- package/dist/rows-AtX0guAb.mjs +2 -0
- package/dist/rows-AtX0guAb.mjs.map +1 -0
- package/dist/scalar-CZ_q89Hc.mjs +4 -0
- package/dist/scalar-CZ_q89Hc.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-CZTCxG2p.mjs +2 -0
- package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CZTCxG2p.mjs.map} +1 -1
- package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-DoZHc1o7.mjs} +2 -2
- package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-DoZHc1o7.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-BtNtBsUh.mjs} +2 -2
- package/dist/select-assembly-BtNtBsUh.mjs.map +1 -0
- package/dist/{settle-B9Vg1FnP.mjs → settle-v6QhvFkm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-v6QhvFkm.mjs.map} +1 -1
- package/dist/{sha256-DDEbgnTU.mjs → sha256-D_fCV62w.mjs} +1 -1
- package/dist/{sha256-DDEbgnTU.mjs.map → sha256-D_fCV62w.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
- package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CV2qkIKN.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CV2qkIKN.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CnAwmszh.mjs +2 -0
- package/dist/sqlite-adapter-CnAwmszh.mjs.map +1 -0
- package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DztTzv08.mjs} +2 -2
- package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DztTzv08.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-Ci8ROrql.mjs} +2 -2
- package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-Ci8ROrql.mjs.map} +1 -1
- package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-DO0ej03b.mjs} +1 -1
- package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-DO0ej03b.mjs.map} +1 -1
- package/dist/to-many-BtLpp5cW.mjs +2 -0
- package/dist/{to-many-CUBK3CTd.mjs.map → to-many-BtLpp5cW.mjs.map} +1 -1
- package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Km-Gr-a3.mjs} +1 -1
- package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Km-Gr-a3.mjs.map} +1 -1
- package/dist/{types-BNR3u6hH.mjs → types-C4v6iAmY.mjs} +1 -1
- package/dist/{types-BNR3u6hH.mjs.map → types-C4v6iAmY.mjs.map} +1 -1
- package/dist/{utils-Be91XL14.mjs → utils-CAACs9Jw.mjs} +3 -3
- package/dist/utils-CAACs9Jw.mjs.map +1 -0
- package/dist/v-Pb_jJOjC.mjs +2 -0
- package/dist/{v-lthABIXD.mjs.map → v-Pb_jJOjC.mjs.map} +1 -1
- package/dist/validation-BSpO4DjI.mjs +2 -0
- package/dist/{validation-BfJaNYMf.mjs.map → validation-BSpO4DjI.mjs.map} +1 -1
- package/dist/validation-pfpKPPZ_.mjs +2 -0
- package/dist/validation-pfpKPPZ_.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-Dthaj1Hz.mjs +2 -0
- package/dist/validator-Dthaj1Hz.mjs.map +1 -0
- package/dist/version-DvynkoaW.mjs +2 -0
- package/dist/{version-DAFcmokN.mjs.map → version-DvynkoaW.mjs.map} +1 -1
- package/dist/write-sinks-3IKCDF-S.mjs +2 -0
- package/dist/write-sinks-3IKCDF-S.mjs.map +1 -0
- package/dist/writes-BX5fLiw5.mjs +2 -0
- package/dist/writes-BX5fLiw5.mjs.map +1 -0
- package/package.json +55 -15
- package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
- package/dist/builder-ClblW6Lj.mjs +0 -2
- package/dist/chain-C1VPkUpC.mjs +0 -2
- package/dist/chain-C1VPkUpC.mjs.map +0 -1
- package/dist/client-C1MxqFtt.mjs.map +0 -1
- package/dist/client-DHf2ZfRe.mjs +0 -2
- package/dist/client-DHf2ZfRe.mjs.map +0 -1
- package/dist/driver-aqfbJdZC.mjs +0 -2
- package/dist/error-mapping-Zett_Pnt.mjs +0 -2
- package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
- package/dist/every-BUf842ai.mjs +0 -2
- package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
- package/dist/geo-point-codec-DcUTvoEg.mjs.map +0 -1
- package/dist/identifier-conversion-8ldidfgu.mjs +0 -2
- package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
- package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
- package/dist/normalized-result-VunNi4ID.mjs +0 -2
- package/dist/pinned-session-D8bM5obl.mjs +0 -2
- package/dist/postgres-HaFcFACt.mjs.map +0 -1
- package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
- package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
- package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
- package/dist/postgres-result-D4_yZqO8.mjs +0 -2
- package/dist/result-shape-BuGfArOr.mjs +0 -2
- package/dist/rows-BlONp14o.mjs +0 -2
- package/dist/rows-BlONp14o.mjs.map +0 -1
- package/dist/scalar-B3WLZzJj.mjs +0 -4
- package/dist/scalar-B3WLZzJj.mjs.map +0 -1
- package/dist/schema-B_Bc7TQ2.mjs +0 -2
- package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
- package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
- package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
- package/dist/to-many-CUBK3CTd.mjs +0 -2
- package/dist/utils-Be91XL14.mjs.map +0 -1
- package/dist/v-lthABIXD.mjs +0 -2
- package/dist/validation-BfJaNYMf.mjs +0 -2
- package/dist/validation-DN1N2OdK.mjs.map +0 -1
- package/dist/validator-BJhI364k.mjs +0 -2
- package/dist/validator-BJhI364k.mjs.map +0 -1
- package/dist/version-DAFcmokN.mjs +0 -2
- /package/dist/{contract-Dw0FR78e.d.mts → contract-CYl0OzhZ.d.mts} +0 -0
- /package/dist/{sql-Q_twK-wW.d.mts → sql-BnXk8adi.d.mts} +0 -0
package/dist/permissions.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./base-wlv81COV.mjs";import{o as n,r}from"./validation-DN1N2OdK.mjs";import{t as i}from"./v-lthABIXD.mjs";const a=new Set([`optional`,`nullable`,`lazyRef`]);function refuse(e,n,i){throw new r(`viborm/permissions: ${e}`,{meta:{extension:`viborm.permissions`,...n&&{model:n}},...i!==void 0&&{cause:t(i)}})}function mayBeNull(e,t){let{type:n,options:r,value:i,wrapped:a}=e;return n===`nullable`||r?.nullable===!0||n===`json`&&r?.array!==!0||r?.schema!==void 0||r?.transform!==void 0&&!t.has(e)?!0:n===`literal`?i===null:n===`union`&&Array.isArray(r)?r.some(e=>mayBeNull(e,t)):n===`optional`||n===`lazyRef`?mayBeNull(a,t):n===`transform`||n===`pipe`}function walk(e,t,n){let r=e,i=!1,o=!1,s=!1;for(;;){let{type:e,wrapped:t,options:c,acceptsUndefined:l}=r;if(i||=l===!0||c?.optional===!0,o||=mayBeNull(r,n),s||=c?.transform!==void 0&&!n.has(r)||c?.schema!==void 0||e===`transform`||e===`pipe`,e===void 0||!a.has(e))break;r=t}let{type:c,entries:l,options:u,value:d,item:f}=r;if(c!==`object`&&c!==`record`&&c!==`array`)return{optional:i,nullable:o,uncertain:s};let p;return c===`array`?p={optional:i,nullable:o,uncertain:s,item:walk(f,`${t}[]`,n)}:c===`record`?p={optional:i,nullable:o,uncertain:s,any:walk(d,`${t}.*`,n)}:(u?.strict===!1&&refuse(`the actor schema admits unknown keys at "${t}": a path it does not declare would be read`),p={optional:i,nullable:o,uncertain:s,keys:new Map(Object.entries(l).filter(([e])=>!u?.omit?.includes(e)).map(([e,r])=>[e,walk(r,t===`actor`?e:`${t}.${e}`,n)]))}),u?.array?{optional:i,nullable:o,uncertain:s,item:p}:p}function bindingSchema(e,t=new WeakMap,n=new Set,r=`actor`,a=new WeakSet){let o=typeof e==`function`?e():e,s=t.get(o);if(s!==void 0)return s;n.has(o)&&refuse(`the actor schema is recursive at "${r}": its paths are not finite`),n.add(o);let child=(e,i=r)=>bindingSchema(e,t,n,i,a),c=o;if(o.type===`object`){let{transform:e,refuse:t,...n}=o.options??{},s=n.partial!==!1&&n.atLeast===void 0,prune=e=>{let t=e;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t};c=i.object(Object.fromEntries(Object.entries(o.entries).map(([e,t])=>[e,child(t,r===`actor`?e:`${r}.${e}`)])),{...n,partial:!1,refuse:s&&t?e=>t(prune(e)):t,transform:s?n=>{let r=t?n:prune(n);return e?e(r):r}:e}),s&&e===void 0&&a.add(c)}else o.type===`optional`?c=i.optional(child(o.wrapped),o.default):o.type===`nullable`?c=i.nullable(child(o.wrapped)):o.type===`lazyRef`?c=child(o.wrapped):o.type===`array`?c=i.array(child(o.item)):o.type===`record`?c=i.record(o.key,child(o.value)):o.type===`union`&&Array.isArray(o.options)?c=i.union(o.options.map(e=>child(e))):o.type===`pipe`&&(c=i.pipe(child(o.schema),...o.actions));let acceptsUndefined=e=>{let t=e;return t.acceptsUndefined===!0||t.type===`literal`&&t.value===void 0};return c!==o&&(o.type===`union`&&Array.isArray(o.options)&&o.options.some(e=>acceptsUndefined(child(e)))||o.type===`pipe`&&acceptsUndefined(child(o.schema))||o.type===`nullable`&&acceptsUndefined(child(o.wrapped)))&&Object.defineProperty(c,`acceptsUndefined`,{value:!0}),n.delete(o),t.set(o,c),c}function actorContract(e){e?.type!==`object`&&refuse(`the actor must be a viborm/validation object schema (v.object)`);let t=new WeakSet,n=bindingSchema(e,new WeakMap,new Set,`actor`,t),r=walk(n,`actor`,t);return{hasPath(e){let t=r;for(let n of e.split(`.`))if(t=t.keys?.get(n)??t.any,t===void 0)return!1;return!0},availabilityPath(e){let t=r,n,i=e===void 0?[]:e.split(`.`);for(let r=0;r<i.length;r++){if(t.uncertain||t.any!==void 0||(t=t.keys?.get(i[r]),t===void 0))return e;(t.optional||t.nullable||t.uncertain)&&(n=i.slice(0,r+1).join(`.`))}return n},schema:n}}const o=Object.freeze({OR:Object.freeze([])}),s=`default`,c=`$access`,l=`$create`,u=new Set([`mandatory`,`actions`,`operations`,`fields`,`domains`]),d=new Set([`read`,`update`,`delete`]),f=new Set([`actor`,`levels`,`mandatory`,`models`,`cache`]),p=new Set([`read`,`write`]);function distance(e,t){let n=Array.from({length:e.length+1},(e,n)=>Array.from({length:t.length+1},(e,t)=>n===0?t:t===0?n:0));for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++){let a=e[r-1]===t[i-1]?0:1,o=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+a);r>1&&i>1&&e[r-1]===t[i-2]&&e[r-2]===t[i-1]&&(o=Math.min(o,n[r-2][i-2]+1)),n[r][i]=o}return n[e.length][t.length]}const m=new Set([`AND`,`OR`,`NOT`]),h=`$exists`,isEnclosingRow=e=>isRecord(e)&&Object.keys(e).length===2&&typeof e.$row==`string`&&Number.isSafeInteger(e.up)&&e.up>=0,existsOf=e=>{let[t,n]=Object.entries(e)[0];return[t,n]},g=new Set([`is`,`isNot`,`some`,`every`,`none`]),isRecord=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.getOwnPropertySymbols(e).length===0},isActorField=e=>isRecord(e)&&typeof e.actor==`string`&&Object.keys(e).length===1,isTrue=e=>Object.keys(e).length===0,membersOf=(e,t)=>Object.keys(e).length===1&&Array.isArray(e[t])?e[t]:[e];function and(e){if(e.includes(!1))return!1;let t=e.filter(e=>!isTrue(e)).flatMap(e=>membersOf(e,`AND`));return t.length<2?t[0]??{}:{AND:t}}function structuralKeys(){let e=new Map,t=new WeakMap,n=new Map,r=0,keyOf=i=>{switch(typeof i){case`number`:return Object.is(i,-0)?`n-0`:`n${i}`;case`string`:return`s${JSON.stringify(i)}`;case`bigint`:return`b${i}`;case`boolean`:case`undefined`:return`p${i}`;default:break}if(i===null)return`pnull`;if(i instanceof Date&&!Number.isNaN(i.getTime()))return`d${i.getTime()}`;if(!(Array.isArray(i)||isRecord(i))){let e=n.get(i);return e===void 0&&n.set(i,e=`o${r++}`),e}let a=t.get(i);if(a!==void 0)return a;let o=Array.isArray(i)?`[${i.map(keyOf).join(`,`)}]`:`{${Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${keyOf(i[e])}`).join(`,`)}}`;return a=e.get(o),a===void 0&&e.set(o,a=`#${r++}`),t.set(i,a),a},same=(e,t)=>e===t&&typeof e!=`number`||keyOf(e)===keyOf(t),distinct=e=>{let t=new Set;return e.filter(e=>{let n=keyOf(e);return t.has(n)?!1:(t.add(n),!0)})},or=e=>{let t=e.filter(e=>e!==!1);if(t.length===0)return!1;if(t.some(isTrue))return{};let n=distinct(t.flatMap(e=>membersOf(e,`OR`)));return n.length===1?n[0]:{OR:n}};return{keyOf,same,distinct,or}}function actionsOf(e,t,n){let r=new Map(t.actions?Object.entries(t.actions):n.map((e,t)=>[e,n.slice(t-1,t)])),i=new Map;for(let t of[...n,...r.keys(),...[...r.values()].flat()])t.includes(`,`)&&refuse(`models.${e}: "${t}" is not an individual action; commas group rules only`,e);for(let a of Object.keys(t)){if(u.has(a))continue;let o=`models.${e}.${a}`,s={rule:t[a],source:o},c=a.includes(`,`)?a.split(`,`).map(e=>e.replace(/^[ \t\r\n]+|[ \t\r\n]+$/g,``)):[a];for(let a of c){a.length===0&&refuse(`${o}: an action group cannot contain an empty member`,e),a===`within`&&refuse(`${o} was renamed to "mandatory"`,e),a===`arms`&&refuse(`${o}: arms was removed; assign rules to named actions`,e),u.has(a)&&refuse(`${o}: "${a}" is a key of the declaration, not an action`,e);let c=i.get(a);if(c!==void 0&&refuse(`${o}: action "${a}" already has a rule at ${c.source}`,e),i.set(a,s),r.has(a))continue;t.actions&&refuse(`${o}: neither an action ${e} lists in \`actions\` nor a key of the declaration (${[...u].join(`, `)}); unknown action "${a}"`,e);let l=[...u,...n].find(e=>e.toLowerCase()===a.toLowerCase()||distance(e,a)<=(e.length<=4?1:2));l!==void 0&&refuse(`${o}: spelled like "${l}"; rename the action, or list the model's \`actions\``,e),r.set(a,[])}}for(let e of[`update`,`delete`]){let t=r.get(e);t!==void 0&&(r.has(`read`)||r.set(`read`,[]),t.includes(`read`)||r.set(e,[...t,`read`]))}for(let[t,n]of r){(t===`arms`||t===`within`)&&refuse(`models.${e}: "${t}" is a retired declaration key, not an action`,e),u.has(t)&&refuse(`models.${e}: "${t}" is a key of the declaration, not an action`,e);for(let i of n)r.has(i)||refuse(`models.${e}.actions.${t} implies "${i}", which ${e} does not declare`,e)}let a=new Map;for(let e of r.keys()){let t=new Set,visit=e=>{if(!t.has(e)){t.add(e);for(let t of r.get(e))visit(t)}};visit(e),a.set(e,Object.freeze([...t]))}return{rules:i,closure:a,evidence:{names:[...r.keys()]}}}function evidenceOf(e,t){return actionsOf(t,e.models[t],e.levels??[]).evidence}function verbsOf(e){return Object.fromEntries(Object.entries(e.models).map(([e,{modes:t,reads:n,...r}])=>[e,Object.keys(n).length===0?r:{...r,reads:n}]))}function compilePolicy(e,t,n=actorContract(e.actor)){return policyCompiler(e,t,n).policy()}const _=Object.freeze({predicates:Object.freeze({[l]:o}),writes:Object.freeze({}),reads:Object.freeze({}),modes:Object.freeze({}),place:l,moves:Object.freeze({})}),v=Object.freeze([]);function policyCompiler(t,n,i=actorContract(t.actor)){let{keyOf:a,same:u,distinct:y,or:b}=structuralKeys(),x=Object.freeze([]),S=t.levels??x;new Set(S).size!==S.length&&refuse(`levels must list each action only once`);for(let e of Object.keys(t))f.has(e)||refuse(`"${e}" is not a key of the policy (${[...f].join(`, `)})`);for(let e of Object.keys(t.models))Object.hasOwn(n,e)||refuse(`models.${e}: the schema has no such model`,e);let C=new Map(Object.entries(n).map(([e,t])=>[t,e])),stateOf=e=>n[e][`~`].state,relationOf=(e,t)=>Object.hasOwn(stateOf(e).relations,t)?stateOf(e).relations[t][`~`]:void 0,targetOf=(e,t)=>{let n=relationOf(e,t)?.settleTarget();return C.get(n)},w=new Map(Object.entries(t.models).map(([e,t])=>[e,actionsOf(e,t,S)])),T=new Map,modelOf=e=>{let t=T.get(e);if(t)return t;let n=Object.freeze({name:e,actions:Object.freeze([...w.get(e)?.evidence.names??[]])});return T.set(e,n),n},E=new Map,D=new WeakMap,O=new Map,k=new Map,A=new WeakSet,j=[],scope=(e,t)=>({OR:[{$if:{control:`scopes`,path:`unrestricted`,equals:!0}},{$if:{control:`scopes`,path:`allowed`,has:`${e}.${t}`}}]}),ruleAt=(e,t)=>{let n=`${e}.${t}`,r=O.get(n);if(r!==void 0)return r;let i=w.get(e).rules.get(t),a=i?.rule===void 0?!1:lower(e,t,i.rule,i.source);E.set(n,a);let o=availableGrant(e,a);return O.set(n,o),o},M=new Map,restriction=e=>{let n=M.get(e);if(n!==void 0)return n;let admit=(t,n)=>{if(typeof t==`function`&&refuse(`${n}: mandatory is action-independent and cannot contain callbacks`,e),Array.isArray(t))for(let e of t)admit(e,n);else if(isRecord(t))for(let e of Object.values(t))admit(e,n)},r=t.models[e];admit(r.mandatory,`models.${e}.mandatory`),admit(t.mandatory,`mandatory`);let i=and([lower(e,`read`,r.mandatory??{},`models.${e}.mandatory`),lower(e,`read`,t.mandatory??{},`mandatory`)]);return M.set(e,i),i},P=(e,t)=>{let n=`${e}.${t}`,r=k.get(n);if(r!==void 0)return r;j.includes(n)&&refuse(`models.${n} reads itself: ${[...j.slice(j.indexOf(n)),n].join(` → `)}`,e),j.push(n);try{let r=w.get(e),i=r.rules.get(t)?.rule===!1?[]:[...r.closure].flatMap(([e,n])=>n.includes(t)?[e]:[]),a=b(i.map(t=>ruleAt(e,t))),o=and([restriction(e),absorb(e,a)]);if(o!==!1){let t=i.map(t=>summarizeReads(e,E.get(`${e}.${t}`),`source`,!0)),n=summarizeReads(e,restriction(e),`source`,!0);n!==null&&t.every(e=>e!==null)&&D.set(o,combineReads(!0,[n,combineReads(!1,t)]))}return k.set(n,o),o!==!1&&A.add(o),o}finally{j.pop()}},absorb=(e,t)=>{if(t===!1||!Array.isArray(t.OR))return t;let n=t.OR,r=new Set,i=and([restriction(e),t]);for(let t=0;t<n.length;t++){let a=n[t];for(let o=0;o<n.length;o++){if(o===t||r.has(o))continue;let s=n[o];if(!implies(e,a,s)||o>t&&implies(e,s,a))continue;let c=n.filter((e,n)=>n!==t&&!r.has(n)),l=and([restriction(e),b(c)]);if(preservesReads(e,i,l)){i=l,r.add(t);break}}}let a=n.filter((e,t)=>!r.has(t));return a.length===1?a[0]:{OR:a}},path=(e,t)=>{typeof t==`string`&&!i.hasPath(t)&&refuse(`${e} reads actor path "${t}", which the actor schema does not declare`)},value=(e,t)=>isActorField(t)?(path(e,t.actor),{control:`actor`,path:t.actor}):isRecord(t)?(t.control===`actor`&&path(e,t.path),Object.fromEntries(Object.entries(t).map(([t,n])=>[t,value(e,n)]))):t,conditions=(e,t,n=``)=>(isRecord(t)||refuse(`${e} tests the actor with a value that is not an object of its facts`),Object.keys(t).length===0&&refuse(`${e} tests the actor${n?` at "${n.slice(0,-1)}"`:``} with an empty object`),Object.entries(t).flatMap(([t,r])=>{let i=`${n}${t}`;return isRecord(r)?conditions(e,r,`${i}.`):(path(e,i),typeof r==`object`&&r&&refuse(`${e} tests actor path "${i}" against ${Array.isArray(r)?`a list`:`a value that is not a literal`}`),[{$if:r===null?{control:`actor`,path:i,exists:!1}:{control:`actor`,path:i,equals:r}}])})),evaluated=(e,t,n,i)=>{try{return e(t,modelOf(n))}catch(e){if(e instanceof r)throw e;return refuse(`${i}: the rule function threw at "${t}"`,n,e)}},lower=(e,t,r,i,a=[{model:e}])=>{if(typeof r==`boolean`)return r?{}:!1;if(typeof r==`function`)return lower(e,t,evaluated(r,t,e,i),i,a);isRecord(r)||refuse(`${i}: a rule is a boolean, a where object or a function of the action`,e);let o=stateOf(e),s={},c=[];for(let[l,u]of Object.entries(r))if(m.has(l)){let n=(Array.isArray(u)?u:[u]).map(n=>lower(e,t,n,i,a)),r=l===`OR`?b(n):and(l===`AND`?n:n.map(e=>e===!1?{}:isTrue(e)?!1:{NOT:e}));if(r===!1)return!1;c.push(r)}else if(l===`actor`&&!(Object.hasOwn(o.scalars,l)||Object.hasOwn(o.relations,l)))c.push(...conditions(i,u));else if(l===`$if`)isRecord(u)&&u.control===`actor`&&path(i,u.path),s[l]=u;else if(l===h){let r=isRecord(u)?Object.keys(u):[],[o]=r;(r.length!==1||!Object.hasOwn(n,o))&&refuse(`${i}: $exists names exactly one model of the schema and the where its rows must match`,e);let c=lower(o,t,u[o],i,[...a,{model:o}]);if(c===!1)return!1;s[l]={[o]:c}}else if(targetOf(e,l)!==void 0){let n=relation(e,t,l,u,i,a);if(n===!1)return!1;n!==void 0&&(s[l]=n)}else u===void 0&&refuse(`${i}: ${l} is compared with undefined, which holds for every row; compare with null, a literal or an actor value`,e),enclosingRows(e,l,u,i,a),s[l]=value(i,u);return and([s,...c])},enclosingRows=(e,t,n,r,i)=>{if(isEnclosingRow(n)){let a=`{ $row: ${JSON.stringify(n.$row)}, up: ${n.up} }`,o=i.length-1-n.up;o<0&&refuse(`${r}: ${t} compares ${a}, which reaches past the rule (${i.length-1} relation bodies deep here)`,e);let s=i.slice(o+1).find(e=>e.sealed);s&&refuse(`${r}: ${t} compares ${a} across a recursive relation to ${s.model}`,e);let c=i[o].model;Object.hasOwn(stateOf(c).scalars,n.$row)||refuse(`${r}: ${t} compares ${a}, and ${c} has no scalar field "${n.$row}"`,e);return}if(Array.isArray(n))for(let a of n)enclosingRows(e,t,a,r,i);else if(isRecord(n))for(let a of Object.values(n))enclosingRows(e,t,a,r,i)},relation=(e,t,n,r,i,a)=>{let o=targetOf(e,n);if(typeof r==`string`){modelOf(o).actions.includes(r)||refuse(`${i} reads ${n} at "${r}", which ${o} does not declare`,e);let t=P(o,r);return t===!1?!1:{is:t}}if(r===void 0&&refuse(`${i}: ${n} is filtered with undefined, which holds for every row`,e),typeof r==`object`&&r&&!isRecord(r)&&refuse(`${i} filters ${n} with a value that is not a filter object, an action name or null`,e),!isRecord(r))return r;if(!Object.keys(r).some(e=>g.has(e)))return lower(o,t,r,i,[...a,{model:o}]);let s={},c=!1,l={model:o,...r.recurse!==void 0&&{sealed:`recursive`}};for(let[e,n]of Object.entries(r)){if(!(g.has(e)&&n!==null)){s[e]=n;continue}let r=lower(o,t,n,i,[...a,l]);if(r!==!1)s[e]=r;else if(e===`is`||e===`some`)return!1;else e===`every`&&(c=!0)}return c&&(s.none={}),Object.keys(s).length===0?void 0:s},N=new Map(Object.keys(n).map(e=>[e,new Map])),implies=(e,t,n)=>{if(t===n)return!0;let r=N.get(e),i=a(t),o=r.get(i);o===void 0&&r.set(i,o=new Map);let s=a(n),c=o.get(s);return c===void 0&&o.set(s,c=provable(e,t,n)),c},provable=(e,t,n)=>{let r=conjuncts(n);if(r.length!==1)return r.every(n=>implies(e,t,n));let i=conjuncts(t),[a,o]=Object.entries(i[0]??{AND:[]})[0],[s,c]=Object.entries(r[0])[0];if(i.length===1&&a===`OR`)return o.every(t=>implies(e,t,n));if(s===`OR`&&c.some(n=>implies(e,t,n)))return!0;if(i.length!==1)return i.some(t=>implies(e,t,n));if(a!==s||!isRecord(o)||!isRecord(c))return a===s&&u(o,c);if(a===`NOT`)return implies(e,c,o);if(a===`$if`)return u(o,c)||narrower(o,c,`hasSome`);if(a===h){let[e,t]=existsOf(o),[n,r]=existsOf(c);return e===n&&implies(e,t,r)}let l=targetOf(e,a);if(l===void 0)return u(o,c)||narrower(o,c,`hasSome`)||narrower(o,c,`in`);let d=[...g].filter(e=>Object.hasOwn(c,e));return d.length===0?implies(l,o,c):d.every(e=>isRecord(o[e])&&isRecord(c[e])&&u(without(o,e),without(c,e))&&(e===`none`||e===`isNot`?implies(l,c[e],o[e]):implies(l,o[e],c[e])))},F=new WeakMap,conjuncts=e=>{let t=F.get(e);if(t!==void 0)return t;let n=Object.keys(e).length===1&&!Object.hasOwn(e,`AND`)?[e]:Object.entries(e).flatMap(([e,t])=>e===`AND`?t.flatMap(conjuncts):[{[e]:t}]);return F.set(e,n),n},without=(e,t)=>{let{[t]:n,...r}=e;return r},narrower=(e,t,n)=>Array.isArray(e[n])&&Array.isArray(t[n])&&u(without(e,n),without(t,n))&&e[n].every(e=>t[n].some(t=>u(e,t))),I=new Map,shared=e=>{if(e===!1)return e;let t=a(e),n=I.get(t);return n===void 0?(I.set(t,e),e):n},L=new WeakMap,negate=e=>{if(e===!1)return{};if(isTrue(e))return!1;if(Object.keys(e).length===1&&isRecord(e.NOT))return e.NOT;let t=L.get(e);if(t!==void 0)return t;let n=Array.isArray(e.AND)?guardOr(e.AND.map(e=>negate(e))):Array.isArray(e.OR)?guardAnd(e.OR.map(e=>negate(e))):shared({NOT:e});return L.set(e,n),n},R=new Map,combined=(e,t,n)=>{let r=e;for(let e of t)r+=e===!1?` F`:` ${a(e)}`;if(R.has(r))return R.get(r);let i=shared(n());return R.set(r,i),i},guardOr=e=>combined(`OR`,e,()=>b(e)),guardAnd=e=>combined(`AND`,e,()=>{let t=and(e);return t===!1||!Array.isArray(t.AND)?t:and(y(t.AND))}),z={yes:!1,no:{},reads:new Map},atomic=(e=new Map)=>({yes:!1,no:!1,reads:e}),combineReads=(e,t)=>{let n=(e?guardAnd:guardOr)(t.map(e=>e.yes)),r=(e?guardOr:guardAnd)(t.map(e=>e.no)),i=negate(e?r:n),a=new Map;for(let e of t)for(let[t,n]of e.reads){let e=guardAnd([i,n]);a.set(t,guardOr([a.get(t)??!1,e]))}return{yes:n,no:r,reads:a}},B=new Map(Object.keys(n).map(e=>[e,new WeakMap])),V=new Map(Object.keys(n).map(e=>[e,new WeakMap])),H=new Map(Object.keys(n).map(e=>[e,new WeakMap])),U=new Map(Object.keys(n).map(e=>[e,new WeakMap])),parameterKey=(e,t)=>isRecord(e)&&typeof e.control==`string`&&(e.path===void 0||typeof e.path==`string`)&&Object.keys(e).every(e=>e===`control`||e===`path`)?JSON.stringify([e.control,e.path??null,t]):void 0,containsParameter=e=>parameterKey(e,!1)!==void 0||(Array.isArray(e)?e.some(containsParameter):isRecord(e)&&Object.values(e).some(containsParameter)),W=new Set([`equals`,`not`,`in`,`notIn`,`lt`,`lte`,`gt`,`gte`,`contains`,`startsWith`,`endsWith`,`has`,`hasSome`,`hasEvery`,`isEmpty`]),scalarReads=e=>{let t=parameterKey(e,!1);if(t!==void 0)return atomic(new Map([[t,{}]]));if(!isRecord(e))return containsParameter(e)?null:atomic();if(Object.keys(e).length===0)return null;let n=new Map;for(let[t,r]of Object.entries(e)){if(t===`mode`||t===`path`)continue;if(!W.has(t))return null;let e=parameterKey(r,t===`in`||t===`notIn`);if(e!==void 0)n.set(e,{});else if(t===`not`||t===`equals`){let e=scalarReads(r);if(e===null)return null;for(let[t,r]of e.reads)n.set(t,r)}else if(Array.isArray(r)&&(t===`in`||t===`notIn`))for(let e of r){let t=parameterKey(e,!1);if(t!==void 0)n.set(t,{});else if(containsParameter(e))return null}else if(containsParameter(r))return null}return Object.keys(e).every(e=>e===`mode`||e===`path`)?null:atomic(n)},summarizeReads=(e,t,n=void 0,r=!1)=>{if(t===!1)return z;if(!isRecord(t))return null;if(n===`source`){let n=D.get(t);if(n!==void 0)return r?n:summarizeReads(e,t,`compiled`)}let i=(n===`compiled`?U:n?r?H:V:B).get(e),a=i.get(t);if(a!==void 0)return a;let o=[],unsupported=()=>(i.set(t,null),null);for(let[i,a]of Object.entries(t))if(m.has(i)){let t=Array.isArray(a)?a:[a],s=[];for(let a of t){let t=summarizeReads(e,a,n,r||i===`NOT`);if(t===null)return unsupported();s.push(i===`NOT`?{yes:t.no,no:t.yes,reads:t.reads}:t)}o.push(combineReads(i!==`OR`,s))}else if(i===`$if`){if(!isRecord(a))return unsupported();let e={$if:a};o.push({yes:e,no:negate(e),reads:new Map})}else if(i===h){let[e,t]=existsOf(a),i=summarizeReads(e,t,n,r);if(i===null)return unsupported();o.push(atomic(i.reads))}else if(Object.hasOwn(stateOf(e).scalars,i))if(n&&stateOf(e).scalars[i][`~`].state.type===`json`){let e=new Map,collect=t=>{let n=parameterKey(t,!1);if(n!==void 0)e.set(n,{});else if(isRecord(t)){let n=parameterKey(t.equals,!1);n!==void 0&&e.set(n,{}),isRecord(t.not)&&collect(t.not)}};collect(a),o.push(atomic(e))}else{let e=scalarReads(a);if(e===null&&!n)return unsupported();o.push(e??atomic())}else{let t=targetOf(e,i);if(t===void 0)return unsupported();if(a===null){o.push(atomic());continue}let s=[];if(isRecord(a)&&Object.keys(a).some(e=>g.has(e))){for(let[e,t]of Object.entries(a))if(g.has(e))s.push({body:t,negative:r||e===`every`||e===`none`||e===`isNot`});else if(e!==`recurse`&&e!==`self`)return unsupported()}else s.push({body:a,negative:r});let c=[];for(let{body:e,negative:r}of s){if(e===null){c.push(atomic());continue}let i=summarizeReads(t,e,n,r);if(i===null)return unsupported();c.push(atomic(i.reads))}o.push(combineReads(!0,c))}let s=combineReads(!0,o);return i.set(t,s),s},provesGuard=(e,t,n)=>t===!1||n!==!1&&(isTrue(n)||u(t,n)||implies(e,t,n)),provesPresence=(e,t)=>{if(e===!1)return!0;if(Array.isArray(e.AND))return e.AND.some(e=>provesPresence(e,t));if(Array.isArray(e.OR))return e.OR.every(e=>provesPresence(e,t));let n=isRecord(e.$if)?e.$if:void 0,r=isRecord(e.NOT)&&isRecord(e.NOT.$if)?e.NOT.$if:void 0,i=n??(r?.exists===!1?r:void 0);return i?.control===`actor`&&typeof i.path==`string`&&(i.path===t||i.path.startsWith(`${t}.`))&&(n===void 0||n.exists!==!1)},guardAlternatives=(e,t)=>{if(D.has(t))return t;let replace=(e,t)=>{let n=!1,r=Object.entries(e).map(([e,r])=>{let i=t(e,r);return n||=i!==r,[e,i]});return n?Object.fromEntries(r):e};return replace(t,(t,n)=>{if((t===`OR`||t===`AND`)&&Array.isArray(n)){let r=n.map(n=>t===`OR`?availableGrant(e,n):guardAlternatives(e,n));return r.some((e,t)=>e!==n[t])?r:n}if(t===h){let[e,t]=existsOf(n),r=guardAlternatives(e,t);return r===t?n:{[e]:r}}let r=targetOf(e,t);return r===void 0||!isRecord(n)?n:Object.keys(n).some(e=>g.has(e))?replace(n,(e,t)=>(e===`is`||e===`some`)&&isRecord(t)?guardAlternatives(r,t):t):guardAlternatives(r,n)})},availableGrant=(e,t)=>{if(t===!1)return t;let n=guardAlternatives(e,t),r=summarizeReads(e,n,`source`);if(r===null)return n;let a=[];for(let[t,n]of r.reads){let[r,o]=JSON.parse(t);if(r!==`actor`)continue;let s=i.availabilityPath(o??void 0);if(s===void 0)continue;let c={$if:{control:`actor`,path:s,exists:!0}};provesPresence(n,s)||provesGuard(e,n,c)||a.push(b([negate(n),c]))}return a.length===0?n:and([guardAnd(a),n])},preservesReads=(e,t,n)=>{let r=summarizeReads(e,t),i=summarizeReads(e,n);if(r===null||i===null)return!1;for(let[t,n]of r.reads){let r=i.reads.get(t)??!1;if(!(provesGuard(e,n,r)&&provesGuard(e,r,n)))return!1}return!0},conjoin=(e,t,n=[])=>{let r=and(t);if(r===!1)return!1;let i=[...conjuncts(r)],a=and([...n,...i]);for(let t=i.length-1;t>=0;t--){let r=i[t],covers=t=>implies(e,t,r);if(!(n.some(covers)||i.some((e,n)=>n!==t&&covers(e))))continue;let o=i.filter((e,n)=>n!==t),s=and([...n,...o]);preservesReads(e,a,s)&&(a=s,i.splice(t,1))}return and(i)},verbsFor=e=>{let n=modelOf(e),r=t.models[e].operations??{},i={};for(let[e,t]of[[`read`,`read`],[`update`,`update`],[`delete`,`delete`]]){let a=r[e]??t;n.actions.includes(a)&&(i[e]=a)}return i},keysOf=e=>Object.entries(stateOf(e).relations).flatMap(([n,r])=>{let i=r[`~`].state.foreignKey;if(i===void 0)return[];let a=targetOf(e,n),o=t.models[a]&&verbsFor(a).read,s=o?P(a,o):!1,c=s===!1?!1:{[n]:{is:s}},l=i.fields.every(t=>stateOf(e).scalars[t]?.[`~`].state.nullable===!0);return[{fields:i.fields,clause:l?b([and(i.fields.map(e=>({[e]:null}))),c]):c}]}),rootReads=(e,t,n,r,i=new Map)=>{if(isEnclosingRow(t)){t.up===n&&r.add(t.$row);return}if(typeof t!=`object`||!t||n>0&&A.has(t))return;let a=i.get(t)??new Set;if(!a.has(n)){if(i.set(t,a.add(n)),Array.isArray(t)){for(let a of t)rootReads(e,a,n,r,i);return}if(isRecord(t))for(let[a,o]of Object.entries(t)){if(a===`$if`)continue;if(a===h){let[e,t]=existsOf(o);rootReads(e,t,n+1,r,i);continue}let t=m.has(a)?void 0:targetOf(e,a);if(t===void 0||!isRecord(o)){rootReads(e,o,n,r,i);continue}if(!Object.keys(o).some(e=>g.has(e))){rootReads(t,o,n+1,r,i);continue}for(let e of g){let a=o[e];isRecord(a)&&rootReads(t,a,n+1,r,i)}}}},fieldsRead=(e,t,n)=>(rootReads(e,t,0,n),ownFields(e,t,n)),ownFields=(e,t,n)=>{for(let[r,i]of Object.entries(t))if(m.has(r))for(let t of Array.isArray(i)?i:[i])ownFields(e,t,n);else if(r===`$if`||r===h)continue;else if(targetOf(e,r)===void 0)n.add(r);else{for(let t of joinedOn(e,r))n.add(t);if(isRecord(i)&&i.self===!0)for(let t of g)isRecord(i[t])&&ownFields(e,i[t],n)}return n},holders=(e,t)=>Object.entries(stateOf(e).relations).filter(([,e])=>e[`~`].state.foreignKey?.fields.includes(t)).map(([e])=>e),joinedOn=(e,t)=>{let n=relationOf(e,t).state.foreignKey;if(n!==void 0)return n.fields;let r=new Set;for(let t of C.values())for(let n of Object.values(stateOf(t).relations)){let t=n[`~`].state.foreignKey;if(t!==void 0&&C.get(n[`~`].settleTarget())===e)for(let e of t.references)r.add(e)}return[...r]},G=new Map;for(let n of Object.keys(t.models)){let r=t.models[n],i=modelOf(n),a=e((e,t)=>(t!==void 0&&!i.actions.includes(t)&&refuse(`models.${n}.${e} names "${t}", which ${n} does not declare. Declared actions: ${i.actions.join(`, `)||`none`}. Add its rule or choose a declared action.`,n),t),`declared`),o=new Set(i.actions),claimName=(e,t)=>{o.has(e)&&refuse(`${t}: an action, a domain, the placement or a move already has the name "${e}"`,n),o.add(e)},c=r.operations??{};for(let e of Object.keys(c))d.has(e)||refuse(`models.${n}.operations.${e}: not a configurable operation; use read, update or delete (create always uses its own grant)`,n);for(let e of[`read`,`update`,`delete`])a(`operations.${e}`,c[e]);let u=verbsFor(n),f={},m=[],h={},g=stateOf(n);for(let[e,t]of Object.entries(r.fields??{})){let r=isRecord(t)?Object.keys(t).find(e=>!p.has(e)):``;r!==void 0&&refuse(`models.${n}.fields.${e}${r?`.${r}`:``}: a field entry takes only read and write`,n);let{read:i,write:o}=t;if(Object.hasOwn(g.scalars,e)||Object.hasOwn(g.relations,e)||refuse(`models.${n}.fields.${e}: ${n} has no such field`,n),o!==void 0)if(a(`fields.${e}.write`,o),o===u.update)f[e]=o;else{let t=`$write:${e}`;claimName(t,`models.${n}.fields.${e}.write`),f[e]=t,m.push([e,o])}i!==void 0&&(h[e]=a(`fields.${e}.read`,i))}claimName(l,`models.${n}.create`);let _=new Map(i.actions.map(e=>[e,e]));for(let e of Object.keys(r.domains??{}))claimName(e,`models.${n}.domains.${e}`),_.set(e,e);_.has(s)&&refuse(`models.${n}: "${s}" is the mode a call takes by default, not an action or a domain`,n),G.set(n,{...u,modes:Object.freeze(Object.fromEntries(_)),writes:f,protectedWrites:m,reads:h})}let compileModel=e=>{let n=t.models[e],r=modelOf(e),{writes:i,protectedWrites:a,reads:s,...u}=G.get(e),d=verbsFor(e),f=new Map,claim=(t,n,r)=>{f.has(t)&&refuse(`${n}: an action, a domain, the placement or a move already has the name "${t}"`,e),f.set(t,r)};for(let t of r.actions)f.set(t,and([P(e,t),scope(e,t)])||o);let p=w.get(e).evidence;for(let[t,n]of a)claim(`$write:${t}`,`models.${e}.fields.${t}.write`,and([d.update===void 0?!1:f.get(d.update),f.get(n)])||o);let m=P(e,`create`),h=keysOf(e);claim(l,`models.${e}.create`,conjoin(e,[m,scope(e,`create`),...h.map(({clause:e})=>e)])||o);let g=m===!1?new Set:fieldsRead(e,m,new Set),_={};for(let t of new Set([...g,...h.flatMap(({fields:e})=>e)])){let n=`move:${t}`,r=new Set([t,...holders(e,t)].map(e=>i[e]??d.update)),a=[d.read,...r.size===1?r:[]].filter(e=>e!==void 0).map(e=>f.get(e));claim(n,`models.${e}.fields.${t}`,conjoin(e,[g.has(t)?m:{},...h.filter(({fields:e})=>e.includes(t)).map(({clause:e})=>e)],a)||o),_[t]=n}for(let[t,r]of Object.entries(n.domains??{})){let n=`models.${e}.domains.${t}`;claim(t,n,lower(e,`read`,r,n)||o)}return Object.freeze({predicates:Object.freeze(Object.fromEntries(f)),...d,writes:Object.freeze(i),reads:Object.freeze(s),modes:u.modes,place:l,moves:Object.freeze(_),...p.names.length>0&&{evidence:Object.freeze({as:c,names:Object.freeze(p.names)})}})},K=new Map,modelAt=e=>{let n=K.get(e);if(n!==void 0)return n;let r=Object.hasOwn(t.models,e)?compileModel(e):_;return K.set(e,r),r},q,acyclicAt=e=>{if(q===void 0){for(let e of Object.keys(n))try{modelAt(e)}catch(e){if(!(e instanceof r))throw e}q=new Map([...recursion(K)].map(([e,t])=>[e,Object.freeze(t)]))}return q.get(e)??v},J=Object.freeze(Object.fromEntries([...w].flatMap(([e,t])=>[...t.closure].map(([t,n])=>[`${e}.${t}`,Object.freeze(n.map(t=>`${e}.${t}`))])))),Y=Object.freeze(Object.fromEntries(Object.keys(n).map(e=>{let t=G.get(e);if(t===void 0)return[e,_];let{read:n,update:r,delete:i,modes:a}=t;return[e,Object.freeze({...n!==void 0&&{read:n},...r!==void 0&&{update:r},...i!==void 0&&{delete:i},modes:a})]}))),X;return Object.freeze({scopes:J,declared:Y,model:modelAt,acyclic:acyclicAt,policy:()=>{if(X!==void 0)return X;let e={};for(let t of Object.keys(n)){let n=modelAt(t),r=acyclicAt(t);e[t]=r.length===0?n:Object.freeze({...n,acyclic:r})}return X=Object.freeze({control:`actor`,scopes:J,models:Object.freeze(e)}),X}});function recursion(t){let r=new Map,i=new Map(Object.keys(n).map(e=>[e,new WeakSet])),a=e((e,t)=>{if(!(!isRecord(t)||i.get(e).has(t))){i.get(e).add(t);for(let[n,i]of Object.entries(t)){if(m.has(n)){for(let t of Array.isArray(i)?i:[i])a(e,t);continue}if(n===h){a(...existsOf(i));continue}let t=targetOf(e,n);if(t===void 0||!isRecord(i))continue;if(t===e&&i.recurse!==void 0&&relationOf(e,n).state.foreignKey!==void 0){let t=r.get(e)??[];t.includes(n)||t.push(n),r.set(e,t)}let o=[...g].filter(e=>Object.hasOwn(i,e));o.length===0&&a(t,i);for(let e of o)a(t,i[e])}}},`walk`);for(let[e,n]of t)for(let t of Object.values(n.predicates))a(e,t);return r}}function declarationRevision(e,t){let n=[],r=new Set,visit=e=>{if(typeof e!=`object`||!e||t.has(e)||r.has(e))return!0;let i=Object.getPrototypeOf(e);if(Array.isArray(e)?i!==Array.prototype||!Array.from({length:e.length},(t,n)=>Object.hasOwn(e,n)).every(Boolean):i!==Object.prototype&&i!==null)return!1;r.add(e);let a=Reflect.ownKeys(e),o=[],s=[];for(let t of a){let n=Object.getOwnPropertyDescriptor(e,t);if(!(n&&`value`in n&&Object.is(Reflect.get(e,t),n.value))||(o.push(n.value),s.push(n.enumerable===!0),!visit(n.value)))return!1}return n.push({value:e,keys:a,values:o,enumerable:s,prototype:i}),!0};if(e.every(visit))return()=>n.every(({value:e,keys:t,values:n,enumerable:r,prototype:i})=>{let a=Reflect.ownKeys(e);return Object.getPrototypeOf(e)===i&&a.length===t.length&&t.every((t,i)=>{let o=Object.getOwnPropertyDescriptor(e,t);return a[i]===t&&o&&`value`in o&&Object.is(o.value,n[i])&&Object.is(Reflect.get(e,t),n[i])&&o.enumerable===r[i]})})}function declarationSnapshot(e,t){let n=new Map,copy=e=>{if(typeof e!=`object`||!e||t.has(e))return e;let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)return e;let i=n.get(e);if(i!==void 0)return i;let a=Array.isArray(e)?[]:Object.create(r);n.set(e,a);for(let t of Reflect.ownKeys(e)){if(Array.isArray(e)&&t===`length`)continue;let n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,{value:copy(n.value),enumerable:n.enumerable===!0,writable:!1,configurable:!1})}return Object.freeze(a)};return copy(e)}function plainFreezer(){let e=new Map,t=new Set,n=Symbol(`not plain`),copy=r=>{if(typeof r!=`object`||!r)return typeof r==`function`||typeof r==`symbol`?n:r;let i=e.get(r);if(i!==void 0)return i;if(t.has(r))return n;let a=Object.getPrototypeOf(r),o=Array.isArray(r);if(o?a!==Array.prototype:a!==Object.prototype&&a!==null)return n;t.add(r);try{let t=o?[]:Object.create(a);for(let e of Reflect.ownKeys(r)){if(o&&e===`length`)continue;let i=Object.getOwnPropertyDescriptor(r,e);if(typeof e!=`string`||!(`value`in i)||!i.enumerable)return n;let a=copy(i.value);if(a===n)return n;Object.defineProperty(t,e,{value:a,enumerable:!0,writable:!0,configurable:!0})}return o&&t.length!==r.length?n:(Object.freeze(t),e.set(r,t),t)}finally{t.delete(r)}};return e=>{let t=copy(e);return t===n?void 0:t}}const y=`viborm.permissions`,b={findMany:`read`,findFirst:`read`,findUnique:`read`,findFirstOrThrow:`read`,findUniqueOrThrow:`read`,count:`read`,aggregate:`read`,groupBy:`read`,exist:`read`,update:`update`,updateMany:`update`,delete:`delete`,deleteMany:`delete`};function refuseUnreachable(e){return async t=>{if(t.kind===`model`){let{model:r,operation:i}=t,a=e.get(r),o=b[i],s=t.controls?.as;if(!a.listed||o!==void 0&&!a.verbs.has(o)||typeof s==`string`&&!a.modes.has(s))throw new n(r,i)}return await t.proceed()}}function scopeSchema(e){return{"~standard":{version:1,vendor:y,validate(t){if(t===void 0)return{value:{unrestricted:!0,allowed:[]}};if(!Array.isArray(t))return{issues:[{message:`Scopes must be an array of model.permission names`}]};let n=new Set;for(let r of t){if(typeof r!=`string`||!Object.hasOwn(e,r))return{issues:[{message:`Unknown permission scope: ${typeof r==`string`?r:`expected a string`}`}]};for(let t of e[r])n.add(t)}return{value:{unrestricted:!1,allowed:[...n]}}}}}}function modesOf(e){let t=[s,...new Set(Object.values(e).flatMap(e=>Object.keys(e.modes)))],narrowing=(e,t)=>t===s||t===e.read?{}:{root:Object.hasOwn(e.modes,t)?e.modes[t]:o};return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.fromEntries(t.map(e=>[e,narrowing(n,e)]))]))}function selfKeyed(e,t){let n=e[t][`~`].state.relations;return Object.values(n).some(n=>n[`~`].state.foreignKey!==void 0&&n[`~`].settleTarget()===e[t])}function reachOf(e,t){return new Map(Object.entries(t).map(([t,n])=>[t,{listed:Object.hasOwn(e.models,t),verbs:new Set([...[`read`,`update`,`delete`].filter(e=>n[e]!==void 0)]),modes:new Set([s,...Object.keys(n.modes)])}]))}function permissions(e){let t=actorContract(e.actor),compile=n=>compilePolicy(e,n,t),r=new WeakMap,definitionOf=(n,r,i)=>({name:y,controls:{actor:{schema:t.schema,bound:!0,required:!0,uncacheable:e.cache!==`allow`},scopes:{schema:scopeSchema(n),bound:!0,required:!0,uncacheable:e.cache!==`allow`}},rows:{control:`as`,default:s,models:modesOf(r),verbs:i},query:refuseUnreachable(reachOf(e,r)),client:e=>({$as:(t,n)=>e.$bind({actor:t,scopes:n})})}),lazyDefinition=n=>{let r=declarationSnapshot(e,new Set([e.actor,...Object.values(n)])),i=policyCompiler(r,Object.freeze({...n}),t),a=plainFreezer(),o=Object.fromEntries(Object.keys(n).map(e=>{if(!Object.hasOwn(r.models,e))return[e,verbsOf({models:{[e]:i.model(e)}})[e]];let t=selfKeyed(n,e)?()=>i.acyclic(e):void 0,o,resolve=()=>{if(o!==void 0)return o;let n=verbsOf({models:{[e]:i.model(e)}})[e],r=a(n)??n;return o=Object.freeze(t?{...r,acyclic:t}:{...r}),o};return[e,resolve]})),s=definitionOf(i.scopes,i.declared,o);return deepFreeze(s.rows),s},eagerDefinition=e=>{let t=compile(e);return definitionOf(t.scopes,t.models,verbsOf(t))},preparedFor=t=>{let n=r.get(t);if(n?.current())return n;r.delete(t);let i=declarationRevision([e,t],new Set([e.actor,...Object.values(t)]));if(i===void 0)return{current:()=>!1,definition:eagerDefinition(t)};let a={current:i,definition:lazyDefinition(t)};return i()&&r.set(t,a),a},declaredActions=t=>{if(t?.actions)return t.actions;let n=new Map(Object.keys(e.models).map(t=>[t,evidenceOf(e,t).names]));return t&&(t.actions=n),n},rows=e=>extend(e,preparedFor(e.$schema).definition),withMethods=(e,t)=>{let answers=e=>{let r=t.get(e);return t=>{let i=t,ask=async(t,a)=>{for(let i of t)if(!r.includes(i))throw new n(e,i);let evidence=async e=>(await i.findUnique({where:a,select:{[c]:e}}))?.[c],o=await evidence(t);return t.map(e=>o?.[e]===!0)};return{can:async(e,t)=>{if(typeof e==`string`)return(await ask([e],t))[0];let n=await ask(e,t);return Object.fromEntries(e.map((e,t)=>[e,n[t]]))},assert:async(t,r)=>{let i=typeof t==`string`?[t]:t,a=await ask(i,r),o=i.find((e,t)=>!a[t]);if(o!==void 0)throw new n(e,o)}}}};return extend(e,{name:`${y}.methods`,model:Object.fromEntries([...t.keys()].map(e=>[e,answers(e)]))})},methods=e=>{let t=r.get(e.$schema);return withMethods(e,declaredActions(t?.current()?t:void 0))},apply=e=>{let t=preparedFor(e.$schema);return withMethods(extend(e,t.definition),declaredActions(t))};return Object.freeze(Object.assign(apply,{config:e,compile,rows,methods}))}function deepFreeze(e){if(!(typeof e!=`object`||!e||Object.isFrozen(e))){for(let t of Object.values(e))deepFreeze(t);Object.freeze(e)}}function extend(e,t){return Reflect.apply(e.$extends,e,[t])}export{permissions};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./base-wlv81COV.mjs";import{i as n,t as r}from"./query-CTna5P9o.mjs";import{t as i}from"./v-Pb_jJOjC.mjs";const a=new Set([`optional`,`nullable`,`lazyRef`]);function refuse(e,n,i){throw new r(`viborm/permissions: ${e}`,{meta:{extension:`viborm.permissions`,...n&&{model:n}},...i!==void 0&&{cause:t(i)}})}function mayBeNull(e,t){let{type:n,options:r,value:i,wrapped:a}=e;return n===`nullable`||r?.nullable===!0||n===`json`&&r?.array!==!0||r?.schema!==void 0||r?.transform!==void 0&&!t.has(e)?!0:n===`literal`?i===null:n===`union`&&Array.isArray(r)?r.some(e=>mayBeNull(e,t)):n===`optional`||n===`lazyRef`?mayBeNull(a,t):n===`transform`||n===`pipe`}function walk(e,t,n){let r=e,i=!1,o=!1,s=!1;for(;;){let{type:e,wrapped:t,options:c,acceptsUndefined:l}=r;if(i||=l===!0||c?.optional===!0,o||=mayBeNull(r,n),s||=c?.transform!==void 0&&!n.has(r)||c?.schema!==void 0||e===`transform`||e===`pipe`,e===void 0||!a.has(e))break;r=t}let{type:c,entries:l,options:u,value:d,item:f}=r;if(c!==`object`&&c!==`record`&&c!==`array`)return{optional:i,nullable:o,uncertain:s};let p;return c===`array`?p={optional:i,nullable:o,uncertain:s,item:walk(f,`${t}[]`,n)}:c===`record`?p={optional:i,nullable:o,uncertain:s,any:walk(d,`${t}.*`,n)}:(u?.strict===!1&&refuse(`the actor schema admits unknown keys at "${t}": a path it does not declare would be read`),p={optional:i,nullable:o,uncertain:s,keys:new Map(Object.entries(l).filter(([e])=>!u?.omit?.includes(e)).map(([e,r])=>[e,walk(r,t===`actor`?e:`${t}.${e}`,n)]))}),u?.array?{optional:i,nullable:o,uncertain:s,item:p}:p}function bindingSchema(e,t=new WeakMap,n=new Set,r=`actor`,a=new WeakSet){let o=typeof e==`function`?e():e,s=t.get(o);if(s!==void 0)return s;n.has(o)&&refuse(`the actor schema is recursive at "${r}": its paths are not finite`),n.add(o);let child=(e,i=r)=>bindingSchema(e,t,n,i,a),c=o;if(o.type===`object`){let{transform:e,refuse:t,...n}=o.options??{},s=n.partial!==!1&&n.atLeast===void 0,prune=e=>{let t=e;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t};c=i.object(Object.fromEntries(Object.entries(o.entries).map(([e,t])=>[e,child(t,r===`actor`?e:`${r}.${e}`)])),{...n,partial:!1,refuse:s&&t?e=>t(prune(e)):t,transform:s?n=>{let r=t?n:prune(n);return e?e(r):r}:e}),s&&e===void 0&&a.add(c)}else o.type===`optional`?c=i.optional(child(o.wrapped),o.default):o.type===`nullable`?c=i.nullable(child(o.wrapped)):o.type===`lazyRef`?c=child(o.wrapped):o.type===`array`?c=i.array(child(o.item)):o.type===`record`?c=i.record(o.key,child(o.value)):o.type===`union`&&Array.isArray(o.options)?c=i.union(o.options.map(e=>child(e))):o.type===`pipe`&&(c=i.pipe(child(o.schema),...o.actions));let acceptsUndefined=e=>{let t=e;return t.acceptsUndefined===!0||t.type===`literal`&&t.value===void 0};return c!==o&&(o.type===`union`&&Array.isArray(o.options)&&o.options.some(e=>acceptsUndefined(child(e)))||o.type===`pipe`&&acceptsUndefined(child(o.schema))||o.type===`nullable`&&acceptsUndefined(child(o.wrapped)))&&Object.defineProperty(c,`acceptsUndefined`,{value:!0}),n.delete(o),t.set(o,c),c}function actorContract(e){e?.type!==`object`&&refuse(`the actor must be a viborm/validation object schema (v.object)`);let t=new WeakSet,n=bindingSchema(e,new WeakMap,new Set,`actor`,t),r=walk(n,`actor`,t);return{hasPath(e){let t=r;for(let n of e.split(`.`))if(t=t.keys?.get(n)??t.any,t===void 0)return!1;return!0},availabilityPath(e){let t=r,n,i=e===void 0?[]:e.split(`.`);for(let r=0;r<i.length;r++){if(t.uncertain||t.any!==void 0||(t=t.keys?.get(i[r]),t===void 0))return e;(t.optional||t.nullable||t.uncertain)&&(n=i.slice(0,r+1).join(`.`))}return n},schema:n}}const o=Object.freeze({OR:Object.freeze([])}),s=`default`,c=`$access`,l=`$create`,u=new Set([`mandatory`,`actions`,`operations`,`fields`,`domains`]),d=new Set([`read`,`update`,`delete`]),f=new Set([`actor`,`levels`,`mandatory`,`models`,`cache`]),p=new Set([`read`,`write`]);function distance(e,t){let n=Array.from({length:e.length+1},(e,n)=>Array.from({length:t.length+1},(e,t)=>n===0?t:t===0?n:0));for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++){let a=e[r-1]===t[i-1]?0:1,o=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+a);r>1&&i>1&&e[r-1]===t[i-2]&&e[r-2]===t[i-1]&&(o=Math.min(o,n[r-2][i-2]+1)),n[r][i]=o}return n[e.length][t.length]}const m=new Set([`AND`,`OR`,`NOT`]),h=`$exists`,isEnclosingRow=e=>isRecord(e)&&Object.keys(e).length===2&&typeof e.$row==`string`&&Number.isSafeInteger(e.up)&&e.up>=0,existsOf=e=>{let[t,n]=Object.entries(e)[0];return[t,n]},g=new Set([`is`,`isNot`,`some`,`every`,`none`]),isRecord=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.getOwnPropertySymbols(e).length===0},isActorField=e=>isRecord(e)&&typeof e.actor==`string`&&Object.keys(e).length===1,isTrue=e=>Object.keys(e).length===0,membersOf=(e,t)=>Object.keys(e).length===1&&Array.isArray(e[t])?e[t]:[e];function and(e){if(e.includes(!1))return!1;let t=e.filter(e=>!isTrue(e)).flatMap(e=>membersOf(e,`AND`));return t.length<2?t[0]??{}:{AND:t}}function structuralKeys(){let e=new Map,t=new WeakMap,n=new Map,r=0,keyOf=i=>{switch(typeof i){case`number`:return Object.is(i,-0)?`n-0`:`n${i}`;case`string`:return`s${JSON.stringify(i)}`;case`bigint`:return`b${i}`;case`boolean`:case`undefined`:return`p${i}`;default:break}if(i===null)return`pnull`;if(i instanceof Date&&!Number.isNaN(i.getTime()))return`d${i.getTime()}`;if(!(Array.isArray(i)||isRecord(i))){let e=n.get(i);return e===void 0&&n.set(i,e=`o${r++}`),e}let a=t.get(i);if(a!==void 0)return a;let o=Array.isArray(i)?`[${i.map(keyOf).join(`,`)}]`:`{${Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${keyOf(i[e])}`).join(`,`)}}`;return a=e.get(o),a===void 0&&e.set(o,a=`#${r++}`),t.set(i,a),a},same=(e,t)=>e===t&&typeof e!=`number`||keyOf(e)===keyOf(t),distinct=e=>{let t=new Set;return e.filter(e=>{let n=keyOf(e);return t.has(n)?!1:(t.add(n),!0)})},or=e=>{let t=e.filter(e=>e!==!1);if(t.length===0)return!1;if(t.some(isTrue))return{};let n=distinct(t.flatMap(e=>membersOf(e,`OR`)));return n.length===1?n[0]:{OR:n}};return{keyOf,same,distinct,or}}function actionsOf(e,t,n){let r=new Map(t.actions?Object.entries(t.actions):n.map((e,t)=>[e,n.slice(t-1,t)])),i=new Map;for(let t of[...n,...r.keys(),...[...r.values()].flat()])t.includes(`,`)&&refuse(`models.${e}: "${t}" is not an individual action; commas group rules only`,e);for(let a of Object.keys(t)){if(u.has(a))continue;let o=`models.${e}.${a}`,s={rule:t[a],source:o},c=a.includes(`,`)?a.split(`,`).map(e=>e.replace(/^[ \t\r\n]+|[ \t\r\n]+$/g,``)):[a];for(let a of c){a.length===0&&refuse(`${o}: an action group cannot contain an empty member`,e),a===`within`&&refuse(`${o} was renamed to "mandatory"`,e),a===`arms`&&refuse(`${o}: arms was removed; assign rules to named actions`,e),u.has(a)&&refuse(`${o}: "${a}" is a key of the declaration, not an action`,e);let c=i.get(a);if(c!==void 0&&refuse(`${o}: action "${a}" already has a rule at ${c.source}`,e),i.set(a,s),r.has(a))continue;t.actions&&refuse(`${o}: neither an action ${e} lists in \`actions\` nor a key of the declaration (${[...u].join(`, `)}); unknown action "${a}"`,e);let l=[...u,...n].find(e=>e.toLowerCase()===a.toLowerCase()||distance(e,a)<=(e.length<=4?1:2));l!==void 0&&refuse(`${o}: spelled like "${l}"; rename the action, or list the model's \`actions\``,e),r.set(a,[])}}for(let e of[`update`,`delete`]){let t=r.get(e);t!==void 0&&(r.has(`read`)||r.set(`read`,[]),t.includes(`read`)||r.set(e,[...t,`read`]))}for(let[t,n]of r){(t===`arms`||t===`within`)&&refuse(`models.${e}: "${t}" is a retired declaration key, not an action`,e),u.has(t)&&refuse(`models.${e}: "${t}" is a key of the declaration, not an action`,e);for(let i of n)r.has(i)||refuse(`models.${e}.actions.${t} implies "${i}", which ${e} does not declare`,e)}let a=new Map;for(let e of r.keys()){let t=new Set,visit=e=>{if(!t.has(e)){t.add(e);for(let t of r.get(e))visit(t)}};visit(e),a.set(e,Object.freeze([...t]))}return{rules:i,closure:a,evidence:{names:[...r.keys()]}}}function evidenceOf(e,t){return actionsOf(t,e.models[t],e.levels??[]).evidence}function verbsOf(e){return Object.fromEntries(Object.entries(e.models).map(([e,{modes:t,reads:n,...r}])=>[e,Object.keys(n).length===0?r:{...r,reads:n}]))}function compilePolicy(e,t,n=actorContract(e.actor)){return policyCompiler(e,t,n).policy()}const _=Object.freeze({predicates:Object.freeze({[l]:o}),writes:Object.freeze({}),reads:Object.freeze({}),modes:Object.freeze({}),place:l,moves:Object.freeze({})}),v=Object.freeze([]);function policyCompiler(t,n,i=actorContract(t.actor)){let{keyOf:a,same:u,distinct:y,or:b}=structuralKeys(),x=Object.freeze([]),S=t.levels??x;new Set(S).size!==S.length&&refuse(`levels must list each action only once`);for(let e of Object.keys(t))f.has(e)||refuse(`"${e}" is not a key of the policy (${[...f].join(`, `)})`);for(let e of Object.keys(t.models))Object.hasOwn(n,e)||refuse(`models.${e}: the schema has no such model`,e);let C=new Map(Object.entries(n).map(([e,t])=>[t,e])),stateOf=e=>n[e][`~`].state,relationOf=(e,t)=>Object.hasOwn(stateOf(e).relations,t)?stateOf(e).relations[t][`~`]:void 0,targetOf=(e,t)=>{let n=relationOf(e,t)?.settleTarget();return C.get(n)},w=new Map(Object.entries(t.models).map(([e,t])=>[e,actionsOf(e,t,S)])),T=new Map,modelOf=e=>{let t=T.get(e);if(t)return t;let n=Object.freeze({name:e,actions:Object.freeze([...w.get(e)?.evidence.names??[]])});return T.set(e,n),n},E=new Map,D=new WeakMap,O=new Map,k=new Map,A=new WeakSet,j=[],scope=(e,t)=>({OR:[{$if:{control:`scopes`,path:`unrestricted`,equals:!0}},{$if:{control:`scopes`,path:`allowed`,has:`${e}.${t}`}}]}),ruleAt=(e,t)=>{let n=`${e}.${t}`,r=O.get(n);if(r!==void 0)return r;let i=w.get(e).rules.get(t),a=i?.rule===void 0?!1:lower(e,t,i.rule,i.source);E.set(n,a);let o=availableGrant(e,a);return O.set(n,o),o},M=new Map,restriction=e=>{let n=M.get(e);if(n!==void 0)return n;let admit=(t,n)=>{if(typeof t==`function`&&refuse(`${n}: mandatory is action-independent and cannot contain callbacks`,e),Array.isArray(t))for(let e of t)admit(e,n);else if(isRecord(t))for(let e of Object.values(t))admit(e,n)},r=t.models[e];admit(r.mandatory,`models.${e}.mandatory`),admit(t.mandatory,`mandatory`);let i=and([lower(e,`read`,r.mandatory??{},`models.${e}.mandatory`),lower(e,`read`,t.mandatory??{},`mandatory`)]);return M.set(e,i),i},P=(e,t)=>{let n=`${e}.${t}`,r=k.get(n);if(r!==void 0)return r;j.includes(n)&&refuse(`models.${n} reads itself: ${[...j.slice(j.indexOf(n)),n].join(` → `)}`,e),j.push(n);try{let r=w.get(e),i=r.rules.get(t)?.rule===!1?[]:[...r.closure].flatMap(([e,n])=>n.includes(t)?[e]:[]),a=b(i.map(t=>ruleAt(e,t))),o=and([restriction(e),absorb(e,a)]);if(o!==!1){let t=i.map(t=>summarizeReads(e,E.get(`${e}.${t}`),`source`,!0)),n=summarizeReads(e,restriction(e),`source`,!0);n!==null&&t.every(e=>e!==null)&&D.set(o,combineReads(!0,[n,combineReads(!1,t)]))}return k.set(n,o),o!==!1&&A.add(o),o}finally{j.pop()}},absorb=(e,t)=>{if(t===!1||!Array.isArray(t.OR))return t;let n=t.OR,r=new Set,i=and([restriction(e),t]);for(let t=0;t<n.length;t++){let a=n[t];for(let o=0;o<n.length;o++){if(o===t||r.has(o))continue;let s=n[o];if(!implies(e,a,s)||o>t&&implies(e,s,a))continue;let c=n.filter((e,n)=>n!==t&&!r.has(n)),l=and([restriction(e),b(c)]);if(preservesReads(e,i,l)){i=l,r.add(t);break}}}let a=n.filter((e,t)=>!r.has(t));return a.length===1?a[0]:{OR:a}},path=(e,t)=>{typeof t==`string`&&!i.hasPath(t)&&refuse(`${e} reads actor path "${t}", which the actor schema does not declare`)},value=(e,t)=>isActorField(t)?(path(e,t.actor),{control:`actor`,path:t.actor}):isRecord(t)?(t.control===`actor`&&path(e,t.path),Object.fromEntries(Object.entries(t).map(([t,n])=>[t,value(e,n)]))):t,conditions=(e,t,n=``)=>(isRecord(t)||refuse(`${e} tests the actor with a value that is not an object of its facts`),Object.keys(t).length===0&&refuse(`${e} tests the actor${n?` at "${n.slice(0,-1)}"`:``} with an empty object`),Object.entries(t).flatMap(([t,r])=>{let i=`${n}${t}`;return isRecord(r)?conditions(e,r,`${i}.`):(path(e,i),typeof r==`object`&&r&&refuse(`${e} tests actor path "${i}" against ${Array.isArray(r)?`a list`:`a value that is not a literal`}`),[{$if:r===null?{control:`actor`,path:i,exists:!1}:{control:`actor`,path:i,equals:r}}])})),evaluated=(e,t,n,i)=>{try{return e(t,modelOf(n))}catch(e){if(e instanceof r)throw e;return refuse(`${i}: the rule function threw at "${t}"`,n,e)}},lower=(e,t,r,i,a=[{model:e}])=>{if(typeof r==`boolean`)return r?{}:!1;if(typeof r==`function`)return lower(e,t,evaluated(r,t,e,i),i,a);isRecord(r)||refuse(`${i}: a rule is a boolean, a where object or a function of the action`,e);let o=stateOf(e),s={},c=[];for(let[l,u]of Object.entries(r))if(m.has(l)){let n=(Array.isArray(u)?u:[u]).map(n=>lower(e,t,n,i,a)),r=l===`OR`?b(n):and(l===`AND`?n:n.map(e=>e===!1?{}:isTrue(e)?!1:{NOT:e}));if(r===!1)return!1;c.push(r)}else if(l===`actor`&&!(Object.hasOwn(o.scalars,l)||Object.hasOwn(o.relations,l)))c.push(...conditions(i,u));else if(l===`$if`)isRecord(u)&&u.control===`actor`&&path(i,u.path),s[l]=u;else if(l===h){let r=isRecord(u)?Object.keys(u):[],[o]=r;(r.length!==1||!Object.hasOwn(n,o))&&refuse(`${i}: $exists names exactly one model of the schema and the where its rows must match`,e);let c=lower(o,t,u[o],i,[...a,{model:o}]);if(c===!1)return!1;s[l]={[o]:c}}else if(targetOf(e,l)!==void 0){let n=relation(e,t,l,u,i,a);if(n===!1)return!1;n!==void 0&&(s[l]=n)}else u===void 0&&refuse(`${i}: ${l} is compared with undefined, which holds for every row; compare with null, a literal or an actor value`,e),enclosingRows(e,l,u,i,a),s[l]=value(i,u);return and([s,...c])},enclosingRows=(e,t,n,r,i)=>{if(isEnclosingRow(n)){let a=`{ $row: ${JSON.stringify(n.$row)}, up: ${n.up} }`,o=i.length-1-n.up;o<0&&refuse(`${r}: ${t} compares ${a}, which reaches past the rule (${i.length-1} relation bodies deep here)`,e);let s=i.slice(o+1).find(e=>e.sealed);s&&refuse(`${r}: ${t} compares ${a} across a recursive relation to ${s.model}`,e);let c=i[o].model;Object.hasOwn(stateOf(c).scalars,n.$row)||refuse(`${r}: ${t} compares ${a}, and ${c} has no scalar field "${n.$row}"`,e);return}if(Array.isArray(n))for(let a of n)enclosingRows(e,t,a,r,i);else if(isRecord(n))for(let a of Object.values(n))enclosingRows(e,t,a,r,i)},relation=(e,t,n,r,i,a)=>{let o=targetOf(e,n);if(typeof r==`string`){modelOf(o).actions.includes(r)||refuse(`${i} reads ${n} at "${r}", which ${o} does not declare`,e);let t=P(o,r);return t===!1?!1:{is:t}}if(r===void 0&&refuse(`${i}: ${n} is filtered with undefined, which holds for every row`,e),typeof r==`object`&&r&&!isRecord(r)&&refuse(`${i} filters ${n} with a value that is not a filter object, an action name or null`,e),!isRecord(r))return r;if(!Object.keys(r).some(e=>g.has(e)))return lower(o,t,r,i,[...a,{model:o}]);let s={},c=!1,l={model:o,...r.recurse!==void 0&&{sealed:`recursive`}};for(let[e,n]of Object.entries(r)){if(!(g.has(e)&&n!==null)){s[e]=n;continue}let r=lower(o,t,n,i,[...a,l]);if(r!==!1)s[e]=r;else if(e===`is`||e===`some`)return!1;else e===`every`&&(c=!0)}return c&&(s.none={}),Object.keys(s).length===0?void 0:s},N=new Map(Object.keys(n).map(e=>[e,new Map])),implies=(e,t,n)=>{if(t===n)return!0;let r=N.get(e),i=a(t),o=r.get(i);o===void 0&&r.set(i,o=new Map);let s=a(n),c=o.get(s);return c===void 0&&o.set(s,c=provable(e,t,n)),c},provable=(e,t,n)=>{let r=conjuncts(n);if(r.length!==1)return r.every(n=>implies(e,t,n));let i=conjuncts(t),[a,o]=Object.entries(i[0]??{AND:[]})[0],[s,c]=Object.entries(r[0])[0];if(i.length===1&&a===`OR`)return o.every(t=>implies(e,t,n));if(s===`OR`&&c.some(n=>implies(e,t,n)))return!0;if(i.length!==1)return i.some(t=>implies(e,t,n));if(a!==s||!isRecord(o)||!isRecord(c))return a===s&&u(o,c);if(a===`NOT`)return implies(e,c,o);if(a===`$if`)return u(o,c)||narrower(o,c,`hasSome`);if(a===h){let[e,t]=existsOf(o),[n,r]=existsOf(c);return e===n&&implies(e,t,r)}let l=targetOf(e,a);if(l===void 0)return u(o,c)||narrower(o,c,`hasSome`)||narrower(o,c,`in`);let d=[...g].filter(e=>Object.hasOwn(c,e));return d.length===0?implies(l,o,c):d.every(e=>isRecord(o[e])&&isRecord(c[e])&&u(without(o,e),without(c,e))&&(e===`none`||e===`isNot`?implies(l,c[e],o[e]):implies(l,o[e],c[e])))},F=new WeakMap,conjuncts=e=>{let t=F.get(e);if(t!==void 0)return t;let n=Object.keys(e).length===1&&!Object.hasOwn(e,`AND`)?[e]:Object.entries(e).flatMap(([e,t])=>e===`AND`?t.flatMap(conjuncts):[{[e]:t}]);return F.set(e,n),n},without=(e,t)=>{let{[t]:n,...r}=e;return r},narrower=(e,t,n)=>Array.isArray(e[n])&&Array.isArray(t[n])&&u(without(e,n),without(t,n))&&e[n].every(e=>t[n].some(t=>u(e,t))),I=new Map,shared=e=>{if(e===!1)return e;let t=a(e),n=I.get(t);return n===void 0?(I.set(t,e),e):n},L=new WeakMap,negate=e=>{if(e===!1)return{};if(isTrue(e))return!1;if(Object.keys(e).length===1&&isRecord(e.NOT))return e.NOT;let t=L.get(e);if(t!==void 0)return t;let n=Array.isArray(e.AND)?guardOr(e.AND.map(e=>negate(e))):Array.isArray(e.OR)?guardAnd(e.OR.map(e=>negate(e))):shared({NOT:e});return L.set(e,n),n},R=new Map,combined=(e,t,n)=>{let r=e;for(let e of t)r+=e===!1?` F`:` ${a(e)}`;if(R.has(r))return R.get(r);let i=shared(n());return R.set(r,i),i},guardOr=e=>combined(`OR`,e,()=>b(e)),guardAnd=e=>combined(`AND`,e,()=>{let t=and(e);return t===!1||!Array.isArray(t.AND)?t:and(y(t.AND))}),z={yes:!1,no:{},reads:new Map},atomic=(e=new Map)=>({yes:!1,no:!1,reads:e}),combineReads=(e,t)=>{let n=(e?guardAnd:guardOr)(t.map(e=>e.yes)),r=(e?guardOr:guardAnd)(t.map(e=>e.no)),i=negate(e?r:n),a=new Map;for(let e of t)for(let[t,n]of e.reads){let e=guardAnd([i,n]);a.set(t,guardOr([a.get(t)??!1,e]))}return{yes:n,no:r,reads:a}},B=new Map(Object.keys(n).map(e=>[e,new WeakMap])),V=new Map(Object.keys(n).map(e=>[e,new WeakMap])),H=new Map(Object.keys(n).map(e=>[e,new WeakMap])),U=new Map(Object.keys(n).map(e=>[e,new WeakMap])),parameterKey=(e,t)=>isRecord(e)&&typeof e.control==`string`&&(e.path===void 0||typeof e.path==`string`)&&Object.keys(e).every(e=>e===`control`||e===`path`)?JSON.stringify([e.control,e.path??null,t]):void 0,containsParameter=e=>parameterKey(e,!1)!==void 0||(Array.isArray(e)?e.some(containsParameter):isRecord(e)&&Object.values(e).some(containsParameter)),W=new Set([`equals`,`not`,`in`,`notIn`,`lt`,`lte`,`gt`,`gte`,`contains`,`startsWith`,`endsWith`,`has`,`hasSome`,`hasEvery`,`isEmpty`]),scalarReads=e=>{let t=parameterKey(e,!1);if(t!==void 0)return atomic(new Map([[t,{}]]));if(!isRecord(e))return containsParameter(e)?null:atomic();if(Object.keys(e).length===0)return null;let n=new Map;for(let[t,r]of Object.entries(e)){if(t===`mode`||t===`path`)continue;if(!W.has(t))return null;let e=parameterKey(r,t===`in`||t===`notIn`);if(e!==void 0)n.set(e,{});else if(t===`not`||t===`equals`){let e=scalarReads(r);if(e===null)return null;for(let[t,r]of e.reads)n.set(t,r)}else if(Array.isArray(r)&&(t===`in`||t===`notIn`))for(let e of r){let t=parameterKey(e,!1);if(t!==void 0)n.set(t,{});else if(containsParameter(e))return null}else if(containsParameter(r))return null}return Object.keys(e).every(e=>e===`mode`||e===`path`)?null:atomic(n)},summarizeReads=(e,t,n=void 0,r=!1)=>{if(t===!1)return z;if(!isRecord(t))return null;if(n===`source`){let n=D.get(t);if(n!==void 0)return r?n:summarizeReads(e,t,`compiled`)}let i=(n===`compiled`?U:n?r?H:V:B).get(e),a=i.get(t);if(a!==void 0)return a;let o=[],unsupported=()=>(i.set(t,null),null);for(let[i,a]of Object.entries(t))if(m.has(i)){let t=Array.isArray(a)?a:[a],s=[];for(let a of t){let t=summarizeReads(e,a,n,r||i===`NOT`);if(t===null)return unsupported();s.push(i===`NOT`?{yes:t.no,no:t.yes,reads:t.reads}:t)}o.push(combineReads(i!==`OR`,s))}else if(i===`$if`){if(!isRecord(a))return unsupported();let e={$if:a};o.push({yes:e,no:negate(e),reads:new Map})}else if(i===h){let[e,t]=existsOf(a),i=summarizeReads(e,t,n,r);if(i===null)return unsupported();o.push(atomic(i.reads))}else if(Object.hasOwn(stateOf(e).scalars,i))if(n&&stateOf(e).scalars[i][`~`].state.type===`json`){let e=new Map,collect=t=>{let n=parameterKey(t,!1);if(n!==void 0)e.set(n,{});else if(isRecord(t)){let n=parameterKey(t.equals,!1);n!==void 0&&e.set(n,{}),isRecord(t.not)&&collect(t.not)}};collect(a),o.push(atomic(e))}else{let e=scalarReads(a);if(e===null&&!n)return unsupported();o.push(e??atomic())}else{let t=targetOf(e,i);if(t===void 0)return unsupported();if(a===null){o.push(atomic());continue}let s=[];if(isRecord(a)&&Object.keys(a).some(e=>g.has(e))){for(let[e,t]of Object.entries(a))if(g.has(e))s.push({body:t,negative:r||e===`every`||e===`none`||e===`isNot`});else if(e!==`recurse`&&e!==`self`)return unsupported()}else s.push({body:a,negative:r});let c=[];for(let{body:e,negative:r}of s){if(e===null){c.push(atomic());continue}let i=summarizeReads(t,e,n,r);if(i===null)return unsupported();c.push(atomic(i.reads))}o.push(combineReads(!0,c))}let s=combineReads(!0,o);return i.set(t,s),s},provesGuard=(e,t,n)=>t===!1||n!==!1&&(isTrue(n)||u(t,n)||implies(e,t,n)),provesPresence=(e,t)=>{if(e===!1)return!0;if(Array.isArray(e.AND))return e.AND.some(e=>provesPresence(e,t));if(Array.isArray(e.OR))return e.OR.every(e=>provesPresence(e,t));let n=isRecord(e.$if)?e.$if:void 0,r=isRecord(e.NOT)&&isRecord(e.NOT.$if)?e.NOT.$if:void 0,i=n??(r?.exists===!1?r:void 0);return i?.control===`actor`&&typeof i.path==`string`&&(i.path===t||i.path.startsWith(`${t}.`))&&(n===void 0||n.exists!==!1)},guardAlternatives=(e,t)=>{if(D.has(t))return t;let replace=(e,t)=>{let n=!1,r=Object.entries(e).map(([e,r])=>{let i=t(e,r);return n||=i!==r,[e,i]});return n?Object.fromEntries(r):e};return replace(t,(t,n)=>{if((t===`OR`||t===`AND`)&&Array.isArray(n)){let r=n.map(n=>t===`OR`?availableGrant(e,n):guardAlternatives(e,n));return r.some((e,t)=>e!==n[t])?r:n}if(t===h){let[e,t]=existsOf(n),r=guardAlternatives(e,t);return r===t?n:{[e]:r}}let r=targetOf(e,t);return r===void 0||!isRecord(n)?n:Object.keys(n).some(e=>g.has(e))?replace(n,(e,t)=>(e===`is`||e===`some`)&&isRecord(t)?guardAlternatives(r,t):t):guardAlternatives(r,n)})},availableGrant=(e,t)=>{if(t===!1)return t;let n=guardAlternatives(e,t),r=summarizeReads(e,n,`source`);if(r===null)return n;let a=[];for(let[t,n]of r.reads){let[r,o]=JSON.parse(t);if(r!==`actor`)continue;let s=i.availabilityPath(o??void 0);if(s===void 0)continue;let c={$if:{control:`actor`,path:s,exists:!0}};provesPresence(n,s)||provesGuard(e,n,c)||a.push(b([negate(n),c]))}return a.length===0?n:and([guardAnd(a),n])},preservesReads=(e,t,n)=>{let r=summarizeReads(e,t),i=summarizeReads(e,n);if(r===null||i===null)return!1;for(let[t,n]of r.reads){let r=i.reads.get(t)??!1;if(!(provesGuard(e,n,r)&&provesGuard(e,r,n)))return!1}return!0},conjoin=(e,t,n=[])=>{let r=and(t);if(r===!1)return!1;let i=[...conjuncts(r)],a=and([...n,...i]);for(let t=i.length-1;t>=0;t--){let r=i[t],covers=t=>implies(e,t,r);if(!(n.some(covers)||i.some((e,n)=>n!==t&&covers(e))))continue;let o=i.filter((e,n)=>n!==t),s=and([...n,...o]);preservesReads(e,a,s)&&(a=s,i.splice(t,1))}return and(i)},verbsFor=e=>{let n=modelOf(e),r=t.models[e].operations??{},i={};for(let[e,t]of[[`read`,`read`],[`update`,`update`],[`delete`,`delete`]]){let a=r[e]??t;n.actions.includes(a)&&(i[e]=a)}return i},keysOf=e=>Object.entries(stateOf(e).relations).flatMap(([n,r])=>{let i=r[`~`].state.foreignKey;if(i===void 0)return[];let a=targetOf(e,n),o=t.models[a]&&verbsFor(a).read,s=o?P(a,o):!1,c=s===!1?!1:{[n]:{is:s}},l=i.fields.every(t=>stateOf(e).scalars[t]?.[`~`].state.nullable===!0);return[{fields:i.fields,clause:l?b([and(i.fields.map(e=>({[e]:null}))),c]):c}]}),rootReads=(e,t,n,r,i=new Map)=>{if(isEnclosingRow(t)){t.up===n&&r.add(t.$row);return}if(typeof t!=`object`||!t||n>0&&A.has(t))return;let a=i.get(t)??new Set;if(!a.has(n)){if(i.set(t,a.add(n)),Array.isArray(t)){for(let a of t)rootReads(e,a,n,r,i);return}if(isRecord(t))for(let[a,o]of Object.entries(t)){if(a===`$if`)continue;if(a===h){let[e,t]=existsOf(o);rootReads(e,t,n+1,r,i);continue}let t=m.has(a)?void 0:targetOf(e,a);if(t===void 0||!isRecord(o)){rootReads(e,o,n,r,i);continue}if(!Object.keys(o).some(e=>g.has(e))){rootReads(t,o,n+1,r,i);continue}for(let e of g){let a=o[e];isRecord(a)&&rootReads(t,a,n+1,r,i)}}}},fieldsRead=(e,t,n)=>(rootReads(e,t,0,n),ownFields(e,t,n)),ownFields=(e,t,n)=>{for(let[r,i]of Object.entries(t))if(m.has(r))for(let t of Array.isArray(i)?i:[i])ownFields(e,t,n);else if(r===`$if`||r===h)continue;else if(targetOf(e,r)===void 0)n.add(r);else{for(let t of joinedOn(e,r))n.add(t);if(isRecord(i)&&i.self===!0)for(let t of g)isRecord(i[t])&&ownFields(e,i[t],n)}return n},holders=(e,t)=>Object.entries(stateOf(e).relations).filter(([,e])=>e[`~`].state.foreignKey?.fields.includes(t)).map(([e])=>e),joinedOn=(e,t)=>{let n=relationOf(e,t).state.foreignKey;if(n!==void 0)return n.fields;let r=new Set;for(let t of C.values())for(let n of Object.values(stateOf(t).relations)){let t=n[`~`].state.foreignKey;if(t!==void 0&&C.get(n[`~`].settleTarget())===e)for(let e of t.references)r.add(e)}return[...r]},G=new Map;for(let n of Object.keys(t.models)){let r=t.models[n],i=modelOf(n),a=e((e,t)=>(t!==void 0&&!i.actions.includes(t)&&refuse(`models.${n}.${e} names "${t}", which ${n} does not declare. Declared actions: ${i.actions.join(`, `)||`none`}. Add its rule or choose a declared action.`,n),t),`declared`),o=new Set(i.actions),claimName=(e,t)=>{o.has(e)&&refuse(`${t}: an action, a domain, the placement or a move already has the name "${e}"`,n),o.add(e)},c=r.operations??{};for(let e of Object.keys(c))d.has(e)||refuse(`models.${n}.operations.${e}: not a configurable operation; use read, update or delete (create always uses its own grant)`,n);for(let e of[`read`,`update`,`delete`])a(`operations.${e}`,c[e]);let u=verbsFor(n),f={},m=[],h={},g=stateOf(n);for(let[e,t]of Object.entries(r.fields??{})){let r=isRecord(t)?Object.keys(t).find(e=>!p.has(e)):``;r!==void 0&&refuse(`models.${n}.fields.${e}${r?`.${r}`:``}: a field entry takes only read and write`,n);let{read:i,write:o}=t;if(Object.hasOwn(g.scalars,e)||Object.hasOwn(g.relations,e)||refuse(`models.${n}.fields.${e}: ${n} has no such field`,n),o!==void 0)if(a(`fields.${e}.write`,o),o===u.update)f[e]=o;else{let t=`$write:${e}`;claimName(t,`models.${n}.fields.${e}.write`),f[e]=t,m.push([e,o])}i!==void 0&&(h[e]=a(`fields.${e}.read`,i))}claimName(l,`models.${n}.create`);let _=new Map(i.actions.map(e=>[e,e]));for(let e of Object.keys(r.domains??{}))claimName(e,`models.${n}.domains.${e}`),_.set(e,e);_.has(s)&&refuse(`models.${n}: "${s}" is the mode a call takes by default, not an action or a domain`,n),G.set(n,{...u,modes:Object.freeze(Object.fromEntries(_)),writes:f,protectedWrites:m,reads:h})}let compileModel=e=>{let n=t.models[e],r=modelOf(e),{writes:i,protectedWrites:a,reads:s,...u}=G.get(e),d=verbsFor(e),f=new Map,claim=(t,n,r)=>{f.has(t)&&refuse(`${n}: an action, a domain, the placement or a move already has the name "${t}"`,e),f.set(t,r)};for(let t of r.actions)f.set(t,and([P(e,t),scope(e,t)])||o);let p=w.get(e).evidence;for(let[t,n]of a)claim(`$write:${t}`,`models.${e}.fields.${t}.write`,and([d.update===void 0?!1:f.get(d.update),f.get(n)])||o);let m=P(e,`create`),h=keysOf(e);claim(l,`models.${e}.create`,conjoin(e,[m,scope(e,`create`),...h.map(({clause:e})=>e)])||o);let g=m===!1?new Set:fieldsRead(e,m,new Set),_={};for(let t of new Set([...g,...h.flatMap(({fields:e})=>e)])){let n=`move:${t}`,r=new Set([t,...holders(e,t)].map(e=>i[e]??d.update)),a=[d.read,...r.size===1?r:[]].filter(e=>e!==void 0).map(e=>f.get(e));claim(n,`models.${e}.fields.${t}`,conjoin(e,[g.has(t)?m:{},...h.filter(({fields:e})=>e.includes(t)).map(({clause:e})=>e)],a)||o),_[t]=n}for(let[t,r]of Object.entries(n.domains??{})){let n=`models.${e}.domains.${t}`;claim(t,n,lower(e,`read`,r,n)||o)}return Object.freeze({predicates:Object.freeze(Object.fromEntries(f)),...d,writes:Object.freeze(i),reads:Object.freeze(s),modes:u.modes,place:l,moves:Object.freeze(_),...p.names.length>0&&{evidence:Object.freeze({as:c,names:Object.freeze(p.names)})}})},K=new Map,modelAt=e=>{let n=K.get(e);if(n!==void 0)return n;let r=Object.hasOwn(t.models,e)?compileModel(e):_;return K.set(e,r),r},q,acyclicAt=e=>{if(q===void 0){for(let e of Object.keys(n))try{modelAt(e)}catch(e){if(!(e instanceof r))throw e}q=new Map([...recursion(K)].map(([e,t])=>[e,Object.freeze(t)]))}return q.get(e)??v},J=Object.freeze(Object.fromEntries([...w].flatMap(([e,t])=>[...t.closure].map(([t,n])=>[`${e}.${t}`,Object.freeze(n.map(t=>`${e}.${t}`))])))),Y=Object.freeze(Object.fromEntries(Object.keys(n).map(e=>{let t=G.get(e);if(t===void 0)return[e,_];let{read:n,update:r,delete:i,modes:a}=t;return[e,Object.freeze({...n!==void 0&&{read:n},...r!==void 0&&{update:r},...i!==void 0&&{delete:i},modes:a})]}))),X;return Object.freeze({scopes:J,declared:Y,model:modelAt,acyclic:acyclicAt,policy:()=>{if(X!==void 0)return X;let e={};for(let t of Object.keys(n)){let n=modelAt(t),r=acyclicAt(t);e[t]=r.length===0?n:Object.freeze({...n,acyclic:r})}return X=Object.freeze({control:`actor`,scopes:J,models:Object.freeze(e)}),X}});function recursion(t){let r=new Map,i=new Map(Object.keys(n).map(e=>[e,new WeakSet])),a=e((e,t)=>{if(!(!isRecord(t)||i.get(e).has(t))){i.get(e).add(t);for(let[n,i]of Object.entries(t)){if(m.has(n)){for(let t of Array.isArray(i)?i:[i])a(e,t);continue}if(n===h){a(...existsOf(i));continue}let t=targetOf(e,n);if(t===void 0||!isRecord(i))continue;if(t===e&&i.recurse!==void 0&&relationOf(e,n).state.foreignKey!==void 0){let t=r.get(e)??[];t.includes(n)||t.push(n),r.set(e,t)}let o=[...g].filter(e=>Object.hasOwn(i,e));o.length===0&&a(t,i);for(let e of o)a(t,i[e])}}},`walk`);for(let[e,n]of t)for(let t of Object.values(n.predicates))a(e,t);return r}}function declarationRevision(e,t){let n=[],r=new Set,visit=e=>{if(typeof e!=`object`||!e||t.has(e)||r.has(e))return!0;let i=Object.getPrototypeOf(e);if(Array.isArray(e)?i!==Array.prototype||!Array.from({length:e.length},(t,n)=>Object.hasOwn(e,n)).every(Boolean):i!==Object.prototype&&i!==null)return!1;r.add(e);let a=Reflect.ownKeys(e),o=[],s=[];for(let t of a){let n=Object.getOwnPropertyDescriptor(e,t);if(!(n&&`value`in n&&Object.is(Reflect.get(e,t),n.value))||(o.push(n.value),s.push(n.enumerable===!0),!visit(n.value)))return!1}return n.push({value:e,keys:a,values:o,enumerable:s,prototype:i}),!0};if(e.every(visit))return()=>n.every(({value:e,keys:t,values:n,enumerable:r,prototype:i})=>{let a=Reflect.ownKeys(e);return Object.getPrototypeOf(e)===i&&a.length===t.length&&t.every((t,i)=>{let o=Object.getOwnPropertyDescriptor(e,t);return a[i]===t&&o&&`value`in o&&Object.is(o.value,n[i])&&Object.is(Reflect.get(e,t),n[i])&&o.enumerable===r[i]})})}function declarationSnapshot(e,t){let n=new Map,copy=e=>{if(typeof e!=`object`||!e||t.has(e))return e;let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)return e;let i=n.get(e);if(i!==void 0)return i;let a=Array.isArray(e)?[]:Object.create(r);n.set(e,a);for(let t of Reflect.ownKeys(e)){if(Array.isArray(e)&&t===`length`)continue;let n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,{value:copy(n.value),enumerable:n.enumerable===!0,writable:!1,configurable:!1})}return Object.freeze(a)};return copy(e)}function plainFreezer(){let e=new Map,t=new Set,n=Symbol(`not plain`),copy=r=>{if(typeof r!=`object`||!r)return typeof r==`function`||typeof r==`symbol`?n:r;let i=e.get(r);if(i!==void 0)return i;if(t.has(r))return n;let a=Object.getPrototypeOf(r),o=Array.isArray(r);if(o?a!==Array.prototype:a!==Object.prototype&&a!==null)return n;t.add(r);try{let t=o?[]:Object.create(a);for(let e of Reflect.ownKeys(r)){if(o&&e===`length`)continue;let i=Object.getOwnPropertyDescriptor(r,e);if(typeof e!=`string`||!(`value`in i)||!i.enumerable)return n;let a=copy(i.value);if(a===n)return n;Object.defineProperty(t,e,{value:a,enumerable:!0,writable:!0,configurable:!0})}return o&&t.length!==r.length?n:(Object.freeze(t),e.set(r,t),t)}finally{t.delete(r)}};return e=>{let t=copy(e);return t===n?void 0:t}}const y=`viborm.permissions`,b={findMany:`read`,findFirst:`read`,findUnique:`read`,findFirstOrThrow:`read`,findUniqueOrThrow:`read`,count:`read`,aggregate:`read`,groupBy:`read`,exist:`read`,update:`update`,updateMany:`update`,delete:`delete`,deleteMany:`delete`};function refuseUnreachable(e){return async t=>{if(t.kind===`model`){let{model:r,operation:i}=t,a=e.get(r),o=b[i],s=t.controls?.as;if(!a.listed||o!==void 0&&!a.verbs.has(o)||typeof s==`string`&&!a.modes.has(s))throw new n(r,i)}return await t.proceed()}}function scopeSchema(e){return{"~standard":{version:1,vendor:y,validate(t){if(t===void 0)return{value:{unrestricted:!0,allowed:[]}};if(!Array.isArray(t))return{issues:[{message:`Scopes must be an array of model.permission names`}]};let n=new Set;for(let r of t){if(typeof r!=`string`||!Object.hasOwn(e,r))return{issues:[{message:`Unknown permission scope: ${typeof r==`string`?r:`expected a string`}`}]};for(let t of e[r])n.add(t)}return{value:{unrestricted:!1,allowed:[...n]}}}}}}function modesOf(e){let t=[s,...new Set(Object.values(e).flatMap(e=>Object.keys(e.modes)))],narrowing=(e,t)=>t===s||t===e.read?{}:{root:Object.hasOwn(e.modes,t)?e.modes[t]:o};return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.fromEntries(t.map(e=>[e,narrowing(n,e)]))]))}function selfKeyed(e,t){let n=e[t][`~`].state.relations;return Object.values(n).some(n=>n[`~`].state.foreignKey!==void 0&&n[`~`].settleTarget()===e[t])}function reachOf(e,t){return new Map(Object.entries(t).map(([t,n])=>[t,{listed:Object.hasOwn(e.models,t),verbs:new Set([...[`read`,`update`,`delete`].filter(e=>n[e]!==void 0)]),modes:new Set([s,...Object.keys(n.modes)])}]))}function permissions(e){let t=actorContract(e.actor),compile=n=>compilePolicy(e,n,t),r=new WeakMap,definitionOf=(n,r,i)=>({name:y,controls:{actor:{schema:t.schema,bound:!0,required:!0,uncacheable:e.cache!==`allow`},scopes:{schema:scopeSchema(n),bound:!0,required:!0,uncacheable:e.cache!==`allow`}},rows:{control:`as`,default:s,models:modesOf(r),verbs:i},query:refuseUnreachable(reachOf(e,r)),client:e=>({$as:(t,n)=>e.$bind({actor:t,scopes:n})})}),lazyDefinition=n=>{let r=declarationSnapshot(e,new Set([e.actor,...Object.values(n)])),i=policyCompiler(r,Object.freeze({...n}),t),a=plainFreezer(),o=Object.fromEntries(Object.keys(n).map(e=>{if(!Object.hasOwn(r.models,e))return[e,verbsOf({models:{[e]:i.model(e)}})[e]];let t=selfKeyed(n,e)?()=>i.acyclic(e):void 0,o,resolve=()=>{if(o!==void 0)return o;let n=verbsOf({models:{[e]:i.model(e)}})[e],r=a(n)??n;return o=Object.freeze(t?{...r,acyclic:t}:{...r}),o};return[e,resolve]})),s=definitionOf(i.scopes,i.declared,o);return deepFreeze(s.rows),s},eagerDefinition=e=>{let t=compile(e);return definitionOf(t.scopes,t.models,verbsOf(t))},preparedFor=t=>{let n=r.get(t);if(n?.current())return n;r.delete(t);let i=declarationRevision([e,t],new Set([e.actor,...Object.values(t)]));if(i===void 0)return{current:()=>!1,definition:eagerDefinition(t)};let a={current:i,definition:lazyDefinition(t)};return i()&&r.set(t,a),a},declaredActions=t=>{if(t?.actions)return t.actions;let n=new Map(Object.keys(e.models).map(t=>[t,evidenceOf(e,t).names]));return t&&(t.actions=n),n},rows=e=>extend(e,preparedFor(e.$schema).definition),withMethods=(e,t)=>{let answers=e=>{let r=t.get(e);return t=>{let i=t,ask=async(t,a)=>{for(let i of t)if(!r.includes(i))throw new n(e,i);let evidence=async e=>(await i.findUnique({where:a,select:{[c]:e}}))?.[c],o=await evidence(t);return t.map(e=>o?.[e]===!0)};return{can:async(e,t)=>{if(typeof e==`string`)return(await ask([e],t))[0];let n=await ask(e,t);return Object.fromEntries(e.map((e,t)=>[e,n[t]]))},assert:async(t,r)=>{let i=typeof t==`string`?[t]:t,a=await ask(i,r),o=i.find((e,t)=>!a[t]);if(o!==void 0)throw new n(e,o)}}}};return extend(e,{name:`${y}.methods`,model:Object.fromEntries([...t.keys()].map(e=>[e,answers(e)]))})},methods=e=>{let t=r.get(e.$schema);return withMethods(e,declaredActions(t?.current()?t:void 0))},apply=e=>{let t=preparedFor(e.$schema);return withMethods(extend(e,t.definition),declaredActions(t))};return Object.freeze(Object.assign(apply,{config:e,compile,rows,methods}))}function deepFreeze(e){if(!(typeof e!=`object`||!e||Object.isFrozen(e))){for(let t of Object.values(e))deepFreeze(t);Object.freeze(e)}}function extend(e,t){return Reflect.apply(e.$extends,e,[t])}export{permissions};
|
|
2
2
|
//# sourceMappingURL=permissions.mjs.map
|
package/dist/pg.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, An as DriverTransactionOptions, At as DriverConfig, F as LinkedClientConfig, Fn as QueryExecutionContext, Ft as VibORMClient, In as QueryResult, Pt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, jn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-CsO6vG2h.mjs";
|
|
2
2
|
import { Pool, PoolClient, PoolConfig, PoolConfig as PgOptions } from "pg";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/pg/index.d.ts
|
package/dist/pg.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t}from"./execution-context-_oajgBi4.mjs";import{m as n,n as r,r as i,u as a}from"./error-mapping-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{l as t}from"./execution-context-_oajgBi4.mjs";import{m as n,n as r,r as i,u as a}from"./error-mapping-D--MVRCY.mjs";import{t as o}from"./query-CTna5P9o.mjs";import{n as s}from"./transaction-D5LHYn-r.mjs";import{n as c}from"./suppressed-failure-DO0ej03b.mjs";import{n as l}from"./client-Yqn0LqmI.mjs";import{c as u,d,f,i as p,o as m,s as h,t as g,u as _}from"./driver-CK_IKqDa.mjs";import{t as v}from"./postgres-result-D94PyZ78.mjs";import{t as y}from"./postgres-adapter-CYZAL2uo.mjs";import{n as b,t as x}from"./relation-bound-5hindjxU.mjs";import{Client as S,Pool as C,types as w}from"pg";const identityParser=e=>e,T={getTypeParser:(e,t)=>[1082,1114,1184,1115,1182,1185].includes(e)&&t!==`binary`?identityParser:w.getTypeParser(e,t)};function createOwnedPoolErrorState(){let e=0,t={retain(n){e+=1,t.backgroundFailure={error:n,generation:e,isAvailable:!0}}};return t}function holdClientErrors(e){let t,retain=e=>{t??=e};return e.on(`error`,retain),{failure:()=>t,stop:()=>{e.off(`error`,retain)}}}const E=new Set([`user`,`password`,`host`,`port`]),D=[`sslmode`,`sslcert`,`sslkey`,`sslrootcert`];function connectionRecord(e,t){let n=e.connectionString??t;if(!n)return e;if(typeof e.password==`function`)throw new o('Driver "pg" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',{meta:{driver:`pg`,operation:`configuration`}});let r=f(n),i;try{i=new URL(r)}catch{i=void 0}let a=Object.entries(e).filter(([e,t])=>t!==void 0&&(E.has(e)||e===`database`||e===`ssl`||e!==`connectionString`&&i?.searchParams.has(e)));if(a.length===0)return{...e,connectionString:r};if(i===void 0)throw new o(`Driver "pg" could not read its connection URL to apply the connection options beside it.`,{meta:{driver:`pg`,operation:`configuration`}});for(let[e,t]of a)if(i.searchParams.delete(e),e===`ssl`)for(let e of D)i.searchParams.delete(e);else e===`database`?i.pathname=`/${String(t)}`:E.has(e)&&(typeof t==`string`||typeof t==`number`)&&i.searchParams.set(e,String(t));return{...e,connectionString:i.href}}const O={pool:!0,options:!0,pgvector:!0,postgis:!0,databaseUrl:!0,namespace:!0,sharedRelationBodies:!0,relationsPerStatement:!0,migrationSessionAttestation:!0};var PgDriver=class extends g{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;ownedPoolErrors=new WeakMap;serverVersion;readsServer;constructor(e={}){super(`postgresql`,`pg`);let t=d(e);this.suppliedPool=e.pool;let n={...e.options};h(`pg`,e,!!(this.suppliedPool||n.host||n.connectionString)),this.connectionOptions=connectionRecord(n,e.databaseUrl),this.suppliedPool&&(this.client=this.suppliedPool),y(this,t,e),this.readsServer=this.suppliedPool===void 0&&n.Client===void 0&&x(this.adapter,()=>this.serverVersion),m(this,`migrationSessionAttestation`,_(e))}migrationSessionEndpoints(){let e=this.suppliedPool?Reflect.get(this.suppliedPool,`options`):void 0,t=typeof e==`object`&&e?e:{};return[this.connectionOptions.host,this.connectionOptions.connectionString,Reflect.get(t,`host`),Reflect.get(t,`connectionString`)]}initClient(){if(this.suppliedPool!==void 0)return Promise.resolve(this.suppliedPool);let e=new C({types:T,...this.connectionOptions,...this.readsServer?{Client:this.readingClient()}:{}}),t=createOwnedPoolErrorState();return this.ownedPoolErrors.set(e,t),e.on(`error`,t.retain),Promise.resolve(e)}readingClient(){let read=e=>{this.serverVersion=e};return class extends S{constructor(e){super(e),this.connection.on(`parameterStatus`,e=>{e.parameterName===`server_version`&&read(e.parameterValue)})}}}readBackgroundPoolFailure(e){return this.ownedPoolErrors.get(e)?.backgroundFailure}clearBackgroundPoolFailure(e,t){if(t===void 0||!t.isAvailable)return!1;t.isAvailable=!1;let n=this.ownedPoolErrors.get(e);return n?.backgroundFailure?.generation===t.generation&&(n.backgroundFailure=void 0),!0}consumeBackgroundPoolFailure(e,t){if(this.clearBackgroundPoolFailure(e,t))return t?.error}throwPoolQueryFailure(e,t,n,r,a,o){let s=this.consumeBackgroundPoolFailure(e,t);throw s===void 0?n:c(i(n,{driverName:this.driverName,dialect:this.dialect,model:o?.model,operation:o?.operation,correlationId:o?.correlationId,query:r,params:this.getDiagnosticParameters(a??[],o),diagnostics:this.getErrorDisclosure(o),forceContext:!0}),s)}async acquirePooledClient(e,t={},n){let i=this.readBackgroundPoolFailure(e),a=!1;try{return await p(async()=>{try{let t=await e.connect();return this.clearBackgroundPoolFailure(e,i),t}finally{a=!0}},e=>e.release(),n,{driverName:this.driverName,form:`callback`})}catch(n){if(!a)throw n;let o=this.consumeBackgroundPoolFailure(e,i);throw o===void 0?n:c(r(n,{driverName:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId,diagnostics:this.getErrorDisclosure(t)},`Database connection failed after the pool reported a background failure`),o)}}async closeClient(e){if(e===this.suppliedPool)return;let t=this.ownedPoolErrors.get(e);try{await e.end()}catch(n){let i=this.consumeBackgroundPoolFailure(e,t?.backgroundFailure);throw i===void 0?n:c(r(n,{driverName:this.driverName},`Database disconnection failed`),i)}t!==void 0&&(e.off(`error`,t.retain),t.backgroundFailure=void 0,this.ownedPoolErrors.delete(e))}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=this.readBackgroundPoolFailure(e),s=await e.query({text:t,values:n,types:T}).catch(i=>(b(this.adapter,i),this.throwPoolQueryFailure(e,o,i,t,n,r)));return this.clearBackgroundPoolFailure(e,o),{rows:s.rows,rowCount:v(s.rowCount,s.command,s.rows,{provider:`pg`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,r,i,o){if(`release`in e)throw a(this.driverName);let l=await this.acquirePooledClient(e,i,o?.maxWaitMs),u=holdClientErrors(l),withClientFailure=e=>{let t=u.failure();return t===void 0||t===e?e:c(e,t)},d,queryOrDiscard=async e=>{try{await l.query(e)}catch(e){throw d??=e instanceof Error?e:!0,withClientFailure(e)}};return n({begin:()=>queryOrDiscard(`BEGIN`),callback:async()=>{try{return await r(l)}catch(e){throw withClientFailure(e)}},commit:()=>{let e=u.failure();if(e!==void 0)throw e;return queryOrDiscard(`COMMIT`)},rollback:()=>u.failure()===void 0?queryOrDiscard(`ROLLBACK`):void 0,phases:t(i),close:()=>{try{let e=d??u.failure();if(e){l.release(e);return}l.release()}catch(e){throw super.transactionCleanupFailed(new s(`Driver "pg" could not release an unsafe transaction connection.`,{meta:{driver:`pg`,method:`$transaction`}})),e}finally{u.stop()}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`release`in e)throw a(this.driverName);let t=await this.acquirePooledClient(e,{operation:`pinnedSession`}),n=holdClientErrors(t);return{session:t,lost:n.failure,release:e=>{try{t.release(n.failure()??(e?!0:void 0))}finally{n.stop()}return Promise.resolve()}}}};function createClient(e){u(e,`pg`,O);let{pool:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e;return l(e,new PgDriver({namespace:d(e),migrationSessionAttestation:_(e),pool:t||void 0,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement}))}export{PgDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pg.mjs.map
|
package/dist/pg.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n /**\n * The `server_version` the last connection this driver's own pool opened\n * received at startup, read for the relation bound (`boundByServer`); a\n * pool given its own `Client` class, or supplied, is not read.\n */\n private serverVersion: string | undefined;\n private readonly readsServer: boolean;\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.readsServer =\n this.suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => this.serverVersion);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...this.connectionOptions,\n ...(this.readsServer ? { Client: this.readingClient() } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n /**\n * node-postgres's `Client`, reading each connection's startup: it keeps no\n * parameter status, so the `server_version` that names Neki is read as it\n * arrives, before the connection is handed out (to a statement, or to a\n * transaction before its callback builds any).\n */\n private readingClient(): typeof Client {\n const read = (version: string) => {\n this.serverVersion = version;\n };\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n read(status.parameterValue);\n }\n );\n }\n };\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n return this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n );\n });\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"moBAoEA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAAS,iBAAiB,EAAwC,CAChE,IAAI,EACE,OAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,QAAS,OAAO,CACnB,CACL,YAAe,EACf,SAAY,CACV,EAAO,IAAI,QAAS,OAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,iBACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9B,MAAM,IAAI,EACR,+KACA,CAAE,KAAM,CAAE,OAAQ,KAAM,UAAW,gBAAiB,CAAE,CACvD,CAEH,IAAM,EAAmB,EAAuB,EAAM,CAClD,EACJ,GAAI,CACF,EAAM,IAAI,IAAI,EAAiB,MACzB,CACN,EAAM,IAAA,GAGR,IAAM,EAD+B,OAAO,QAAQ,EAAQ,CAClC,QACvB,CAAC,EAAK,KACL,IAAU,IAAA,KACT,EAAe,IAAI,EAAI,EACtB,IAAQ,YACR,IAAQ,OACP,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EAiB/D,OAAO,EAA6C,EAhBrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC/B,CAAC,CAEiE"}
|
|
1
|
+
{"version":3,"file":"pg.mjs","names":["pgTypes"],"sources":["../src/drivers/pg/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (node-postgres)\n *\n * Driver implementation for pg (node-postgres) with connection pooling.\n *\n * No statement pipelining. node-postgres has no pipeline mode: a `Client` holds\n * one query active at a time and drains the rest from an internal queue, so the\n * statements of a transaction always cost one round trip each no matter how\n * they are issued. Nothing here can change that, and nothing here tries to —\n * see the Phase 9 disposition in `docs/architecture/query-performance-plan.md`,\n * which measured the same limit on the postgres.js driver for different\n * reasons.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, TransactionError } from \"@errors\";\nimport {\n Client,\n type ClientConfig,\n Pool,\n type PoolClient,\n type PoolConfig,\n types as pgTypes,\n} from \"pg\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n normalizeDriverConnectionError,\n normalizeDriverError,\n} from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\n// DATE (1082) and TIMESTAMP WITHOUT TIME ZONE (1114): pg's default parsers\n// build process-local Dates, shifting the stored value by the process\n// timezone. Return the raw strings instead — the shared result parser builds\n// UTC Dates from them, matching every other driver.\nconst DATE_OID = 1082;\nconst TIMESTAMP_OID = 1114;\nconst identityParser = (value: string) => value;\nconst utcSafeTypes: PoolConfig[\"types\"] = {\n getTypeParser: (oid: number, format?: string) => {\n if (\n [DATE_OID, TIMESTAMP_OID, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return pgTypes.getTypeParser(oid as never, format as never);\n },\n};\n\ninterface BackgroundPoolFailure {\n readonly error: Error;\n readonly generation: number;\n isAvailable: boolean;\n}\n\ninterface OwnedPoolErrorState {\n backgroundFailure?: BackgroundPoolFailure;\n readonly retain: (error: Error) => void;\n}\n\nfunction createOwnedPoolErrorState(): OwnedPoolErrorState {\n let generation = 0;\n const state: OwnedPoolErrorState = {\n retain(error) {\n generation += 1;\n state.backgroundFailure = { error, generation, isAvailable: true };\n },\n };\n return state;\n}\n\n/**\n * The `error` channel of one checked-out client, owned for as long as VibORM\n * holds that client.\n *\n * pg-pool removes its idle listener on checkout and puts it back on release,\n * so a connection that drops in between (a restart, a failover, a terminated\n * backend) would otherwise emit an unhandled `error` and end the process. The\n * first failure is kept: its holder refuses to commit after it and releases the\n * client with it, so the pool destroys that connection instead of reusing it.\n *\n * This holds for a supplied pool too. Its `error` event stays the caller's, but\n * a checked-out client is the holder's to answer for until it is released.\n */\ninterface HeldClientErrors {\n readonly failure: () => Error | undefined;\n readonly stop: () => void;\n}\n\nfunction holdClientErrors(client: PgPoolClient): HeldClientErrors {\n let failure: Error | undefined;\n const retain = (error: Error) => {\n failure ??= error;\n };\n client.on(\"error\", retain);\n return {\n failure: () => failure,\n stop: () => {\n client.off(\"error\", retain);\n },\n };\n}\n\n/** The keys node-postgres's URL parser reads from the query before the authority. */\nconst URL_QUERY_KEYS = new Set([\"user\", \"password\", \"host\", \"port\"]);\n/** The query parameters node-postgres derives `ssl` from. */\nconst URL_SSL_KEYS = [\"sslmode\", \"sslcert\", \"sslkey\", \"sslrootcert\"];\n\n/**\n * The pool's connection record: the caller's options, with `databaseUrl` as\n * the connection string unless `options.connectionString` names one, and each\n * connection option they set written into that URL so that it wins.\n *\n * node-postgres parses the connection string over the options beside it and\n * fills the connection keys the URL lacks with empty values, so a per-tenant\n * URL without a password lost `options.password` from a secret, and the URL's\n * port replaced `options.port`. Its parser prefers `user`, `password`, `host`\n * and `port` from the query and reads the database from the path, so an\n * explicit key is written there; any other option the query also names is\n * dropped from it, and an explicit `ssl` drops the parameters that derive one.\n * A password callback cannot be written into a URL, and node-postgres would\n * replace it with the URL's password, so one beside a URL is refused.\n */\nfunction connectionRecord(\n options: PoolConfig,\n databaseUrl: string | undefined\n): PoolConfig {\n const given = options.connectionString ?? databaseUrl;\n if (!given) return options;\n if (typeof options.password === \"function\") {\n throw new ClientInitializationError(\n 'Driver \"pg\" cannot keep a password callback beside a connection URL: node-postgres reads the password from the URL. Pass `host`, `user` and `database` in `options` instead.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n const connectionString = systemRootAsVerifyFull(given);\n let url: URL | undefined;\n try {\n url = new URL(connectionString);\n } catch {\n url = undefined;\n }\n const entries: [string, unknown][] = Object.entries(options);\n const overrides = entries.filter(\n ([key, value]) =>\n value !== undefined &&\n (URL_QUERY_KEYS.has(key) ||\n key === \"database\" ||\n key === \"ssl\" ||\n (key !== \"connectionString\" && url?.searchParams.has(key)))\n );\n if (overrides.length === 0) return { ...options, connectionString };\n if (url === undefined) {\n throw new ClientInitializationError(\n 'Driver \"pg\" could not read its connection URL to apply the connection options beside it.',\n { meta: { driver: \"pg\", operation: \"configuration\" } }\n );\n }\n for (const [key, value] of overrides) {\n url.searchParams.delete(key);\n if (key === \"ssl\") {\n for (const sslKey of URL_SSL_KEYS) url.searchParams.delete(sslKey);\n } else if (key === \"database\") {\n url.pathname = `/${String(value)}`;\n } else if (\n URL_QUERY_KEYS.has(key) &&\n (typeof value === \"string\" || typeof value === \"number\")\n ) {\n url.searchParams.set(key, String(value));\n }\n }\n return { ...options, connectionString: url.href };\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PoolConfig as PgOptions } from \"pg\";\n\ninterface PgErrorEvents {\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** The part of a node-postgres `PoolClient` this driver uses. */\ninterface PgPoolClient\n extends Pick<PoolClient, \"query\" | \"release\">,\n PgErrorEvents {}\n\n/**\n * The part of a node-postgres `Pool` this driver uses, so any pool with that\n * shape is accepted. A Neon WebSocket `Pool` (`@neondatabase/serverless`) is\n * node-postgres's pool over a WebSocket and runs here unchanged, but its\n * bundled copy of the pg declarations lags `@types/pg`: in 8.23 a\n * `PoolClient` is a whole `Client`, and the full `Pool` type refused Neon's.\n */\ninterface PgPool extends Pick<Pool, \"query\" | \"end\">, PgErrorEvents {\n connect(): Promise<PgPoolClient>;\n}\n\nexport interface PgDriverOptions {\n pool?: PgPool;\n options?: PoolConfig;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Each relation filter body a statement repeats is stated once, in a\n * `WITH`, as the key set its arms test: the answers are the same, the\n * statement smaller, and a server that bounds the relations one statement\n * references (PlanetScale's Neki: 256) accepts it. Defaults to `true`;\n * `false` keeps every body inline.\n */\n sharedRelationBodies?: boolean;\n /**\n * The most relations (`FROM` items) one statement may reference. Past it, a\n * statement states the recursive filters it repeats as key sets, and then\n * joins the key sets a row tests, as far as it needs to fit: the answers are\n * the same, some plans slower. PlanetScale Neki refuses a statement over\n * 256: absent, a pool this driver makes reads each connection's startup,\n * 256 on Neki and before the first connection, none on plain PostgreSQL (a\n * supplied pool learns from Neki's first refusal). A stated bound always\n * wins. Only where relation bodies are shared.\n */\n relationsPerStatement?: number;\n /**\n * Your claim, at your risk, that every connection this pool opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type PgClientConfig<C extends DriverConfig> = PgDriverOptions & C;\n\nconst PG_CONFIG_KEYS: Record<keyof PgDriverOptions, true> = {\n pool: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PgDriver extends Driver<PgPool, PgPoolClient> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled here, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed\n * and may be sharing with the caller's own code.\n */\n private readonly suppliedPool: PgPool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database, connectionString — all live here,\n * with the caller's `databaseUrl` merged in (see `connectionRecord`).\n */\n private readonly connectionOptions: PoolConfig;\n /**\n * The listener and latest idle failure for each pool this driver created.\n *\n * Pool identity matters after a failed `end()`: the base lifecycle\n * quarantines that exact pool for a later disconnect retry, while this state\n * keeps its error listener and retained evidence attached to the same\n * transport until a proven successful end.\n */\n private readonly ownedPoolErrors = new WeakMap<object, OwnedPoolErrorState>();\n /**\n * The `server_version` the last connection this driver's own pool opened\n * received at startup, read for the relation bound (`boundByServer`); a\n * pool given its own `Client` class, or supplied, is not read.\n */\n private serverVersion: string | undefined;\n private readonly readsServer: boolean;\n\n constructor(options: PgDriverOptions = {}) {\n super(\"postgresql\", \"pg\");\n const namespace = resolveNamespaceOption(options);\n this.suppliedPool = options.pool;\n const connection = { ...options.options };\n refuseEmptyDatabaseUrl(\n \"pg\",\n options,\n Boolean(\n this.suppliedPool || connection.host || connection.connectionString\n )\n );\n this.connectionOptions = connectionRecord(connection, options.databaseUrl);\n\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n\n installPostgresAdapter(this, namespace, options);\n this.readsServer =\n this.suppliedPool === undefined &&\n connection.Client === undefined &&\n boundByServer(this.adapter, () => this.serverVersion);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's pool connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const supplied: unknown = this.suppliedPool\n ? Reflect.get(this.suppliedPool, \"options\")\n : undefined;\n const pool =\n typeof supplied === \"object\" && supplied !== null ? supplied : {};\n return [\n this.connectionOptions.host,\n this.connectionOptions.connectionString,\n Reflect.get(pool, \"host\"),\n Reflect.get(pool, \"connectionString\"),\n ];\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n *\n * It is also returned UNSUBSCRIBED. A supplied pool is borrowed transport and\n * its events belong to its owner: an 'error' listener added here is the very\n * thing that stops Node from throwing, so VibORM would be silencing a crash\n * for a caller who never asked it to — and for the other consumers of a pool\n * two estates share. This driver listens only on the pool it made.\n */\n protected initClient(): Promise<PgPool> {\n if (this.suppliedPool !== undefined) {\n return Promise.resolve(this.suppliedPool);\n }\n const pool = new Pool({\n types: utcSafeTypes,\n ...this.connectionOptions,\n ...(this.readsServer ? { Client: this.readingClient() } : {}),\n });\n const errorState = createOwnedPoolErrorState();\n this.ownedPoolErrors.set(pool, errorState);\n pool.on(\"error\", errorState.retain);\n return Promise.resolve(pool);\n }\n\n /**\n * node-postgres's `Client`, reading each connection's startup: it keeps no\n * parameter status, so the `server_version` that names Neki is read as it\n * arrives, before the connection is handed out (to a statement, or to a\n * transaction before its callback builds any).\n */\n private readingClient(): typeof Client {\n const read = (version: string) => {\n this.serverVersion = version;\n };\n return class extends Client {\n constructor(config?: string | ClientConfig) {\n super(config);\n this.connection.on(\n \"parameterStatus\",\n (status: { parameterName: string; parameterValue: string }) => {\n if (status.parameterName === \"server_version\")\n read(status.parameterValue);\n }\n );\n }\n };\n }\n\n private readBackgroundPoolFailure(\n pool: PgPool | PgPoolClient\n ): BackgroundPoolFailure | undefined {\n return this.ownedPoolErrors.get(pool)?.backgroundFailure;\n }\n\n /** Clear exactly the failure observed before an operation started. */\n private clearBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): boolean {\n if (observed === undefined || !observed.isAvailable) return false;\n observed.isAvailable = false;\n const state = this.ownedPoolErrors.get(pool);\n if (state?.backgroundFailure?.generation === observed.generation) {\n state.backgroundFailure = undefined;\n }\n return true;\n }\n\n /** Claim one retained failure for one failed acquisition, at most once. */\n private consumeBackgroundPoolFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined\n ): Error | undefined {\n if (!this.clearBackgroundPoolFailure(pool, observed)) return undefined;\n return observed?.error;\n }\n\n /** Surface one pool-owned idle failure beside one pool query failure. */\n private throwPoolQueryFailure(\n pool: PgPool | PgPoolClient,\n observed: BackgroundPoolFailure | undefined,\n error: unknown,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined\n ): never {\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const queryFailure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n model: context?.model,\n operation: context?.operation,\n correlationId: context?.correlationId,\n query: sql,\n params: this.getDiagnosticParameters(params ?? [], context),\n diagnostics: this.getErrorDisclosure(context),\n forceContext: true,\n });\n throw withSuppressedFailure(queryFailure, background);\n }\n\n /**\n * One pooled connection, and — when there is none to be had — the current\n * acquisition failure as primary, with the pool's last background failure\n * retained beside it.\n *\n * The acquisition rejection is the failure of the requested action, so it\n * stays primary. The background report arrived outside every request and is\n * retained through the shared suppressed-failure record. Reported once and\n * released, so the next failure speaks for itself rather than inheriting an\n * explanation that has already been given. An acquisition that fails with\n * nothing retained is left exactly as it was.\n */\n private async acquirePooledClient(\n pool: PgPool,\n context: QueryExecutionContext = {},\n maxWaitMs?: number\n ): Promise<PgPoolClient> {\n const observed = this.readBackgroundPoolFailure(pool);\n let acquisitionSettled = false;\n try {\n const client = await acquireWithMaxWait(\n async () => {\n try {\n const acquired = await pool.connect();\n // This runs even when maxWait has already rejected the caller: a\n // late success healed the pre-start failure before the abandoned\n // client goes straight back to the pool.\n this.clearBackgroundPoolFailure(pool, observed);\n return acquired;\n } finally {\n acquisitionSettled = true;\n }\n },\n (acquired) => acquired.release(),\n maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n return client;\n } catch (error) {\n // A maxWait winner abandons the acquisition. Its eventual rejection is\n // observed by acquireWithMaxWait, but it must not consume evidence into\n // a promise whose result no caller will ever inspect.\n if (!acquisitionSettled) throw error;\n const background = this.consumeBackgroundPoolFailure(pool, observed);\n if (background === undefined) throw error;\n const acquisitionFailure = normalizeDriverConnectionError(\n error,\n {\n driverName: this.driverName,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n diagnostics: this.getErrorDisclosure(context),\n },\n \"Database connection failed after the pool reported a background failure\"\n );\n throw withSuppressedFailure(acquisitionFailure, background);\n }\n }\n\n /**\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients — two schema-scoped estates over one pool is the documented shape\n * — and §5.3's rule is that VibORM never changes a caller's connection\n * state. `$disconnect()` used to end it regardless, so disconnecting one\n * client tore down every other consumer of that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: PgPool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n const errorState = this.ownedPoolErrors.get(pool);\n try {\n await pool.end();\n } catch (error) {\n const background = this.consumeBackgroundPoolFailure(\n pool,\n errorState?.backgroundFailure\n );\n if (background === undefined) throw error;\n const disconnectFailure = normalizeDriverConnectionError(\n error,\n { driverName: this.driverName },\n \"Database disconnection failed\"\n );\n throw withSuppressedFailure(disconnectFailure, background);\n }\n // AFTER a proven end, not before it: `end()` disposes idle clients whose\n // own listeners can still re-emit on the pool. If end rejects, the still\n // live pool keeps containment; its pre-start evidence travels on the public\n // disconnect failure, exactly once.\n if (errorState !== undefined) {\n pool.off(\"error\", errorState.retain);\n errorState.backgroundFailure = undefined;\n this.ownedPoolErrors.delete(pool);\n }\n }\n\n protected async execute<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PgPool | PgPoolClient,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const observed = this.readBackgroundPoolFailure(client);\n const result = await client\n .query({ text: sql, values: params, types: utcSafeTypes })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n return this.throwPoolQueryFailure(\n client,\n observed,\n error,\n sql,\n params,\n context\n );\n });\n // `Pool.query` includes an acquisition. Its success proves transport\n // recovery, but only for evidence that predates this exact operation.\n this.clearBackgroundPoolFailure(client, observed);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n { provider: \"pg\", operation }\n ),\n };\n }\n\n /**\n * PostgreSQL takes the isolation level as the first statement inside the\n * transaction, and node-postgres hands out a pooled client we can wait for\n * with a bound (and release if we stop waiting).\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: PgPool | PgPoolClient,\n fn: (tx: PgPoolClient) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction\n const poolClient = await this.acquirePooledClient(\n client,\n context,\n options?.maxWaitMs\n );\n const clientErrors = holdClientErrors(poolClient);\n // A step's own failure stays primary; a different client failure travels\n // beside it through the shared evidence owner instead of being lost.\n const withClientFailure = (error: unknown): unknown => {\n const failure = clientErrors.failure();\n return failure === undefined || failure === error\n ? error\n : withSuppressedFailure(error, failure);\n };\n let releaseError: Error | boolean | undefined;\n const queryOrDiscard = async (statement: string) => {\n try {\n await poolClient.query(statement);\n } catch (error) {\n releaseError ??= error instanceof Error ? error : true;\n throw withClientFailure(error);\n }\n };\n return runTransactionLifecycle({\n begin: () => queryOrDiscard(\"BEGIN\"),\n callback: async () => {\n try {\n return await fn(poolClient);\n } catch (error) {\n throw withClientFailure(error);\n }\n },\n commit: () => {\n // A callback that settles after its connection failed must not commit:\n // whatever it awaited meanwhile never reached the database.\n const failure = clientErrors.failure();\n if (failure !== undefined) throw failure;\n return queryOrDiscard(\"COMMIT\");\n },\n // The server ends a transaction with its session; a ROLLBACK sent on a\n // client that is no longer queryable would only add a second failure.\n rollback: () =>\n clientErrors.failure() === undefined\n ? queryOrDiscard(\"ROLLBACK\")\n : undefined,\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n const discard = releaseError ?? clientErrors.failure();\n if (discard) {\n poolClient.release(discard);\n return;\n }\n poolClient.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"pg\" could not release an unsafe transaction connection.',\n { meta: { driver: \"pg\", method: \"$transaction\" } }\n )\n );\n throw error;\n } finally {\n clientErrors.stop();\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // The failed PoolClient was discarded with release(error); the pool stays usable.\n }\n\n /**\n * One `PoolClient` from `pool.connect()` — plan §3.5's pinned producer for\n * `pg`. `release(true)` destroys the connection instead of returning it, so a\n * session whose advisory-lock state is unknown never re-enters the pool.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PgPool | PgPoolClient>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"release\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const poolClient = await this.acquirePooledClient(client, {\n operation: \"pinnedSession\",\n });\n const clientErrors = holdClientErrors(poolClient);\n return {\n session: poolClient,\n // The client's own `error` event is how pg reports a socket that died\n // between or under statements; the pinned session then sends nothing\n // more on it (plan S2). Release destroys it either way.\n lost: clientErrors.failure,\n release: (discard) => {\n try {\n poolClient.release(\n clientErrors.failure() ?? (discard ? true : undefined)\n );\n } finally {\n clientErrors.stop();\n }\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PgClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PgDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: PgDriver }>]: LinkedClientConfig<\n C & { driver: PgDriver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pg\", PG_CONFIG_KEYS);\n const { pool, options = {}, pgvector, postgis, databaseUrl } = config;\n const driver = new PgDriver({\n // Namespace, then attestation: the order a refusal reports in.\n namespace: resolveNamespaceOption(config),\n migrationSessionAttestation:\n resolveMigrationSessionAttestationOption(config),\n // Only a supplied pool counts: a falsy one leaves the driver to build its own.\n pool: pool || undefined,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n });\n\n return createClientFromDriverConfig<S, C, PgDriver>(config, driver);\n}\n"],"mappings":"8nBAoEA,MAEM,eAAkB,GAAkB,EACpC,EAAoC,CACxC,eAAgB,EAAa,IAEzB,CAAC,KAAU,KAAe,KAAM,KAAM,KAAM,KAAK,CAAC,SAAS,EAAI,EAC/D,IAAW,SAEJ,eAEFA,EAAQ,cAAc,EAAc,EAAgB,CAE9D,CAaD,SAAS,2BAAiD,CACxD,IAAI,EAAa,EACX,EAA6B,CACjC,OAAO,EAAO,CACZ,GAAc,EACd,EAAM,kBAAoB,CAAE,QAAO,aAAY,YAAa,GAAM,EAErE,CACD,OAAO,EAqBT,SAAS,iBAAiB,EAAwC,CAChE,IAAI,EACE,OAAU,GAAiB,CAC/B,IAAY,GAGd,OADA,EAAO,GAAG,QAAS,OAAO,CACnB,CACL,YAAe,EACf,SAAY,CACV,EAAO,IAAI,QAAS,OAAO,EAE9B,CAIH,MAAM,EAAiB,IAAI,IAAI,CAAC,OAAQ,WAAY,OAAQ,OAAO,CAAC,CAE9D,EAAe,CAAC,UAAW,UAAW,SAAU,cAAc,CAiBpE,SAAS,iBACP,EACA,EACY,CACZ,IAAM,EAAQ,EAAQ,kBAAoB,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,GAAI,OAAO,EAAQ,UAAa,WAC9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Ae,iBAAiB,EAAW,CACjD,MAAO,CACL,QAAS,EAIT,KAAM,EAAa,QACnB,QAAU,GAAY,CACpB,GAAI,CACF,EAAW,QACT,EAAa,SAAS,GAAK,EAAU,GAAO,IAAA,IAC7C,QACO,CACR,EAAa,MAAM,CAErB,OAAO,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAiB/D,OAAO,EAA6C,EAhBrC,IAAI,SAAS,CAE1B,UAAW,EAAuB,EAAO,CACzC,4BACE,EAAyC,EAAO,CAElD,KAAM,GAAQ,IAAA,GACd,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC/B,CAAC,CAEiE"}
|
package/dist/pglite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema, At as DriverConfig, F as LinkedClientConfig,
|
|
1
|
+
import { A as Schema, At as DriverConfig, F as LinkedClientConfig, Fn as QueryExecutionContext, Ft as VibORMClient, In as QueryResult, Pt as NoExtraDriverConfigKeys, jn as TransactionOptionSupport, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver } from "./index-CsO6vG2h.mjs";
|
|
2
2
|
import { PGlite, PGliteOptions, PGliteOptions as PGliteOptions$1, Transaction } from "@electric-sql/pglite";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/pglite/index.d.ts
|
package/dist/pglite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-23DWxZVY.mjs";import{l as n}from"./execution-context-_oajgBi4.mjs";import{f as r,u as i}from"./error-mapping-D--MVRCY.mjs";import{n as a}from"./client-Yqn0LqmI.mjs";import{a as o,n as s}from"./pinned-session-De2rDjdO.mjs";import{c,d as l,r as u,t as d}from"./driver-CK_IKqDa.mjs";import{t as f}from"./postgres-adapter-CYZAL2uo.mjs";import{PGlite as p}from"@electric-sql/pglite";const m=Object.fromEntries([1082,1114,1184,1115,1182,1185].map(e=>[e,e=>e])),h={client:!0,dataDir:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function isPGliteDatabase(e){return`transaction`in e}var PGliteDriver=class extends d{maxBindParametersPerStatement=32767;serializeTransactions=!0;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`pglite`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)})),f(this,t,e)}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let e=this.driverOptions.dataDir,t=this.driverOptions.options??{},n={...t,parsers:{1114:e=>e,...t.parsers}};return e?await p.create(e,n):await p.create(n)}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,n,r,i,a){let o=i?.operation??a,s=await e.query(n,r,{parsers:m}),c=t(s.affectedRows,{provider:`pglite`,operation:o});return{rows:s.rows,rowCount:s.rows.length>0?s.rows.length:c}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`queue`}}transaction(e,t,a){if(!isPGliteDatabase(e))throw i(this.driverName);return r({run:t=>e.transaction(t),callback:t,phases:n(a),close:async()=>void 0})}async physicalPinnedSession(){return await this.getClient({operation:`pinnedSession`})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!isPGliteDatabase(e))throw i(this.driverName);return{session:e,release:async t=>{if(t)try{await e.query(`SELECT pg_advisory_unlock_all()`)}catch(t){throw s(e),o(this.driverName,`No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.`,t)}}}}};function createClient(e){c(e,`pglite`,h);let{client:t,dataDir:n,options:r,pgvector:i,postgis:o}=e,s=l(e);return a(e,new PGliteDriver({client:t,dataDir:n,options:r,pgvector:i,postgis:o,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{PGliteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=pglite.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
2
|
-
//# sourceMappingURL=physical-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{at as t,rt as n}from"./geo-point-codec-CIZxuIvE.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-CQH05hcr.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
|
|
2
|
+
//# sourceMappingURL=physical-t_gDjUCD.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"physical-CAZ_LauY.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,EAuBT,MAAM,EAAiB,mCACjB,EACJ,qEACI,EAAqB,SACrB,EAAqB,kCAG3B,SAAS,iBAAiB,EAAkB,EAA+B,CACzE,IAAM,EAAQ,EAAa,EAAO,CAClC,GAAI,IAAU,IAAA,GAEZ,OAAQ,EAAR,CACE,IAAK,KACH,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAG,OAAO,KAAK,KAAM,CACpE,IAAK,QACH,MAAO,CAAE,eAAgB,OAAQ,WAAY,OAAQ,CACvD,QACE,MAAO,CACL,eAAgB,OAChB,WAAY,EAAO,OAAO,KAAK,KAChC,CAGP,OAAQ,EAAR,CACE,IAAK,KAKH,OAAO,IAAW,QAAU,IAAW,SACnC,CAAE,eAAgB,OAAQ,WAAY,EAAG,OAAO,KAAK,KAAM,CAC3D,CAAE,eAAgB,QAAS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CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
|
|
1
|
+
{"version":3,"file":"physical-t_gDjUCD.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAA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,MAAO,QAC1C,IAAM,EAAQ,EAAmB,KAAK,EAAK,CAC3C,OAAO,GAAS,OAAO,EAAM,GAAG,GAAK,EAAQ,QAAU,IAAA,GAmBzD,SAAgB,YACd,EACA,EACA,EACuB,CACvB,IAAM,EAAa,EAAc,EAAa,EAAQ,CACtD,GAAI,IAAe,IAAA,GACjB,OAAO,iBAAiB,EAAO,OAAQ,EAAQ,CAEjD,IAAM,EAAO,EAAW,KACxB,GAAI,iBAAiB,EAAM,EAAQ,CAGjC,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAM,CAErD,IAAM,EAAiB,qBAAqB,EAAM,EAAO,OAAQ,EAAQ,CACzE,OAAO,IAAmB,IAAA,GACtB,IAAA,GACA,CAAE,iBAAgB,WAAY,EAAM,CAI1C,SAAgB,sBACd,EACA,EACQ,CACR,IAAM,EAAQ,EAAa,EAAO,CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-wlv81COV.mjs";import{n as r}from"./query-CTna5P9o.mjs";import{n as i}from"./suppressed-failure-DO0ej03b.mjs";import{t as a}from"./settle-v6QhvFkm.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
|
|
2
|
+
//# sourceMappingURL=pinned-session-De2rDjdO.mjs.map
|