viborm 1.14.2 → 1.15.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/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
- package/dist/adapters.d.mts +15 -3
- package/dist/adapters.mjs +1 -1
- package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
- package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
- package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.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/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 +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
- package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-CVCC-D1j.mjs +2 -0
- package/dist/client-CVCC-D1j.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
- package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
- package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
- package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
- package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
- package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
- package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
- package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
- package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
- package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
- package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
- package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +1 -1
- package/dist/error-mapping-DIRlrmDK.mjs +2 -0
- package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
- package/dist/every-BHEmfLOW.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
- package/dist/execution-context-VMQm-9CH.mjs +2 -0
- package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
- package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
- package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
- package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
- package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
- package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
- package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
- package/dist/identifiers-BTCfD5ic.mjs +2 -0
- package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
- package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
- package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
- package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
- package/dist/judge-words-DpwxOfre.mjs +2 -0
- package/dist/judge-words-DpwxOfre.mjs.map +1 -0
- package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
- package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
- package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
- package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
- package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
- package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
- package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
- package/dist/methods-part-DoTrY6b9.mjs +2 -0
- package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
- package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
- package/dist/named-statements-CMj1QEyw.mjs +2 -0
- package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
- package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
- package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
- package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
- package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
- package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
- package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +1 -1
- package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +27 -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-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
- package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
- package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
- package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
- package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
- package/dist/postgres-result-CiS5OWp1.mjs +2 -0
- package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
- package/dist/postgres.d.mts +17 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
- package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
- package/dist/query-Cdy8E2jM.mjs +2 -0
- package/dist/query-Cdy8E2jM.mjs.map +1 -0
- package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
- package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
- package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
- package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
- package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
- package/dist/scalar-B9WizsvR.mjs +4 -0
- package/dist/scalar-B9WizsvR.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
- package/dist/schema-MB-pPNTO.mjs.map +1 -0
- package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
- package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
- package/dist/schema-introspection-wMVZowIF.mjs +6 -0
- package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-SuVxJjps.mjs +2 -0
- package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
- package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
- package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
- package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
- package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
- package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +1 -1
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
- package/dist/sql-BGjAsoBE.mjs +2 -0
- package/dist/sql-BGjAsoBE.mjs.map +1 -0
- package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
- package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
- package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
- package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
- package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
- package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
- package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
- package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
- package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
- package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
- package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
- package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
- package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
- package/dist/validation-D0LG854o.mjs +2 -0
- package/dist/validation-D0LG854o.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
- package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
- package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
- package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
- package/dist/version-B_ZLWzLW.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
- package/package.json +35 -35
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/version-CXGIA82S.mjs +0 -2
package/dist/client.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $r as
|
|
2
|
-
import { n as ClientOmitConfig, r as ExactClientOmitConfig, t as defaultOmit } from "./exports-
|
|
3
|
-
export { type AddedProjectedState, type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type CachedClientOf, type Client, type ClientHiddenContext, type ClientOmitConfig, type ClientSchema, type ClientTypeState, type CountResultType, type ExactClientOmitConfig, type ExtendedClient, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type NoExtraOperationKeys, type ObjectSchema, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedArgument, type ProjectedModelOperations, type RawOperation, type RelationLinks, type RowsFragment, type Schema, type StampedFields, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
|
|
1
|
+
import { $r as CachedClient, Ar as validateOperationPayload, Ci as RelationLinks, Ct as RowsFragment, Dr as getOperationPayloadSchema, Fr as isPendingOperation, Gi as IndexDefinition, K as StampedFields, Ki as IndexOptions, Mr as PendingOperation, Nr as UnwrapPendingOperation, Or as renderOperationResultType, Pr as UnwrapPendingOperations, Qr as CacheableOperations, Si as Links, St as RawOperation, U as PlacedArgument, _a as ObjectSchema, ai as OperationPayload, bi as Linked, bt as ExtensionResultConsumerState, ci as Operations, ct as ExtendedClient, di as AggregateResultType, ei as CallOptions, et as AddedProjectedState, fi as BatchPayload, gi as InferSelectInclude, hi as GroupByResultType, ii as NoExtraOperationKeys, jr as ProjectedModelOperations, kr as renderSchemaType, li as Schema, mi as CountResultType, ni as InferDatabase, nt as ClientTypeState, oi as OperationPayloadSchema, pi as ClientHiddenContext, qt as VibSchema, ri as MutationOperations, si as OperationResult, ti as Client, tt as CachedClientOf, ui as ValidatedOperationPayload, vi as ClientSchema, xi as LinkedClientConfig, yi as FlatSchema } from "./database-adapter-D62c-uC6.mjs";
|
|
2
|
+
import { n as ClientOmitConfig, r as ExactClientOmitConfig, t as defaultOmit } from "./exports-Bzvtum3F.mjs";
|
|
3
|
+
export { type AddedProjectedState, type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type CachedClientOf, type CallOptions, type Client, type ClientHiddenContext, type ClientOmitConfig, type ClientSchema, type ClientTypeState, type CountResultType, type ExactClientOmitConfig, type ExtendedClient, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type NoExtraOperationKeys, type ObjectSchema, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedArgument, type ProjectedModelOperations, type RawOperation, type RelationLinks, type RowsFragment, type Schema, type StampedFields, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
|
package/dist/client.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./validation--qS7OPmg.mjs";import{t as n}from"./extension-CGepsF-p.mjs";import{r,t as i}from"./pending-operation-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./validation--qS7OPmg.mjs";import{t as n}from"./extension-CGepsF-p.mjs";import{r,t as i}from"./pending-operation-Dq4rv-Ml.mjs";import{i as a,n as o,r as s,t as c}from"./schema-introspection-wMVZowIF.mjs";import{n as l,t as u}from"./defaults-CrtGVdEC.mjs";function defaultOmit(e){let r={};for(let[n,i]of Object.entries(e)){let e={};for(let[r,a]of Object.entries(i)){if(a!==!0)throw new t(`Default omit configuration member "${n}.${r}" must be true.`);e[r]=l}r[n]={fields:e}}return n(`viborm.defaultOmit`,u(()=>r))}export{i as PendingOperation,defaultOmit,c as getOperationPayloadSchema,r as isPendingOperation,o as renderOperationResultType,s as renderSchemaType,a as validateOperationPayload};
|
|
2
2
|
//# sourceMappingURL=client.mjs.map
|
package/dist/config.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as ResolveCallback, t as MigrationClient } from "./planner-
|
|
1
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-Ckoxeruk.mjs";
|
|
2
2
|
import { n as MigrationStorageWriter } from "./contract-CrIB-3ZJ.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/cli/utils.d.ts
|
package/dist/config.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./utils-
|
|
1
|
+
import{t as e}from"./utils-BLlgSQIo.mjs";export{e as defineConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./schema-
|
|
2
|
-
//# sourceMappingURL=confine-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./schema-MB-pPNTO.mjs";import{l as n,t as r}from"./judge-words-DpwxOfre.mjs";function bound(e){let r=new Map;return(i,a)=>{let o=i[`~`].names.ts,s=e.rows.confine?.get(o);if(s!==void 0)return t(r,`${o} ${a}`,()=>e.conjunction(i,a.map(e=>[e,[s[e]].filter(n)])))??void 0}}const i={admit:({admit:e},t,n)=>Object.fromEntries(Object.entries(t).map(([t,r])=>[t,e(t,`${t}.confine`,r,n)])),bind(e){let n=new Map;for(let[r,i]of e.entries())for(let[e,a]of Object.entries(i.confine??{}))t(n,e,()=>[])[r]=a;return{confine:n,bound}}};var Within=class extends r{join({key:e,model:t,schema:n,lazy:r,layer:a,refuse:o}){(e!==`confine`||r)&&o(`${r?`a lazy entry`:e} does not take within()`);let{scalars:s}=n[t][`~`].state;for(let e of Object.keys(this.held))Object.hasOwn(s,e)||o(`confine names "${e}", which is not a scalar field`);(a.confine??={})[t]=this.held,(a.brings??={}).confines=i}};function within(e){return new Within(e)}export{within as t};
|
|
2
|
+
//# sourceMappingURL=confine-BGGv2du0.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"confine-
|
|
1
|
+
{"version":3,"file":"confine-BGGv2du0.mjs","names":[],"sources":["../src/extensions/confine.ts"],"sourcesContent":["/**\n * `confine: within(where)`: what every row of a set a statement computes\n * over a whole table holds. The word brings what admits and binds it, so a\n * rule that confines nothing carries none of it.\n */\nimport type { PreparedSelector } from \"@query-engine/raptor3/shared/query\";\nimport type { RowDomain } from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AdmittedLayer, Confines } from \"./admission\";\nimport type { ConfineWord, HeldOperand, IsHeld } from \"./contract\";\nimport { given } from \"./entries\";\nimport { Held } from \"./judge-words\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport type { Site } from \"./rule-words\";\n\n/**\n * What an `excluded` layer states its own whole-table sets of a model hold,\n * for one prepared domain: inside its own predicates a layer reads nothing\n * of itself, but a set the statement computes over a whole table (a shared\n * body, a reaching set) still holds only what it bounds. `undefined` where\n * none states one.\n */\nfunction bound(domain: PreparedDomain) {\n const bounds = new Map<string, PreparedSelector | null>();\n return (\n model: AnyModel,\n excluded: readonly number[]\n ): PreparedSelector | undefined => {\n const name = model[\"~\"].names.ts!;\n const inputs = domain.rows.confine?.get(name);\n if (inputs === undefined) return undefined;\n // Every excluded layer's: each only narrows, and one left out would let\n // another's widen what it bounds.\n return (\n memo(bounds, `${name} ${excluded}`, () =>\n domain.conjunction(\n model,\n excluded.map(\n (layer) => [layer, [inputs[layer]].filter(given)] as const\n )\n )\n ) ?? undefined\n );\n };\n}\n\nconst CONFINES: Confines = {\n admit: ({ admit }, written, references) =>\n Object.fromEntries(\n Object.entries(written).map(([name, where]) => [\n name,\n admit(name, `${name}.confine`, where, references),\n ])\n ),\n bind(layers: readonly AdmittedLayer[]): Partial<RowDomain> {\n const confine = new Map<string, Input[]>();\n for (const [layer, member] of layers.entries())\n for (const [model, where] of Object.entries(member.confine ?? {}))\n memo(confine, model, () => [])[layer] = where;\n return { confine, bound };\n },\n};\n\n/** `within(where)`'s value: what a model's whole-table sets hold. */\nclass Within extends Held<object> {\n join({ key, model, schema, lazy, layer, refuse }: Site): void {\n // An entry given lazily is admitted after its layer's confinements.\n if (key !== \"confine\" || lazy)\n refuse(`${lazy ? \"a lazy entry\" : key} does not take within()`);\n // The model's own columns: a confinement reads no relation, so lowering\n // it never builds another set it would confine in turn.\n const { scalars } = schema[model]![\"~\"].state;\n for (const field of Object.keys(this.held))\n if (!Object.hasOwn(scalars, field))\n refuse(`confine names \"${field}\", which is not a scalar field`);\n (layer!.confine ??= {})[model] = this.held;\n (layer!.brings ??= {}).confines = CONFINES;\n }\n}\n\n/**\n * Every row of a set computed over the model's whole table holds `where`, a\n * filter of the model's own columns: `confine: within(where)`.\n */\nexport function within<W>(\n where: HeldOperand<W>\n): IsHeld<W> extends true ? ConfineWord<never> : ConfineWord<W>;\nexport function within(where: object): unknown {\n return new Within(where);\n}\n"],"mappings":"yIAuBA,SAAS,MAAM,EAAwB,CACrC,IAAM,EAAS,IAAI,IACnB,OACE,EACA,IACiC,CACjC,IAAM,EAAO,EA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i}from"./error-mapping-B1-IWkCQ.mjs";import{a,n as o,t as s,x as c,y as l}from"./base-z-cH5ZBI.mjs";import{c as u,d,l as f,o as p,p as m,s as h,u as g,y as _}from"./validation--qS7OPmg.mjs";import{n as v,t as y}from"./transaction-BNomMtme.mjs";import{s as b,t as x}from"./normalized-result-B8pifWS0.mjs";import{r as S,t as C}from"./transaction-operation-CVVJxQ19.mjs";import{r as w}from"./routed-operations-wytpbYKv.mjs";function createFailureError(e,t,n){if(e.kind===`foreignKey`)return new i(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new f(e.message,e.relation??``);return e.raceable&&(t.meta.raceable=!0),t}if(e.kind===`notFound`)return new g(t,n);if(e.kind===`forbidden`)return new p(t,n,e.reason===void 0?void 0:{reason:e.reason});let r=new v(e.message,{meta:{model:t,operation:n}});return e.raceable&&(r.meta.raceable=!0),r}async function attributeOperationBatchError(e,t,n,i=[]){if(!(e instanceof u))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.queryIndex===a);return n?createFailureError(n.failure,n.model,n.operation):e}if(t.length>0&&r(i,n.dialect,new Set(t.map(e=>e.queryIndex))))return e;for(let e of t){let t=(await n._execute(e.probe,i[e.queryIndex]?.context)).rows.length>0;if(e.premise===`exists`?!t:t)return createFailureError(e.failure,e.model,e.operation)}let[s]=t;return s?t.every(e=>sameAttribution(e,s))?createFailureError(s.failure,s.model,s.operation):e:new f(h,``,{code:o.NESTED_WRITE_ASSERTION_FAILED,cause:e})}function sameAttribution(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.reason===t.failure.reason&&e.failure.raceable===t.failure.raceable}function executeArrayTransaction(e,t,n,r){let i,a;try{let t=e.length;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>4294967295)throw new y;let n=Array(t);for(let r=0;r<t;r+=1)n[r]=e[r];i=n}catch(e){a=e}let run=e=>{if(i===void 0)throw a;if(assertOwnedOperations(i,t),i.length===0)return Promise.resolve(i);if(e===void 0)for(let e of[`input`,`plan`])for(let t of i)S(t).prepareAdmission(t,e);return executeMembers(i,t,n,r,e)},o=t.extensionChain?.observation;if(o===void 0)return finishArrayResults(i,t,run);let s={};return finishArrayResults(i,t,()=>o.run({kind:`batch`,operation:`$transaction([...])`,context:r,certainty:()=>s.certainty},()=>run(s)))}function finishArrayResults(e,t,n){let r=t.extensionChain;if(r?.fields===void 0&&r?.watch===void 0)return n();let i=[...e??[]];return n().then(async e=>{let t=[];for(let[n,r]of i.entries()){let i=S(r);try{i.finishResult&&(e[n]=await i.finishResult(r,e[n]))}catch(e){t.push(e)}}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Several array members failed after commit.`,{cause:t[0]});return e})}function executeMembers(e,t,n,r,i){let{driver:a}=t,o=!a.supportsTransactions&&a.supportsBatch;o||assertAtomicArraySupport(a);let s=t.extensionChain,c=s?.coordination;return c&&(s?.observation?o||c.admit:c.intercepts?.(e))?executeSlots(e,t,n,r,i,c,o):o?sendNativeBatch(e,a,n,r):sendTransaction(e,t,n,r,i)}async function executeSlots(e,t,n,r,i,a,o){let{driver:s}=t,c=scopeOf(t,i??{}),l=e.map(e=>({operation:e,owner:S(e),child:createArrayDeferred()})),u=await t.extensionChain?.observation?.members(l.map(e=>[{...e.owner.unit(e.operation),certainty:()=>e.certainty},()=>e.child.promise.then(nothing,nothing).then(()=>memberValue(e))]));try{for(let e of l)e.owner.reserveWith(e.operation,s);for(let e of[`input`,`plan`])for(let t of l)await t.owner.observeBatchPhase(t.operation,s,()=>t.owner.prepareAdmission(t.operation,e))}catch(e){for(let t of l)t.child.reject(e);throw e}let d=await a.admit?.(l,c);if(d!==void 0)throw combineArrayFailures(d[0],d.slice(1));let f;try{f=await(o?sendNativeBatch(e,s,n,r,l,c,i):sendTransaction(e,t,n,r,i,l,c))}catch(e){for(let t of l)t.child.reject(e);throw e}return await u?.done,f}function sendTransaction(e,t,n,r,i,a,o){let s=e,body=async t=>{for(let n=0;n<e.length;n+=1){let r=e[n],i=a?.[n];if(i===void 0){s[n]=await S(r).executeWith(r,t);continue}i.owner.executeCore(r,t,i.notifications).then(i.child.resolve,i.child.reject);try{s[n]=await memberValue(i)}catch(e){await settleSlots(a.slice(n+1),[e])}}return s};return transact(t,n,r,body,o,i)}async function sendNativeBatch(e,t,n,r,i,a,o){if(i===void 0)for(let n of e)S(n).reserveWith(n,t);let s,c=[],publish=async e=>{if(!s){s=e,o&&(o.certainty=e);for(let t of i){t.certainty=e;try{await t.notifications?.[e===`committed`?`committed`:`mayHaveCommitted`]()}catch(e){c.push(e)}}try{await a?.outcomes?.publish(e)}catch(e){c.push(e)}}},close=async(e,t)=>{if(i===void 0)return e;t&&await publish(`may-have-committed`),await settleSlots(i,[s?markCommitCertainty(e,s):e],c)},l,u,d;try{({queries:l,guards:u,parsers:d}=await prepareNativeBatch(e,t))}catch(e){throw await close(e)}let f;try{f=await executeNativeBatch(t,l,u,n,r,i&&t.supportsOrderedCommittedSegments?()=>publish(`committed`):void 0),i&&await publish(`committed`),assertNativeBatchResults(t,f,l.length)}catch(e){throw await close(e,!0)}let p=e;for(let e=0;e<d.length;e+=1){let t=i?.[e];if(t===void 0)p[e]=await d[e](f);else try{t.child.resolve(await d[e](f))}catch(e){t.child.reject(markCommitCertainty(e,`committed`))}}return i&&await settleSlots(i,[],c.map(e=>markCommitCertainty(e,`committed`)),p),p}const nothing=()=>void 0;function memberValue(e){return e.query??e.child.promise}async function settleSlots(e,t,n=[],r=[]){for(let n of e)n.child.reject(t[0]);for(let[n,i]of(await Promise.allSettled(e.map(memberValue))).entries())i.status===`fulfilled`?r[n]=i.value:t.push(i.reason);if(t.push(...n),t.length>0)throw combineArrayFailures(t[0],t.slice(1))}function combineArrayFailures(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and operation post-work both failed.`,{cause:e})}function markCommitCertainty(e,t){return a(e)?n(e,t):e}function createArrayDeferred(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(nothing),{promise:n,resolve:e,reject:t}}async function prepareNativeBatch(e,t){let n=[],r=[],i=[];for(let a of e){let e=S(a),o=await e.observeBatchPhase(a,t,async()=>{let n=e.prepare(a,t);return n?{prepared:n}:{preparedBatch:await e.prepareBatch(a)}}),s=n.length;if(o.prepared){n.push(o.prepared),i.push(n=>e.observeBatchPhase(a,t,()=>{let r=n[s];if(!r)throw arrayError(t,`omitted the result for operation "${e.operation(a)}"`,{operation:e.operation(a)});return e.parseResult(a,r)}));continue}let{preparedBatch:c}=o;if(!c)throw unbatchableArrayError(t);let l=c.queries.length;for(let e of c.queries)n.push(e);for(let e of c.guards??[])r.push({...e,queryIndex:s+e.queryIndex});i.push(n=>e.observeBatchPhase(a,t,()=>c.parseResult(n.slice(s,s+l))))}return{queries:n,guards:r,parsers:i}}async function executeNativeBatch(e,t,n,r,i,a){try{return await e._executeBatch(t,r,i,a)}catch(r){throw await attributeOperationBatchError(r,n,e,t)}}function assertNativeBatchResults(e,t,n){x(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function assertAtomicArraySupport(e){if(!(e.supportsTransactions||e.supportsBatch))throw arrayError(e,`supports neither transactions nor atomic batch execution`)}function unbatchableArrayError(e){return arrayError(e,`does not support callback transactions and this transaction contains operations that cannot be batched atomically`)}function arrayError(e,t,n={method:`$transaction([...])`}){return new v(`Driver "${e.driverName}" ${t}.`,{meta:{driver:e.driverName,...n}})}function assertOwnedOperations(e,t){for(let n of e){if(typeof n!=`object`||!n)throw new y;let e=C(n);if(e===void 0)throw new y;if(e.clientId(n)!==t.clientId)throw d.clientMismatch(e.model(n),e.operation(n));if(e.scopeId(n)!==t.scopeId)throw d.scopeMismatch(e.model(n),e.operation(n))}}const T=Symbol(`viborm.call`),E=Symbol(`viborm.scope`),D=Symbol(`viborm.attempt`),isCall=e=>typeof e==`object`&&!!e,isScope=e=>typeof e==`object`&&!!e&&`engine`in e;function callOf(e){let t=Reflect.get(e,T);return isCall(t)?t:void 0}function attemptOf(e){return Reflect.get(e,D)}function scopeOf$1(e){let t=Reflect.get(e,E);return isScope(t)?t:void 0}e(scopeOf$1,`scopeOf`);function engineOf(e){return callOf(e)?.of?.engine??scopeOf$1(e)?.engine}const O=`called run() after its second moment returned`;function executePreparedQuery(e,t,n,r,i,a,o){return e!==void 0||o?r||o?executeRegisteredQuery(e,t,n,r,i,a,o,runArounds):runArounds(e,t,e=>n(void 0,e),a?.readCommitCertainty,a?.reportAdmissionFailure):n()}function executeRegisteredQuery(e,t,n,r,i,a,o,s){let c=o?[o]:e?.call?.told,l=c?.[0]?.tell?.(c,i),u=!1,d,notified=e=>async()=>{u=!0,i||(d=e),await l?.(e)},f={committed:notified(`committed`),mayHaveCommitted:notified(`may-have-committed`)},executeChild=async e=>{let t=await n(f,e);return r&&!u&&await f.committed(),t};return s&&e&&t?.length?s(e,t,executeChild,()=>d??a?.readCommitCertainty?.(),a?.reportAdmissionFailure):executeChild()}function runArounds(e,t,n,r,i){let at=(a,o)=>{let s=t?.[a];return s===void 0?n(o):runAround(e,s,e=>at(a+1,e??o),r,i,()=>n(o))};return at(0)}async function runAround(e,t,n,r,i,a){let{extension:o}=t,s=e.mode===`direct`,c=s&&e.kind===`model`&&w(e.operation),l=c,u,d,refuse=t=>(d===void 0&&(d=aroundError(o,e,t),i?.(d)),d),f={open:!0,failed:!1,done:!1,direct:s,routable:c,certainty:r,start(e){if(!f.open)throw refuse(`called run() more than once`);if(f.done)throw refuse(O);return f.open=!1,f.failed=!1,u=(async()=>n(e))(),u.then(void 0,()=>{f.failed=!0}),u}},p=Object.defineProperties(()=>{if(!f.done)return f.start();if(!l)throw refuse(O);return l=!1,(async()=>a())()},{input:{get:()=>e.input},mode:{value:e.mode},[T]:{value:e.kind===`model`?e.call:void 0},[D]:{value:f}}),m;try{m={value:await t.handler(e,p)}}catch(e){m={reason:e}}f.done=!0;let h=`reason`in m&&(d===void 0||m.reason!==d)?aroundFailure(o,e,m.reason,r?.()):void 0;if(u===void 0){if(h!==void 0)throw h;if(e.mode===`array`||e.kind!==`model`||!w(e.operation))throw aroundError(o,e,`returned without run()`)}else h!==void 0&&!f.failed&&i?.(h),await u;if(`value`in m&&d===void 0)return m.value;throw d??h}function aroundFailure(e,t,n,r){return c(n)?n:aroundError(e,t,`failed`,l(n),r)}function aroundError(e,t,n,r,i){return new m(`Extension "${e}" around() for ${t.kind===`model`?`${t.model}.${t.operation}`:t.operation} ${n}.`,{...r&&{cause:r},meta:{method:`around`,model:t.model,operation:t.operation,...i===void 0?{}:{commitCertainty:i}}})}var TransactionWriteOutcomes=class{staged=[];publish(e){return publishWriteOutcomes(this.staged.filter(e=>e.ok),{certainty:e})}async end({parent:e,root:t},r,i){if(!i)return e?collect(e).staged.push(...this.staged.filter(e=>e.ok)):await this.publish(`committed`),r;let{certainty:o}=t;if(e||o===void 0)throw r;let s=a(r)?n(r,o):r;try{await this.publish(o)}catch(e){throw _(s,e)}throw s}};function collect(e){return e.outcomes??=new TransactionWriteOutcomes,e.outcomes}function tell(e,t){if(t===void 0)return t=>publishWriteOutcomes(e,{certainty:t});for(let n of e)(n.collect?.(t)??t.outcomes)?.staged.push(n);return async()=>{for(let t of e)t.ok=!0}}async function publishWriteOutcomes(e,t){let n;for(let{extension:r,listener:i}of e)try{await i(t)}catch(e){n??=e instanceof s?e:new m(`Extension "${r}" settled() failed (${t.certainty}).`,{cause:l(e),meta:{method:`settled`,commitCertainty:t.certainty}})}if(n)throw n}function interceptsArray(e){return e.some(e=>{let{handlers:t,registration:n}=S(e).around(e);return t?.length||n})}async function stageArray(e,t){for(let n of e){let{write:e,registration:r}=n.owner.around(n.operation);if(r===void 0)continue;let child=e=>(n.notifications=e,n.child.promise),i=executeRegisteredQuery(void 0,void 0,child,e,t,void 0,r);n.query=i,i.catch(ignore)}}const ignore=()=>void 0;function admitArray(e,t,n){let r=e.map(e=>e.owner.around(e.operation));return admitArrayQueries(e,(i,a,o)=>{let{context:s,handlers:c,write:l,registration:u}=r[e.indexOf(i)];return c?.length||u?n(s,c,a,l,t,o,u):a()})}async function admitArrayQueries(e,t){let n,r=e.length,i=createArrayDeferred();r===0&&i.resolve();for(let a of e){let reportAdmissionFailure=e=>{let t=a.admissionFailures??=[];t.includes(e)||t.push(e),n??={failure:e},i.reject(e)},e;try{e=t(a,e=>(a.notifications=e,--r,r===0&&i.resolve(),a.child.promise),{reportAdmissionFailure,readCommitCertainty:()=>a.certainty})}catch(t){reportAdmissionFailure(t),e=Promise.reject(t)}a.query=e,e.catch(reportAdmissionFailure)}try{if(await i.promise,await Promise.resolve(),n)throw n.failure;return}catch(t){for(let n of e)n.child.reject(t);await Promise.allSettled(e.map(memberValue));let n=[];for(let t of e)for(let e of t.admissionFailures??[])n.includes(e)||n.push(e);return n}}const k={rank:-1},A={rank:1,executePreparedQuery:executeRegisteredQuery,intercepts:interceptsArray,admit:stageArray},j={rank:2,executePreparedQuery,intercepts:interceptsArray,admit:(e,t)=>admitArray(e,t,executePreparedQuery)};function coordinate(e,t,n){n&&(e.collect=n),(e.coordination===void 0||t.rank>e.coordination.rank)&&(e.coordination=t)}function transact(e,n,r,i,a,o=a?.root??{}){let s=e.extensionChain,c=e.transaction,l,end=e=>t=>{if(e||c||(o.certainty=`committed`),!l?.outcomes){if(e)throw t;return t}let n=l.outcomes.end(l,t,e);return n.catch(()=>void 0),n},u=e.driver.withTransaction(t=>(l=a??scopeOf(e,o),i(t,l)),n,c||!(s?.coordination||s?.methods)?r:t(r,{readyToCommit:()=>{o.certainty=`may-have-committed`},committed:()=>{o.certainty=`committed`}}));return c?b(u,end()):u.then(end(),end(!0))}function scopeOf(e,t){let n={parent:e.transaction,root:t};return e.extensionChain?.collect?.(n),n}export{transact as a,tell as c,attemptOf as d,callOf as f,createFailureError as g,executeArrayTransaction as h,coordinate as i,T as l,scopeOf$1 as m,j as n,collect as o,engineOf as p,k as r,publishWriteOutcomes as s,A as t,E as u};
|
|
2
|
-
//# sourceMappingURL=coordination-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{N as t,i as n,t as r,y as i}from"./error-mapping-DIRlrmDK.mjs";import{a,n as o,t as s,x as c,y as l}from"./base-z-cH5ZBI.mjs";import{c as u,d,l as f,o as p,p as m,s as h,u as g,y as _}from"./validation--qS7OPmg.mjs";import{n as v,t as y}from"./transaction-BNomMtme.mjs";import{s as b,t as x}from"./normalized-result-B8pifWS0.mjs";import{r as S,t as C}from"./transaction-operation-CVVJxQ19.mjs";import{r as w}from"./routed-operations-wytpbYKv.mjs";function createFailureError(e,t,n){if(e.kind===`foreignKey`)return new i(e.message,{meta:{model:t,operation:n}});if(e.kind===`nestedWrite`){let t=new f(e.message,e.relation??``);return e.raceable&&(t.meta.raceable=!0),t}if(e.kind===`notFound`)return new g(t,n);if(e.kind===`forbidden`)return new p(t,n,e.reason===void 0?void 0:{reason:e.reason});let r=new v(e.message,{meta:{model:t,operation:n}});return e.raceable&&(r.meta.raceable=!0),r}async function attributeOperationBatchError(e,t,n,i=[]){if(!(e instanceof u))return e;let a=e.meta.statementIndex;if(typeof a==`number`){let n=t.find(e=>e.queryIndex===a);return n?createFailureError(n.failure,n.model,n.operation):e}if(t.length>0&&r(i,n.dialect,new Set(t.map(e=>e.queryIndex))))return e;for(let e of t){let t=(await n._execute(e.probe,i[e.queryIndex]?.context)).rows.length>0;if(e.premise===`exists`?!t:t)return createFailureError(e.failure,e.model,e.operation)}let[s]=t;return s?t.every(e=>sameAttribution(e,s))?createFailureError(s.failure,s.model,s.operation):e:new f(h,``,{code:o.NESTED_WRITE_ASSERTION_FAILED,cause:e})}function sameAttribution(e,t){return e.model===t.model&&e.operation===t.operation&&e.failure.kind===t.failure.kind&&e.failure.message===t.failure.message&&e.failure.relation===t.failure.relation&&e.failure.reason===t.failure.reason&&e.failure.raceable===t.failure.raceable}function executeArrayTransaction(e,t,n,r){let i,a;try{let t=e.length;if(typeof t!=`number`||!Number.isInteger(t)||t<0||t>4294967295)throw new y;let n=Array(t);for(let r=0;r<t;r+=1)n[r]=e[r];i=n}catch(e){a=e}let run=e=>{if(i===void 0)throw a;if(assertOwnedOperations(i,t),i.length===0)return Promise.resolve(i);if(e===void 0)for(let e of[`input`,`plan`])for(let t of i)S(t).prepareAdmission(t,e);return executeMembers(i,t,n,r,e)},o=t.extensionChain?.observation;if(o===void 0)return finishArrayResults(i,t,run);let s={};return finishArrayResults(i,t,()=>o.run({kind:`batch`,operation:`$transaction([...])`,context:r,certainty:()=>s.certainty},()=>run(s)))}function finishArrayResults(e,t,n){let r=t.extensionChain;if(r?.fields===void 0&&r?.watch===void 0)return n();let i=[...e??[]];return n().then(async e=>{let t=[];for(let[n,r]of i.entries()){let i=S(r);try{i.finishResult&&(e[n]=await i.finishResult(r,e[n]))}catch(e){t.push(e)}}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Several array members failed after commit.`,{cause:t[0]});return e})}function executeMembers(e,t,n,r,i){let{driver:a}=t,o=!a.supportsTransactions&&a.supportsBatch;o||assertAtomicArraySupport(a);let s=t.extensionChain,c=s?.coordination;return c&&(s?.observation?o||c.admit:c.intercepts?.(e))?executeSlots(e,t,n,r,i,c,o):o?sendNativeBatch(e,a,n,r):sendTransaction(e,t,n,r,i)}async function executeSlots(e,t,n,r,i,a,o){let{driver:s}=t,c=scopeOf(t,i??{}),l=e.map(e=>({operation:e,owner:S(e),child:createArrayDeferred()})),u=await t.extensionChain?.observation?.members(l.map(e=>[{...e.owner.unit(e.operation),certainty:()=>e.certainty},()=>e.child.promise.then(nothing,nothing).then(()=>memberValue(e))]));try{for(let e of l)e.owner.reserveWith(e.operation,s);for(let e of[`input`,`plan`])for(let t of l)await t.owner.observeBatchPhase(t.operation,s,()=>t.owner.prepareAdmission(t.operation,e))}catch(e){for(let t of l)t.child.reject(e);throw e}let d=await a.admit?.(l,c);if(d!==void 0)throw combineArrayFailures(d[0],d.slice(1));let f;try{f=await(o?sendNativeBatch(e,s,n,r,l,c,i):sendTransaction(e,t,n,r,i,l,c))}catch(e){for(let t of l)t.child.reject(e);throw e}return await u?.done,f}function sendTransaction(e,t,n,r,i,a,o){let s=e,body=async t=>{for(let n=0;n<e.length;n+=1){let r=e[n],i=a?.[n];if(i===void 0){s[n]=await S(r).executeWith(r,t);continue}i.owner.executeCore(r,t,i.notifications).then(i.child.resolve,i.child.reject);try{s[n]=await memberValue(i)}catch(e){await settleSlots(a.slice(n+1),[e])}}return s};return transact(t,n,r,body,o,i)}async function sendNativeBatch(e,t,n,r,i,a,o){if(i===void 0)for(let n of e)S(n).reserveWith(n,t);let s,c=[],publish=async e=>{if(!s){s=e,o&&(o.certainty=e);for(let t of i){t.certainty=e;try{await t.notifications?.[e===`committed`?`committed`:`mayHaveCommitted`]()}catch(e){c.push(e)}}try{await a?.outcomes?.publish(e)}catch(e){c.push(e)}}},close=async(e,t)=>{if(i===void 0)return e;t&&await publish(`may-have-committed`),await settleSlots(i,[s?markCommitCertainty(e,s):e],c)},l,u,d;try{({queries:l,guards:u,parsers:d}=await prepareNativeBatch(e,t))}catch(e){throw await close(e)}let f;try{f=await executeNativeBatch(t,l,u,n,r,i&&t.supportsOrderedCommittedSegments?()=>publish(`committed`):void 0),i&&await publish(`committed`),assertNativeBatchResults(t,f,l.length)}catch(e){throw await close(e,!0)}let p=e;for(let e=0;e<d.length;e+=1){let t=i?.[e];if(t===void 0)p[e]=await d[e](f);else try{t.child.resolve(await d[e](f))}catch(e){t.child.reject(markCommitCertainty(e,`committed`))}}return i&&await settleSlots(i,[],c.map(e=>markCommitCertainty(e,`committed`)),p),p}const nothing=()=>void 0;function memberValue(e){return e.query??e.child.promise}async function settleSlots(e,t,n=[],r=[]){for(let n of e)n.child.reject(t[0]);for(let[n,i]of(await Promise.allSettled(e.map(memberValue))).entries())i.status===`fulfilled`?r[n]=i.value:t.push(i.reason);if(t.push(...n),t.length>0)throw combineArrayFailures(t[0],t.slice(1))}function combineArrayFailures(e,t){let n=t.filter(t=>t!==e);return n.length===0?e:AggregateError([e,...n],`Array transaction and operation post-work both failed.`,{cause:e})}function markCommitCertainty(e,t){return a(e)?n(e,t):e}function createArrayDeferred(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.catch(nothing),{promise:n,resolve:e,reject:t}}async function prepareNativeBatch(e,t){let n=[],r=[],i=[];for(let a of e){let e=S(a),o=await e.observeBatchPhase(a,t,async()=>{let n=e.prepare(a,t);return n?{prepared:n}:{preparedBatch:await e.prepareBatch(a)}}),s=n.length;if(o.prepared){n.push(o.prepared),i.push(n=>e.observeBatchPhase(a,t,()=>{let r=n[s];if(!r)throw arrayError(t,`omitted the result for operation "${e.operation(a)}"`,{operation:e.operation(a)});return e.parseResult(a,r)}));continue}let{preparedBatch:c}=o;if(!c)throw unbatchableArrayError(t);let l=c.queries.length;for(let e of c.queries)n.push(e);for(let e of c.guards??[])r.push({...e,queryIndex:s+e.queryIndex});i.push(n=>e.observeBatchPhase(a,t,()=>c.parseResult(n.slice(s,s+l))))}return{queries:n,guards:r,parsers:i}}async function executeNativeBatch(e,t,n,r,i,a){try{return await e._executeBatch(t,r,i,a)}catch(r){throw await attributeOperationBatchError(r,n,e,t)}}function assertNativeBatchResults(e,t,n){x(t,n,{provider:e.driverName,operation:`$transaction([...])`})}function assertAtomicArraySupport(e){if(!(e.supportsTransactions||e.supportsBatch))throw arrayError(e,`supports neither transactions nor atomic batch execution`)}function unbatchableArrayError(e){return arrayError(e,`does not support callback transactions and this transaction contains operations that cannot be batched atomically`)}function arrayError(e,t,n={method:`$transaction([...])`}){return new v(`Driver "${e.driverName}" ${t}.`,{meta:{driver:e.driverName,...n}})}function assertOwnedOperations(e,t){for(let n of e){if(typeof n!=`object`||!n)throw new y;let e=C(n);if(e===void 0)throw new y;if(e.clientId(n)!==t.clientId)throw d.clientMismatch(e.model(n),e.operation(n));if(e.scopeId(n)!==t.scopeId)throw d.scopeMismatch(e.model(n),e.operation(n))}}const T=Symbol(`viborm.call`),E=Symbol(`viborm.scope`),D=Symbol(`viborm.attempt`),isCall=e=>typeof e==`object`&&!!e,isScope=e=>typeof e==`object`&&!!e&&`engine`in e;function callOf(e){let t=Reflect.get(e,T);return isCall(t)?t:void 0}function attemptOf(e){return Reflect.get(e,D)}function scopeOf$1(e){let t=Reflect.get(e,E);return isScope(t)?t:void 0}e(scopeOf$1,`scopeOf`);function engineOf(e){return callOf(e)?.of?.engine??scopeOf$1(e)?.engine}const O=`called run() after its second moment returned`;function executePreparedQuery(e,t,n,r,i,a,o){return e!==void 0||o?r||o?executeRegisteredQuery(e,t,n,r,i,a,o,runArounds):runArounds(e,t,e=>n(void 0,e),a?.readCommitCertainty,a?.reportAdmissionFailure):n()}function executeRegisteredQuery(e,t,n,r,i,a,o,s){let c=o?[o]:e?.call?.told,l=c?.[0]?.tell?.(c,i),u=!1,d,notified=e=>async()=>{u=!0,i||(d=e),await l?.(e)},f={committed:notified(`committed`),mayHaveCommitted:notified(`may-have-committed`)},executeChild=async e=>{let t=await n(f,e);return r&&!u&&await f.committed(),t};return s&&e&&t?.length?s(e,t,executeChild,()=>d??a?.readCommitCertainty?.(),a?.reportAdmissionFailure):executeChild()}function runArounds(e,t,n,r,i){let at=(a,o)=>{let s=t?.[a];return s===void 0?n(o):runAround(e,s,e=>at(a+1,e??o),r,i,()=>n(o))};return at(0)}async function runAround(e,t,n,r,i,a){let{extension:o}=t,s=e.mode===`direct`,c=s&&e.kind===`model`&&w(e.operation),l=c,u,d,refuse=t=>(d===void 0&&(d=aroundError(o,e,t),i?.(d)),d),f={open:!0,failed:!1,done:!1,direct:s,routable:c,certainty:r,start(e){if(!f.open)throw refuse(`called run() more than once`);if(f.done)throw refuse(O);return f.open=!1,f.failed=!1,u=(async()=>n(e))(),u.then(void 0,()=>{f.failed=!0}),u}},p=Object.defineProperties(()=>{if(!f.done)return f.start();if(!l)throw refuse(O);return l=!1,(async()=>a())()},{input:{get:()=>e.input},mode:{value:e.mode},[T]:{value:e.kind===`model`?e.call:void 0},[D]:{value:f}}),m;try{m={value:await t.handler(e,p)}}catch(e){m={reason:e}}f.done=!0;let h=`reason`in m&&(d===void 0||m.reason!==d)?aroundFailure(o,e,m.reason,r?.()):void 0;if(u===void 0){if(h!==void 0)throw h;if(e.mode===`array`||e.kind!==`model`||!w(e.operation))throw aroundError(o,e,`returned without run()`)}else h!==void 0&&!f.failed&&i?.(h),await u;if(`value`in m&&d===void 0)return m.value;throw d??h}function aroundFailure(e,t,n,r){return c(n)?n:aroundError(e,t,`failed`,l(n),r)}function aroundError(e,t,n,r,i){return new m(`Extension "${e}" around() for ${t.kind===`model`?`${t.model}.${t.operation}`:t.operation} ${n}.`,{...r&&{cause:r},meta:{method:`around`,model:t.model,operation:t.operation,...i===void 0?{}:{commitCertainty:i}}})}var TransactionWriteOutcomes=class{staged=[];publish(e){return publishWriteOutcomes(this.staged.filter(e=>e.ok),{certainty:e})}async end({parent:e,root:t},r,i){if(!i)return e?collect(e).staged.push(...this.staged.filter(e=>e.ok)):await this.publish(`committed`),r;let{certainty:o}=t;if(e||o===void 0)throw r;let s=a(r)?n(r,o):r;try{await this.publish(o)}catch(e){throw _(s,e)}throw s}};function collect(e){return e.outcomes??=new TransactionWriteOutcomes,e.outcomes}function tell(e,t){if(t===void 0)return t=>publishWriteOutcomes(e,{certainty:t});for(let n of e)(n.collect?.(t)??t.outcomes)?.staged.push(n);return async()=>{for(let t of e)t.ok=!0}}async function publishWriteOutcomes(e,t){let n;for(let{extension:r,listener:i}of e)try{await i(t)}catch(e){n??=e instanceof s?e:new m(`Extension "${r}" settled() failed (${t.certainty}).`,{cause:l(e),meta:{method:`settled`,commitCertainty:t.certainty}})}if(n)throw n}function interceptsArray(e){return e.some(e=>{let{handlers:t,registration:n}=S(e).around(e);return t?.length||n})}async function stageArray(e,t){for(let n of e){let{write:e,registration:r}=n.owner.around(n.operation);if(r===void 0)continue;let child=e=>(n.notifications=e,n.child.promise),i=executeRegisteredQuery(void 0,void 0,child,e,t,void 0,r);n.query=i,i.catch(ignore)}}const ignore=()=>void 0;function admitArray(e,t,n){let r=e.map(e=>e.owner.around(e.operation));return admitArrayQueries(e,(i,a,o)=>{let{context:s,handlers:c,write:l,registration:u}=r[e.indexOf(i)];return c?.length||u?n(s,c,a,l,t,o,u):a()})}async function admitArrayQueries(e,t){let n,r=e.length,i=createArrayDeferred();r===0&&i.resolve();for(let a of e){let reportAdmissionFailure=e=>{let t=a.admissionFailures??=[];t.includes(e)||t.push(e),n??={failure:e},i.reject(e)},e;try{e=t(a,e=>(a.notifications=e,--r,r===0&&i.resolve(),a.child.promise),{reportAdmissionFailure,readCommitCertainty:()=>a.certainty})}catch(t){reportAdmissionFailure(t),e=Promise.reject(t)}a.query=e,e.catch(reportAdmissionFailure)}try{if(await i.promise,await Promise.resolve(),n)throw n.failure;return}catch(t){for(let n of e)n.child.reject(t);await Promise.allSettled(e.map(memberValue));let n=[];for(let t of e)for(let e of t.admissionFailures??[])n.includes(e)||n.push(e);return n}}const k={rank:-1},A={rank:1,executePreparedQuery:executeRegisteredQuery,intercepts:interceptsArray,admit:stageArray},j={rank:2,executePreparedQuery,intercepts:interceptsArray,admit:(e,t)=>admitArray(e,t,executePreparedQuery)};function coordinate(e,t,n){n&&(e.collect=n),(e.coordination===void 0||t.rank>e.coordination.rank)&&(e.coordination=t)}function transact(e,n,r,i,a,o=a?.root??{}){let s=e.extensionChain,c=e.transaction,l,end=e=>t=>{if(e||c||(o.certainty=`committed`),!l?.outcomes){if(e)throw t;return t}let n=l.outcomes.end(l,t,e);return n.catch(()=>void 0),n},u=e.driver.withTransaction(t=>(l=a??scopeOf(e,o),i(t,l)),n,c||!(s?.coordination||s?.methods)?r:t(r,{readyToCommit:()=>{o.certainty=`may-have-committed`},committed:()=>{o.certainty=`committed`}}));return c?b(u,end()):u.then(end(),end(!0))}function scopeOf(e,t){let n={parent:e.transaction,root:t};return e.extensionChain?.collect?.(n),n}export{transact as a,tell as c,attemptOf as d,callOf as f,createFailureError as g,executeArrayTransaction as h,coordinate as i,T as l,scopeOf$1 as m,j as n,collect as o,engineOf as p,k as r,publishWriteOutcomes as s,A as t,E as u};
|
|
2
|
+
//# sourceMappingURL=coordination-BY6Np3xV.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordination-6qZHx_kl.mjs","names":["error","candidate","batch","scopeOf","failure","failure"],"sources":["../src/query-engine/batch-error-attribution.ts","../src/client/array-transaction.ts","../src/extensions/origin.ts","../src/extensions/query.ts","../src/extensions/array-admission.ts","../src/extensions/coordination.ts"],"sourcesContent":["import { batchMayContainAssertionCollision } from \"@drivers/error-mapping\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n ForbiddenError,\n ForeignKeyError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n TransactionError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { PreparedBatchGuard, PreparedGuardFailure } from \"./types\";\n\n/**\n * Materialize a guard's declared {@link PreparedGuardFailure} as its typed\n * error — the ONE failure-to-error construction, which the engine's own\n * referential refusal reuses when it runs outside a package\n * (`Commands.restrictFailure`). A `notFound` failure rebuilds\n * its sentence from the model and verb, so the declared message is never\n * user-facing for that kind; the `raceable` mark is what lets the routed retry\n * re-plan and converge, so it survives every arm.\n */\nexport function createFailureError(\n failure: PreparedGuardFailure,\n model: string,\n operation: string\n): Error {\n if (failure.kind === \"foreignKey\") {\n return new ForeignKeyError(failure.message, { meta: { model, operation } });\n }\n if (failure.kind === \"nestedWrite\") {\n const error = new NestedWriteError(failure.message, failure.relation ?? \"\");\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n }\n if (failure.kind === \"notFound\") {\n return new NotFoundError(model, operation);\n }\n if (failure.kind === \"forbidden\") {\n return new ForbiddenError(\n model,\n operation,\n failure.reason === undefined ? undefined : { reason: failure.reason }\n );\n }\n const error = new TransactionError(failure.message, {\n meta: { model, operation },\n });\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n}\n\n/**\n * Attribute a native-batch assertion failure to the guard that raised it (P6\n * pure-leaf extraction, consumed by the client's shared-batch path): a\n * `NestedWriteAssertionError` carries the index of the offending statement when\n * the driver surfaces it, else each guard's probe is re-run to locate the\n * violated precondition. The attributed error reconstructs the guard's typed\n * failure with the correct model/operation.\n *\n * The re-probe runs AFTER the atomic batch rolled back, which makes it blind to\n * one whole class: a premise broken by a SIBLING statement inside the same batch\n * is restored by that rollback and probes clean, so no guard is blamed. When\n * every guard in the batch would raise the same failure for the same\n * model/operation, that blindness costs nothing — whichever fired, the error is\n * the same one — but only once it is established that a guard fired AT ALL.\n *\n * That last part is not free. A native batch is normalized against the JOINED\n * SQL, so one assertion statement anywhere arms the detector\n * (`src/drivers/error-mapping.ts`) for every statement in the batch: an ordinary\n * statement that raises the same provider signature — `n / 0` from a literal\n * `divide: 0` on Postgres, a malformed-JSON argument on MySQL/SQLite — arrives\n * as a `NestedWriteAssertionError` no guard caused. Blaming a guard for it\n * asserts something false about the database (a `NotFoundError`/P2025 for a row\n * that is still there, which Prisma callers branch on). So the reconstruction\n * runs only when NO ordinary statement in the batch could have produced the\n * signature — viborm built every statement, so it can tell — and the raw\n * driver-mapped error stands whenever the failure cannot be tied to a guard.\n * A batch carrying guards that DISAGREE about what went wrong likewise stays\n * un-attributable.\n */\nexport async function attributeOperationBatchError(\n error: unknown,\n guards: readonly PreparedBatchGuard[],\n driver: AnyDriver,\n statements: readonly {\n readonly sql: string;\n readonly context?: QueryExecutionContext;\n }[] = []\n): Promise<unknown> {\n if (!(error instanceof NestedWriteAssertionError)) return error;\n const statementIndex = error.meta.statementIndex;\n if (typeof statementIndex === \"number\") {\n const guard = guards.find(\n (candidate) => candidate.queryIndex === statementIndex\n );\n if (guard) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n return error;\n }\n if (\n guards.length > 0 &&\n batchMayContainAssertionCollision(\n statements,\n driver.dialect,\n new Set(guards.map((guard) => guard.queryIndex))\n )\n ) {\n // A failed premise after rollback does not identify which statement failed.\n return error;\n }\n for (const guard of guards) {\n const result = await driver._execute(\n guard.probe,\n statements[guard.queryIndex]?.context\n );\n const exists = result.rows.length > 0;\n if (guard.premise === \"exists\" ? !exists : exists) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n }\n const [candidate] = guards;\n if (candidate) {\n const attributable = guards.every((guard) =>\n sameAttribution(guard, candidate)\n );\n return attributable\n ? createFailureError(\n candidate.failure,\n candidate.model,\n candidate.operation\n )\n : error;\n }\n return new NestedWriteError(NESTED_WRITE_ASSERTION_FLOOR_MESSAGE, \"\", {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error,\n });\n}\n\n/**\n * Two guards that would produce the SAME error: same model, same operation, and\n * a failure identical in every field the reconstruction below reads.\n */\nfunction sameAttribution(\n guard: PreparedBatchGuard,\n other: PreparedBatchGuard\n): boolean {\n return (\n guard.model === other.model &&\n guard.operation === other.operation &&\n guard.failure.kind === other.failure.kind &&\n guard.failure.message === other.failure.message &&\n guard.failure.relation === other.failure.relation &&\n guard.failure.reason === other.failure.reason &&\n guard.failure.raceable === other.failure.raceable\n );\n}\n","/**\n * The one executor of `$transaction([...])`. Every application runs it: one\n * transaction on a transaction driver, one native batch on a batch driver.\n * A chain whose parts intercept calls admits the members through its\n * coordination's `admit` hook (`@extensions/array-admission`), read from\n * the chain's state, so an application without one carries none of it.\n */\n\nimport { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type {\n AnyDriver,\n BatchQuery,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { assertNormalizedBatchResults } from \"@drivers/normalized-result\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport {\n InvalidTransactionInputError,\n isVibORMError,\n PendingOperationError,\n TransactionError,\n} from \"@errors\";\nimport {\n type ArrayCertainty,\n type Coordination,\n scopeOf,\n transact,\n} from \"@extensions/coordination\";\nimport type {\n TransactionScope,\n WriteOutcome,\n WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport { attributeOperationBatchError } from \"@query-engine/batch-error-attribution\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport {\n readTransactionOperation,\n type TransactionOperationCapability,\n type TransactionOperationOwner,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport type { PreparedBatchGuard } from \"@query-engine/types\";\n\ntype ArrayOptions = TransactionOptions | BatchTransactionOptions | undefined;\n\n/** Each member's parser over the batch's results. */\ntype BatchParser = (batchResults: QueryResult<unknown>[]) => Promise<unknown>;\n\n/**\n * Execute one root or nested array transaction. Without an observer, every\n * member's request work (argument admission included) settles before any\n * provider effect; an observer runs it inside each member's unit instead.\n */\nexport function executeArrayTransaction(\n candidates: readonly unknown[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext\n): Promise<unknown[]> {\n let operations: unknown[] | undefined;\n let snapshotFailure: unknown;\n try {\n const length = candidates.length;\n if (\n typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xff_ff_ff_ff\n ) {\n throw new InvalidTransactionInputError();\n }\n const snapshot = new Array<unknown>(length);\n for (let index = 0; index < length; index += 1) {\n snapshot[index] = candidates[index];\n }\n operations = snapshot;\n } catch (error) {\n snapshotFailure = error;\n }\n const run = (batch?: ArrayCertainty): Promise<unknown[]> => {\n if (operations === undefined) throw snapshotFailure;\n assertOwnedOperations(operations, engine);\n if (operations.length === 0) return Promise.resolve(operations);\n if (batch === undefined)\n for (const phase of [\"input\", \"plan\"] as const)\n for (const operation of operations)\n transactionOperationOwner(operation).prepareAdmission(\n operation,\n phase\n );\n return executeMembers(operations, engine, options, context, batch);\n };\n const observation = engine.extensionChain?.observation;\n if (observation === undefined)\n return finishArrayResults(operations, engine, run);\n const batch: ArrayCertainty = {};\n return finishArrayResults(operations, engine, () =>\n observation.run(\n {\n kind: \"batch\",\n operation: \"$transaction([...])\",\n context,\n certainty: () => batch.certainty,\n },\n () => run(batch)\n )\n );\n}\n\n/**\n * Each member's value as its caller receives it: a chain that computes\n * result fields or watches writes finishes every member once the array has\n * settled.\n * The members are read before the run, which writes its values over them.\n */\nfunction finishArrayResults(\n operations: readonly unknown[] | undefined,\n engine: QueryEngine,\n run: () => Promise<unknown[]>\n): Promise<unknown[]> {\n const chain = engine.extensionChain;\n if (chain?.fields === undefined && chain?.watch === undefined) return run();\n const members = [...(operations ?? [])] as object[];\n return run().then(async (values) => {\n // One member at a time: a member's write hooks run in member order, and\n // one failing does not keep the next from running.\n const failures: unknown[] = [];\n for (const [index, operation] of members.entries()) {\n const owner = transactionOperationOwner(operation);\n try {\n if (owner.finishResult)\n values[index] = await owner.finishResult(operation, values[index]);\n } catch (failure) {\n failures.push(failure);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(\n failures,\n \"Several array members failed after commit.\",\n {\n cause: failures[0],\n }\n );\n return values;\n });\n}\n\n/**\n * The members sent as one transaction, or one native batch. On a chain that\n * may intercept them (its `admit` hook), or whose units observe a native\n * batch's members, each member gets a slot first: its unit entered, its\n * arguments admitted and its handlers started, all before anything is sent.\n */\nfunction executeMembers(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined\n): Promise<unknown[]> {\n const { driver } = engine;\n const native = !driver.supportsTransactions && driver.supportsBatch;\n if (!native) assertAtomicArraySupport(driver);\n const chain = engine.extensionChain;\n const coordination = chain?.coordination;\n // Observed members go through slots, but on a transaction driver only\n // where a part may intercept them; else each member's unit runs around\n // its own work, in order. Unobserved members, prepared already, only\n // where one is intercepted.\n return coordination &&\n (chain?.observation\n ? native || coordination.admit\n : coordination.intercepts?.(operations))\n ? executeSlots(\n operations,\n engine,\n options,\n context,\n batch,\n coordination,\n native\n )\n : native\n ? sendNativeBatch(operations, driver, options, context)\n : sendTransaction(operations, engine, options, context, batch);\n}\n\n/** One member of an observed or intercepted array. */\nexport interface ArraySlot {\n readonly operation: TransactionOperationCapability;\n readonly owner: TransactionOperationOwner<TransactionOperationCapability>;\n /** The core's result, which the member's handlers resume with. */\n readonly child: ArrayDeferred<unknown>;\n /** The member's handlers: its value as its caller receives it. */\n query?: Promise<unknown>;\n notifications?: WriteOutcomeNotifications;\n certainty?: WriteOutcome[\"certainty\"];\n admissionFailures?: unknown[];\n}\n\nasync function executeSlots(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n coordination: Coordination,\n native: boolean\n): Promise<unknown[]> {\n const { driver } = engine;\n // The array's scope, made before its members are admitted, which stage in it.\n const scope = scopeOf(engine, batch ?? {});\n const slots = operations.map(\n (operation): ArraySlot => ({\n operation,\n owner: transactionOperationOwner(operation),\n child: createArrayDeferred(),\n })\n );\n // Each member's unit starts before any member is prepared, and the array\n // waits until every unit reached its child: a handler that waits first\n // (for a tracer to load) does so before the array's work, which then runs\n // inside each member's unit, until its handlers settled.\n const units = await engine.extensionChain?.observation?.members(\n slots.map((slot) => [\n { ...slot.owner.unit(slot.operation), certainty: () => slot.certainty },\n () =>\n slot.child.promise.then(nothing, nothing).then(() => memberValue(slot)),\n ])\n );\n try {\n for (const slot of slots) slot.owner.reserveWith(slot.operation, driver);\n for (const phase of [\"input\", \"plan\"] as const)\n for (const slot of slots)\n await slot.owner.observeBatchPhase(slot.operation, driver, () =>\n slot.owner.prepareAdmission(slot.operation, phase)\n );\n } catch (error) {\n for (const slot of slots) slot.child.reject(error);\n throw error;\n }\n const failures = await coordination.admit?.(slots, scope);\n if (failures !== undefined)\n throw combineArrayFailures(failures[0], failures.slice(1));\n let values: unknown[];\n try {\n values = await (native\n ? sendNativeBatch(\n operations,\n driver,\n options,\n context,\n slots,\n scope,\n batch\n )\n : sendTransaction(\n operations,\n engine,\n options,\n context,\n batch,\n slots,\n scope\n ));\n } catch (failure) {\n // A transaction that failed before a member ran still lets that\n // member's handlers and unit end.\n for (const slot of slots) slot.child.reject(failure);\n throw failure;\n }\n // What a member's unit handler threw, once its child succeeded, fails the\n // array: the host contains nothing a handler does.\n await units?.done;\n return values;\n}\n\n/** The members in order inside one transaction, or a savepoint. */\nfunction sendTransaction(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n slots?: ArraySlot[],\n scope?: TransactionScope\n): Promise<unknown[]> {\n const results: unknown[] = operations;\n const body = async (transactionDriver: AnyDriver): Promise<unknown[]> => {\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index]!;\n const slot = slots?.[index];\n if (slot === undefined) {\n results[index] = await transactionOperationOwner(operation).executeWith(\n operation,\n transactionDriver\n );\n continue;\n }\n // The reserved execution turns what its core throws into a rejection.\n slot.owner\n .executeCore(operation, transactionDriver, slot.notifications)\n .then(slot.child.resolve, slot.child.reject);\n try {\n results[index] = await memberValue(slot);\n } catch (failure) {\n // The members after a failed one never run: their handlers resume\n // with its failure before the rollback, which fails with it.\n await settleSlots(slots!.slice(index + 1), [failure]);\n }\n }\n return results;\n };\n return transact(engine, options, context, body, scope, batch);\n}\n\n/** The members prepared in order and sent as one native batch. */\nasync function sendNativeBatch(\n operations: TransactionOperationCapability[],\n driver: AnyDriver,\n options: ArrayOptions,\n context: QueryExecutionContext,\n slots?: ArraySlot[],\n scope?: TransactionScope,\n batch?: ArrayCertainty\n): Promise<unknown[]> {\n // Slots were reserved before they were admitted.\n if (slots === undefined)\n for (const operation of operations)\n transactionOperationOwner(operation).reserveWith(operation, driver);\n // What the sent batch reached, reported to every unit and published once,\n // and what publishing it failed with.\n let reached: WriteOutcome[\"certainty\"] | undefined;\n const late: unknown[] = [];\n const publish = async (certainty: WriteOutcome[\"certainty\"]) => {\n if (reached) return;\n reached = certainty;\n if (batch) batch.certainty = certainty;\n for (const slot of slots!) {\n slot.certainty = certainty;\n try {\n // Only a write's handlers are handed notifications.\n await slot.notifications?.[\n certainty === \"committed\" ? \"committed\" : \"mayHaveCommitted\"\n ]();\n } catch (error) {\n late.push(error);\n }\n }\n try {\n await scope?.outcomes?.publish(certainty);\n } catch (error) {\n late.push(error);\n }\n };\n // The failure to throw: every slot settled, it rejects with the folded one.\n const close = async (failure: unknown, sent?: true): Promise<unknown> => {\n if (slots === undefined) return failure;\n if (sent) await publish(\"may-have-committed\");\n await settleSlots(\n slots,\n [reached ? markCommitCertainty(failure, reached) : failure],\n late\n );\n };\n let queries: BatchQuery[];\n let guards: PreparedBatchGuard[];\n let parsers: BatchParser[];\n try {\n ({ queries, guards, parsers } = await prepareNativeBatch(\n operations,\n driver\n ));\n } catch (error) {\n throw await close(error);\n }\n let batchResults: QueryResult<unknown>[];\n try {\n batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context,\n slots && driver.supportsOrderedCommittedSegments\n ? () => publish(\"committed\")\n : undefined\n );\n if (slots) await publish(\"committed\");\n assertNativeBatchResults(driver, batchResults, queries.length);\n } catch (error) {\n throw await close(error, true);\n }\n const results: unknown[] = operations;\n for (let index = 0; index < parsers.length; index += 1) {\n const slot = slots?.[index];\n if (slot === undefined)\n results[index] = await parsers[index]!(batchResults);\n else\n try {\n slot.child.resolve(await parsers[index]!(batchResults));\n } catch (error) {\n slot.child.reject(markCommitCertainty(error, \"committed\"));\n }\n }\n if (slots)\n await settleSlots(\n slots,\n [],\n late.map((error) => markCommitCertainty(error, \"committed\")),\n results\n );\n return results;\n}\n\nconst nothing = (): undefined => undefined;\n\n/** The member's value as its handlers return it, or its core's before they start. */\nexport function memberValue(\n slot: Pick<ArraySlot, \"query\" | \"child\">\n): Promise<unknown> {\n return slot.query ?? slot.child.promise;\n}\n\n/**\n * Wait for every member's handlers, each child still unsettled rejected\n * with the first of `failures`, their values written into `values`; then\n * fail with the first failure, the distinct others and `extra` folded in.\n */\nexport async function settleSlots(\n slots: readonly ArraySlot[],\n failures: unknown[],\n extra: readonly unknown[] = [],\n values: unknown[] = []\n): Promise<void> {\n for (const slot of slots) slot.child.reject(failures[0]);\n for (const [index, settled] of (\n await Promise.allSettled(slots.map(memberValue))\n ).entries())\n if (settled.status === \"fulfilled\") values[index] = settled.value;\n else failures.push(settled.reason);\n failures.push(...extra);\n if (failures.length > 0)\n throw combineArrayFailures(failures[0], failures.slice(1));\n}\n\n/** The primary failure, with the distinct ones that settled beside it. */\nexport function combineArrayFailures(\n primary: unknown,\n suppressed: readonly unknown[]\n): unknown {\n const distinct = suppressed.filter((failure) => failure !== primary);\n if (distinct.length === 0) return primary;\n return new AggregateError(\n [primary, ...distinct],\n \"Array transaction and operation post-work both failed.\",\n { cause: primary }\n );\n}\n\n/** An error of viborm's own marked with the array's commit certainty. */\nfunction markCommitCertainty(\n error: unknown,\n certainty: WriteOutcome[\"certainty\"]\n): unknown {\n return isVibORMError(error) ? attachCommitCertainty(error, certainty) : error;\n}\n\nexport interface ArrayDeferred<Value> {\n readonly promise: Promise<Value>;\n readonly resolve: (value: Value) => void;\n readonly reject: (reason: unknown) => void;\n}\n\n/** A promise settled from outside; the first settlement holds. */\nexport function createArrayDeferred<Value>(): ArrayDeferred<Value> {\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolve!: (value: Value) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<Value>((ok, fail) => {\n resolve = ok;\n reject = fail;\n });\n promise.catch(nothing);\n return { promise, resolve, reject };\n}\n\n/** Prepare members in order into one native batch with per-member parsers. */\nexport async function prepareNativeBatch(\n operations: readonly TransactionOperationCapability[],\n driver: AnyDriver\n): Promise<{\n readonly queries: BatchQuery[];\n readonly guards: PreparedBatchGuard[];\n readonly parsers: BatchParser[];\n}> {\n const queries: BatchQuery[] = [];\n const guards: PreparedBatchGuard[] = [];\n const parsers: BatchParser[] = [];\n for (const operation of operations) {\n const owner = transactionOperationOwner(operation);\n const preparation = await owner.observeBatchPhase(\n operation,\n driver,\n async () => {\n const prepared = owner.prepare(operation, driver);\n if (prepared) return { prepared };\n return { preparedBatch: await owner.prepareBatch(operation) };\n }\n );\n const start = queries.length;\n if (preparation.prepared) {\n queries.push(preparation.prepared);\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () => {\n const result = batchResults[start];\n if (!result)\n throw arrayError(\n driver,\n `omitted the result for operation \"${owner.operation(operation)}\"`,\n { operation: owner.operation(operation) }\n );\n return owner.parseResult(operation, result);\n })\n );\n continue;\n }\n const { preparedBatch } = preparation;\n if (!preparedBatch) throw unbatchableArrayError(driver);\n const length = preparedBatch.queries.length;\n for (const query of preparedBatch.queries) queries.push(query);\n for (const guard of preparedBatch.guards ?? []) {\n guards.push({ ...guard, queryIndex: start + guard.queryIndex });\n }\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () =>\n preparedBatch.parseResult(batchResults.slice(start, start + length))\n )\n );\n }\n return { queries, guards, parsers };\n}\n\nexport async function executeNativeBatch(\n driver: AnyDriver,\n queries: BatchQuery[],\n guards: PreparedBatchGuard[],\n options: ArrayOptions,\n context: QueryExecutionContext,\n committed?: () => Promise<void>\n): Promise<QueryResult<unknown>[]> {\n // The driver answers an empty batch itself, without sending it.\n try {\n return await driver._executeBatch(\n queries,\n options as BatchTransactionOptions | undefined,\n context,\n committed\n );\n } catch (error) {\n throw await attributeOperationBatchError(error, guards, driver, queries);\n }\n}\n\nexport function assertNativeBatchResults(\n driver: AnyDriver,\n results: QueryResult<unknown>[],\n queryCount: number\n): void {\n assertNormalizedBatchResults(results, queryCount, {\n provider: driver.driverName,\n operation: \"$transaction([...])\",\n });\n}\n\nexport function assertAtomicArraySupport(driver: AnyDriver): void {\n if (driver.supportsTransactions || driver.supportsBatch) return;\n throw arrayError(\n driver,\n \"supports neither transactions nor atomic batch execution\"\n );\n}\n\nexport function unbatchableArrayError(driver: AnyDriver): TransactionError {\n return arrayError(\n driver,\n \"does not support callback transactions and this transaction contains operations that cannot be batched atomically\"\n );\n}\n\nfunction arrayError(\n driver: AnyDriver,\n problem: string,\n meta: Record<string, unknown> = { method: \"$transaction([...])\" }\n): TransactionError {\n return new TransactionError(`Driver \"${driver.driverName}\" ${problem}.`, {\n meta: { driver: driver.driverName, ...meta },\n });\n}\n\nfunction assertOwnedOperations(\n candidates: unknown[],\n engine: QueryEngine\n): asserts candidates is TransactionOperationCapability[] {\n for (const candidate of candidates) {\n if (candidate === null || typeof candidate !== \"object\") {\n throw new InvalidTransactionInputError();\n }\n const owner = readTransactionOperation(candidate);\n if (owner === undefined) throw new InvalidTransactionInputError();\n if (owner.clientId(candidate) !== engine.clientId) {\n throw PendingOperationError.clientMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n if (owner.scopeId(candidate) !== engine.scopeId) {\n throw PendingOperationError.scopeMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n }\n}\n","/**\n * Where a call's words find what they read: a first moment's context and a\n * second moment's `run` carry the call (`CALL`), a method's scope carries its\n * view (`SCOPE`). Symbols, so a call, a run or a scope shows them to the words\n * that import this module and to nothing else.\n */\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport type { PreparedOperation } from \"@query-engine/raptor3/commands\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Seconds } from \"./call\";\nimport type { Attempt, WriteOutcomeRegistration } from \"./query\";\nimport type { Watched } from \"./watch-part\";\n\n/** The key of the call a first moment's context and a `run` belong to. */\nexport const CALL = Symbol(\"viborm.call\");\n/** The key of the view a method's scope serves. */\nexport const SCOPE = Symbol(\"viborm.scope\");\n/** The key of what a second moment's `run` started, which `again` and `via` read. */\nexport const ATTEMPT = Symbol(\"viborm.attempt\");\n\n/**\n * One call, as its words and its parts read it: a model call's own object, a\n * raw statement's resolved query. Each part that keeps something for the\n * call writes its own field, and only it reads that field: what it keeps\n * lives as long as the call, never on a chain or a part, which outlive it.\n */\nexport interface CallOrigin {\n /** The arguments of the extensions the call admitted. */\n readonly values?: AdmittedArgs;\n /** Set once the call is an operation of an engine: absent on a raw statement. */\n of?: {\n readonly engine: QueryEngine;\n readonly context: QueryExecutionContext;\n /** The call prepared once: what runs is this preparation. */\n readonly prepared: () => PreparedOperation;\n };\n /** `around` (`call.ts`): what each part's first moment left its second. */\n seconds?: Seconds;\n /** `watch` and `settled` on a model call (`watch-part.ts`): per extension. */\n watched?: Watched;\n /** `settled` on a raw statement, in an `around`'s first moment (`call.ts`). */\n told?: WriteOutcomeRegistration[];\n}\n\n/** The view one extension's method scope serves. */\ninterface ScopeOrigin {\n readonly engine: QueryEngine;\n readonly extension: string;\n}\n\n// Only this module and the core write these keys: what they hold is what\n// the core put there.\nconst isCall = <T = CallOrigin>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null;\nconst isScope = (value: unknown): value is ScopeOrigin =>\n typeof value === \"object\" && value !== null && \"engine\" in value;\n\n/** The call a first moment's context or a `run` belongs to, if it has one. */\nexport function callOf(x: object): CallOrigin | undefined {\n const call: unknown = Reflect.get(x, CALL);\n return isCall(call) ? call : undefined;\n}\n\n/**\n * What a second moment's `run` started: every `run` the host hands carries\n * it, and a forged one is not guarded against (D6).\n */\nexport function attemptOf(run: object): Attempt {\n return Reflect.get(run, ATTEMPT);\n}\n\n/** The view a method's scope serves, if `x` is one. */\nexport function scopeOf(x: object): ScopeOrigin | undefined {\n const scope: unknown = Reflect.get(x, SCOPE);\n return isScope(scope) ? scope : undefined;\n}\n\n/** The engine a call, a run or a scope works on. */\nexport function engineOf(x: object): QueryEngine | undefined {\n return callOf(x)?.of?.engine ?? scopeOf(x)?.engine;\n}\n","import { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n isVibORMError,\n QueryError,\n retainWriteOutcomeFailure,\n VibORMError,\n} from \"@errors\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\nimport { errorCause, isError } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallHandler } from \"./chain\";\nimport { ATTEMPT, CALL, type CallOrigin } from \"./origin\";\n\nexport type CallMode = \"direct\" | \"transaction\" | \"array\";\n\nexport type RawQueryKind =\n | \"queryRaw\"\n | \"executeRaw\"\n | \"queryRawUnsafe\"\n | \"executeRawUnsafe\";\n\ntype RawQueryOperation = `$${RawQueryKind}`;\n\ninterface PreparedQueryContextBase<Input extends object> {\n readonly mode: CallMode;\n readonly input: Readonly<Input>;\n /**\n * One object per call, the same one its first moments were handed: what\n * links an `around` part's two moments.\n */\n readonly call?: CallOrigin;\n}\n\nexport interface PreparedModelQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: \"model\";\n readonly model: string;\n readonly operation: string;\n /**\n * The call's admitted arguments. A handler sees only its own extension's,\n * and only when that extension declares any.\n */\n readonly values?: AdmittedArgs;\n}\n\nexport interface PreparedRawQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: RawQueryKind;\n readonly model: undefined;\n readonly operation: RawQueryOperation;\n}\n\n/** The prepared logical-operation facts safe for `around` parts to inspect. */\nexport type PreparedQueryContext<\n Input extends object = Record<string, unknown>,\n> = PreparedModelQueryContext<Input> | PreparedRawQueryContext<Input>;\n\nexport type WriteOutcome = Readonly<{\n certainty: \"committed\" | \"may-have-committed\";\n}>;\n\nexport type WriteOutcomeListener = (\n outcome: WriteOutcome\n) => unknown | Promise<unknown>;\n\nexport interface WriteOutcomeRegistration {\n readonly extension: string;\n readonly listener: WriteOutcomeListener;\n /**\n * What installs a transaction scope's collector, brought by the word that\n * registered (`settled`); absent, the scope's own, installed at its start\n * by a chain whose parts hear writes.\n */\n readonly collect?: typeof collect;\n /**\n * What tells a call's registrations of its outcome, brought by what\n * registered (`settled`, the part that watches writes): a chain where\n * nothing registers carries none of it.\n */\n readonly tell?: typeof tell;\n /** In a transaction: the call reached its outcome, so it is told at the scope's end. */\n ok?: true;\n}\n\nexport interface WriteOutcomeNotifications {\n readonly committed: () => Promise<void>;\n readonly mayHaveCommitted: () => Promise<void>;\n}\n\n/** A `run()` no second moment may make once it returned. */\nconst AFTER_RETURN = \"called run() after its second moment returned\";\n\n/** The child a handler chain runs: on the driver a handler chose, if any. */\ntype Child<Result> = (driver?: AnyDriver) => Promise<Result>;\n\n/** What one `around` part runs for a call: its second moment, handed `run` by the runner. */\nexport type AroundRunner = (\n prepared: PreparedQueryContext<object>,\n run: () => Promise<unknown>\n) => unknown;\n\n/** The `around` parts one call runs, the first applied outermost. */\nexport type AroundHandlers = readonly CallHandler<AroundRunner>[];\n\ntype Certainty = WriteOutcome[\"certainty\"];\n\n/** Private coordination hooks used only while array members await admission. */\nexport interface AdmissionHooks {\n readonly reportAdmissionFailure?: (failure: unknown) => void;\n readonly readCommitCertainty?: () => Certainty | undefined;\n}\n\n/** The child of a prepared call, told of the commits it reaches. */\ntype PreparedChild<Result> = (\n notifications?: WriteOutcomeNotifications,\n driver?: AnyDriver\n) => Promise<Result>;\n\n/**\n * Execute one prepared operation through its `around` parts and under what\n * its write registered.\n */\nexport function executePreparedQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration\n): Promise<Result> {\n // A context is prepared only for a call some `around` part wraps.\n const intercepted = context !== undefined;\n if (!(intercepted || registration)) return child();\n return isWrite || registration\n ? executeRegisteredQuery(\n context,\n arounds,\n child,\n isWrite,\n scope,\n hooks,\n registration,\n runArounds\n )\n : runArounds(\n context!,\n arounds,\n (driver) => child(undefined, driver),\n hooks?.readCommitCertainty,\n hooks?.reportAdmissionFailure\n );\n}\n\n/**\n * One write under what it registered (the registration a model write's\n * watches made, or the `settled` functions a raw statement's first moments\n * kept on it), around its `around` parts when `intercept` runs them, which\n * {@link executePreparedQuery} passes: a chain without `around` parts does\n * not carry their runner. Each commit the child reports is told (outside a\n * transaction, the certainty it reached is what `again` reads), and a write\n * that succeeded without reporting one is told it committed.\n */\nexport function executeRegisteredQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration,\n intercept?: typeof runArounds\n): Promise<Result> {\n const registrations = registration ? [registration] : context?.call?.told;\n const told = registrations?.[0]?.tell?.(registrations, scope);\n let reported = false;\n let certainty: Certainty | undefined;\n const notified = (reached: Certainty) => async (): Promise<void> => {\n reported = true;\n if (!scope) certainty = reached;\n await told?.(reached);\n };\n const notifications: WriteOutcomeNotifications = {\n committed: notified(\"committed\"),\n mayHaveCommitted: notified(\"may-have-committed\"),\n };\n // What fails before its outcome is reached is never marked, so never told.\n const executeChild = async (driver?: AnyDriver): Promise<Result> => {\n const value = await child(notifications, driver);\n if (isWrite && !reported) await notifications.committed();\n return value;\n };\n return intercept && context && arounds?.length\n ? intercept(\n context,\n arounds,\n executeChild,\n () => certainty ?? hooks?.readCommitCertainty?.(),\n hooks?.reportAdmissionFailure\n )\n : executeChild();\n}\n\n/**\n * Run one already-compiled part chain around one prepared child, the\n * first handler outermost.\n *\n * The undefined/empty branch deliberately returns the child's promise directly:\n * unextended operations allocate no runner promise, context, closure, or list.\n */\nexport function runArounds<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n arounds: AroundHandlers | undefined,\n child: Child<Result>,\n readCommitCertainty?: () => Certainty | undefined,\n reportAdmissionFailure?: (failure: unknown) => void\n): Promise<Result> {\n const at = (index: number, driver?: AnyDriver): Promise<Result> => {\n const part = arounds?.[index];\n return part === undefined\n ? child(driver)\n : runAround(\n context,\n part,\n (chosen) => at(index + 1, chosen ?? driver),\n readCommitCertainty,\n reportAdmissionFailure,\n () => child(driver)\n );\n };\n return at(0);\n}\n\n/**\n * One `run` of one `around` part, as the words that read it find it\n * (`again`, `via`): what may start the child, and what happened to it.\n */\nexport interface Attempt {\n /** `run()` may start the child. */\n open: boolean;\n /** The child's last start failed. */\n failed: boolean;\n /** The second moment returned. */\n done: boolean;\n /** A direct call outside a transaction and an array. */\n readonly direct: boolean;\n /** A direct read: what `via` may run on another driver. */\n readonly routable: boolean;\n readonly certainty: (() => Certainty | undefined) | undefined;\n readonly start: (driver?: AnyDriver) => Promise<unknown>;\n}\n\n/**\n * One handler around its child. Once the child ran, its failure is the\n * call's, whatever the handler returns or throws after it; a handler that\n * breaks the protocol fails the call with that refusal once the child\n * succeeded.\n */\nasync function runAround<Result, Input extends object>(\n prepared: PreparedQueryContext<Input>,\n part: CallHandler<AroundRunner>,\n child: Child<Result>,\n readCommitCertainty: (() => Certainty | undefined) | undefined,\n reportAdmissionFailure: ((failure: unknown) => void) | undefined,\n core: () => Promise<Result>\n): Promise<Result> {\n const { extension } = part;\n const direct = prepared.mode === \"direct\";\n const routable =\n direct && prepared.kind === \"model\" && isReadOperation(prepared.operation);\n // A direct read may run once more after its handler returned (a value\n // served now and refreshed later): that run is the core's alone.\n let replayable = routable;\n let running: Promise<Result> | undefined;\n let protocolFailure: QueryError | undefined;\n const refuse = (failure: string): QueryError => {\n if (protocolFailure === undefined) {\n protocolFailure = aroundError(extension, prepared, failure);\n reportAdmissionFailure?.(protocolFailure);\n }\n return protocolFailure;\n };\n const attempt: Attempt = {\n open: true,\n failed: false,\n done: false,\n direct,\n routable,\n certainty: readCommitCertainty,\n start(driver) {\n if (!attempt.open) throw refuse(\"called run() more than once\");\n if (attempt.done) throw refuse(AFTER_RETURN);\n attempt.open = false;\n attempt.failed = false;\n // What the child throws, even at once, is its promise's rejection.\n running = (async () => child(driver))();\n // Attached first, so a handler's own `catch` already reads it.\n running.then(undefined, () => {\n attempt.failed = true;\n });\n return running;\n },\n };\n const run = Object.defineProperties(\n (): Promise<unknown> => {\n if (!attempt.done) return attempt.start();\n if (!replayable) throw refuse(AFTER_RETURN);\n replayable = false;\n return (async () => core())();\n },\n {\n // Read when asked: the context snapshots the input the first time.\n input: { get: () => prepared.input },\n mode: { value: prepared.mode },\n [CALL]: { value: prepared.kind === \"model\" ? prepared.call : undefined },\n [ATTEMPT]: { value: attempt },\n }\n );\n let outcome: { readonly value: Result } | { readonly reason: unknown };\n try {\n outcome = {\n // A second moment answers the call: `around`'s types hold its value\n // to the call's result.\n value: (await part.handler(prepared, run)) as Result,\n };\n } catch (reason) {\n outcome = { reason };\n }\n attempt.done = true;\n const failure =\n \"reason\" in outcome &&\n (protocolFailure === undefined || outcome.reason !== protocolFailure)\n ? aroundFailure(\n extension,\n prepared,\n outcome.reason,\n readCommitCertainty?.()\n )\n : undefined;\n if (running === undefined) {\n if (failure !== undefined) throw failure;\n if (\n prepared.mode === \"array\" ||\n prepared.kind !== \"model\" ||\n !isReadOperation(prepared.operation)\n )\n throw aroundError(extension, prepared, \"returned without run()\");\n } else {\n if (failure !== undefined && !attempt.failed)\n reportAdmissionFailure?.(failure);\n await running;\n }\n if (\"value\" in outcome && protocolFailure === undefined) return outcome.value;\n throw protocolFailure ?? failure;\n}\n\nfunction aroundFailure<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n reason: unknown,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): Error {\n if (isError(reason)) return reason;\n return aroundError(\n extension,\n context,\n \"failed\",\n errorCause(reason),\n commitCertainty\n );\n}\n\nfunction aroundError<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n failure: string,\n cause?: Error,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): QueryError {\n return new QueryError(\n `Extension \"${extension}\" around() for ${context.kind === \"model\" ? `${context.model}.${context.operation}` : context.operation} ${failure}.`,\n {\n ...(cause && { cause }),\n meta: {\n method: \"around\",\n model: context.model,\n operation: context.operation,\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n },\n }\n );\n}\n\n/**\n * The collector of one transaction scope: the registrations its calls\n * staged, each told at the scope's end if its call reached its outcome.\n */\nexport class TransactionWriteOutcomes {\n readonly staged: WriteOutcomeRegistration[] = [];\n\n /** Tell what reached its outcome; a native batch's scope ends so. */\n publish(certainty: Certainty): Promise<void> {\n return publishWriteOutcomes(\n this.staged.filter((registration) => registration.ok),\n { certainty }\n );\n }\n\n /**\n * End the scope this collects for, with what its transaction settled\n * with. A savepoint that commits hands what it collected to its parent's\n * collector, which owns the decision; the outermost publishes it after\n * its commit, or, when its commit failed after COMMIT was sent, with the\n * certainty reached, which the failure then carries.\n */\n async end<T>(\n { parent, root }: TransactionScope,\n settled: T,\n failed?: true\n ): Promise<T> {\n if (!failed) {\n if (parent)\n collect(parent).staged.push(\n ...this.staged.filter((registration) => registration.ok)\n );\n else await this.publish(\"committed\");\n return settled;\n }\n const { certainty } = root;\n if (parent || certainty === undefined) throw settled;\n const primary = isVibORMError(settled)\n ? attachCommitCertainty(settled, certainty)\n : settled;\n try {\n await this.publish(certainty);\n } catch (outcomeFailure) {\n throw retainWriteOutcomeFailure(primary, outcomeFailure);\n }\n throw primary;\n }\n}\n\n/**\n * One transaction scope, as `transact` (`coordination.ts`) runs it: what its\n * calls register waits in it until it ends. The scope holds no code: the\n * first registration installs the collector (`collect`), which brings the\n * code that ends the scope, so a transaction where nothing registers runs\n * none of it.\n */\nexport interface TransactionScope {\n /** The scope this one is a savepoint of. */\n readonly parent: TransactionScope | undefined;\n /** The outermost scope's commit phase, as its driver reports it. */\n readonly root: CommitPhase;\n outcomes?: TransactionWriteOutcomes;\n}\n\n/** How far a transaction's commit went; nothing before COMMIT was sent. */\nexport interface CommitPhase {\n certainty?: Certainty;\n}\n\n/** The collector of a transaction scope, installed by its first registration. */\nexport function collect(scope: TransactionScope): TransactionWriteOutcomes {\n scope.outcomes ??= new TransactionWriteOutcomes();\n return scope.outcomes;\n}\n\n/**\n * What tells one call's registrations of the commits it reaches: inside a\n * transaction, each is staged in the scope and marked once the call reached\n * its outcome, told when the scope ends; outside one, each commit is told.\n */\nexport function tell(\n registrations: readonly WriteOutcomeRegistration[],\n scope: TransactionScope | undefined\n): (certainty: Certainty) => Promise<void> {\n if (scope === undefined)\n return (certainty) => publishWriteOutcomes(registrations, { certainty });\n for (const registration of registrations)\n (registration.collect?.(scope) ?? scope.outcomes)?.staged.push(\n registration\n );\n return async () => {\n for (const registration of registrations) registration.ok = true;\n };\n}\n\n/**\n * Deliver every registered listener in registration order, all of them. The\n * first fault rejects: an error of viborm's own as it is, any other value as\n * the cause of a `QueryError`; later faults are lost.\n */\nexport async function publishWriteOutcomes(\n registrations: readonly WriteOutcomeRegistration[],\n outcome: WriteOutcome\n): Promise<void> {\n let first: unknown;\n for (const { extension, listener } of registrations) {\n try {\n await listener(outcome);\n } catch (reason) {\n first ??=\n reason instanceof VibORMError\n ? reason\n : new QueryError(\n `Extension \"${extension}\" settled() failed (${outcome.certainty}).`,\n {\n cause: errorCause(reason),\n meta: {\n method: \"settled\",\n commitCertainty: outcome.certainty,\n },\n }\n );\n }\n }\n if (first) throw first;\n}\n","/**\n * The `admit` hooks of a chain whose parts concern a member of\n * `$transaction([...])`. Where `around` parts may wrap a member, before the\n * one executor (`@client/array-transaction`) sends anything, every member's\n * handlers start and the array waits until each reached `run()` or failed: a\n * refusal, a second `run()`, a late detached one or a handler that throws\n * aborts the array, and nothing is sent. Where parts only hear a member's\n * writes, nothing waits: each member's registration is staged and its child\n * handed what tells it of the commit (`stageArray`).\n */\nimport {\n type ArraySlot,\n createArrayDeferred,\n memberValue,\n} from \"@client/array-transaction\";\nimport {\n type TransactionOperationCapability,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport {\n type AdmissionHooks,\n type executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n type WriteOutcomeNotifications,\n} from \"./query\";\n\n/** What admission reads and writes of a slot. */\nexport type AdmissionSlot = Omit<ArraySlot, \"operation\" | \"owner\">;\n\n/** Whether a part intercepts one of the members, once they are prepared. */\nexport function interceptsArray(\n operations: readonly TransactionOperationCapability[]\n): boolean {\n return operations.some((operation) => {\n const { handlers, registration } =\n transactionOperationOwner(operation).around(operation);\n return handlers?.length || registration;\n });\n}\n\n/**\n * The hook of a chain whose parts hear writes and wrap no call: a member with\n * a registration runs under it, its child reached at once, so the array has\n * nothing to wait for. Its value is then the registration's run, whose\n * rejection the array reads in member order.\n */\nexport async function stageArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope\n): Promise<undefined> {\n for (const slot of slots) {\n const { write, registration } = slot.owner.around(slot.operation);\n if (registration === undefined) continue;\n const child = (notifications?: WriteOutcomeNotifications) => {\n slot.notifications = notifications;\n return slot.child.promise;\n };\n const query = executeRegisteredQuery(\n undefined,\n undefined,\n child,\n write,\n scope,\n undefined,\n registration\n );\n slot.query = query;\n // Read by the array in member order; one the array never reaches (it\n // failed before) is settled here.\n query.catch(ignore);\n }\n return undefined;\n}\n\nconst ignore = (): undefined => undefined;\n\n/**\n * The hook: each member's handlers started, in member order, by `execute`\n * (the chain's runner of a prepared call), which stages what it registered;\n * a member with nothing to intercept is admitted at once.\n */\nexport function admitArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope,\n execute: typeof executePreparedQuery\n): Promise<readonly unknown[] | undefined> {\n const facts = slots.map((slot) => slot.owner.around(slot.operation));\n return admitArrayQueries(slots, (slot, child, hooks) => {\n const { context, handlers, write, registration } =\n facts[slots.indexOf(slot)]!;\n return handlers?.length || registration\n ? execute(context, handlers, child, write, scope, hooks, registration)\n : child();\n });\n}\n\n/**\n * Start every member's handlers and release the array only after each has\n * reached its child. On a failure, every child rejects with the first one,\n * and the distinct failures each member reported return in member order.\n */\nexport async function admitArrayQueries<Slot extends AdmissionSlot>(\n slots: readonly Slot[],\n start: (\n slot: Slot,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n hooks: AdmissionHooks\n ) => Promise<unknown>\n): Promise<readonly unknown[] | undefined> {\n let failed: { readonly failure: unknown } | undefined;\n let remaining = slots.length;\n const signal = createArrayDeferred<void>();\n if (remaining === 0) signal.resolve();\n\n for (const slot of slots) {\n const reportAdmissionFailure = (failure: unknown): void => {\n const failures = (slot.admissionFailures ??= []);\n if (!failures.includes(failure)) failures.push(failure);\n failed ??= { failure };\n signal.reject(failure);\n };\n let query: Promise<unknown>;\n try {\n query = start(\n slot,\n (notifications) => {\n slot.notifications = notifications;\n // Reached once: a second `run()` is refused before its child.\n remaining -= 1;\n if (remaining === 0) signal.resolve();\n return slot.child.promise;\n },\n {\n reportAdmissionFailure,\n readCommitCertainty: () => slot.certainty,\n }\n );\n } catch (error) {\n reportAdmissionFailure(error);\n query = Promise.reject(error);\n }\n slot.query = query;\n query.catch(reportAdmissionFailure);\n }\n\n try {\n await signal.promise;\n // A handler that fails in the turn its member was admitted still aborts.\n await Promise.resolve();\n if (failed) throw failed.failure;\n return undefined;\n } catch (failure) {\n for (const slot of slots) slot.child.reject(failure);\n await Promise.allSettled(slots.map(memberValue));\n const reported: unknown[] = [];\n for (const slot of slots)\n for (const failure of slot.admissionFailures ?? [])\n if (!reported.includes(failure)) reported.push(failure);\n return reported;\n }\n}\n","/**\n * What a part that wraps a call's execution brings beside its own state: how\n * a prepared call runs (under write-outcome registrations, under `around`\n * parts), and, for the parts an array member can be intercepted by, how the\n * one executor of `$transaction([...])` (`@client/array-transaction`)\n * admits its members. A chain of none of those parts carries none of it.\n *\n * And how every transaction scope runs (`transact`): what a call registers\n * there waits in its scope, and the first registration installs the\n * collector by value (`collect`, imported by what registers: `settled`, the\n * part that watches writes, `unit` parts), so an extension behaves the same\n * whatever else its chain holds, and a transaction where nothing registers\n * runs none of that code.\n */\nimport type { ArraySlot } from \"@client/array-transaction\";\nimport { appendExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { afterFulfilled } from \"@drivers/rejection-observed-promise\";\nimport type { TransactionOptions } from \"@drivers/shared/transaction-options\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport { admitArray, interceptsArray, stageArray } from \"./array-admission\";\nimport {\n type CommitPhase,\n type collect,\n executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n} from \"./query\";\n\n/** The commit certainty one array reports to its `batch` unit. */\nexport type ArrayCertainty = CommitPhase;\n\nexport interface Coordination {\n /** What it adds to the one before it: a chain keeps the highest it needs. */\n readonly rank: number;\n /**\n * Where its parts hear writes: the collector installed in each transaction\n * scope from its start, so the scope's failure carries its commit\n * certainty even when nothing registered.\n */\n readonly collect?: typeof collect;\n /**\n * What runs a prepared call under the chain's `around` parts and what it\n * registered: absent where neither exists (`unit` parts alone), since\n * core asks it only of a call that has handlers or a registration.\n */\n readonly executePreparedQuery?: typeof executePreparedQuery;\n /** Present with `admit`: whether a part intercepts one of the members. */\n readonly intercepts?: typeof interceptsArray;\n /**\n * Present where a member of `$transaction([...])` may be intercepted:\n * starts every member's handlers and waits until each reached `run()`,\n * before anything is sent. Resolves to the failures that abort the array.\n */\n readonly admit?: (\n slots: readonly ArraySlot[],\n scope: TransactionScope\n ) => ReturnType<typeof admitArray>;\n}\n\n/**\n * For `unit` parts: nothing of the chain wraps a call, the prepared call\n * runs as it is.\n */\nexport const UNITS: Coordination = { rank: -1 };\n\n/**\n * For the part that watches writes: an array member it hears runs under its\n * registration, and nothing waits, since no handler wraps it.\n */\nexport const ARRAYS: Coordination = {\n rank: 1,\n executePreparedQuery: executeRegisteredQuery,\n intercepts: interceptsArray,\n admit: stageArray,\n};\n\n/** For `around` parts: what runs their second moments around a call, too. */\nexport const QUERIES: Coordination = {\n rank: 2,\n executePreparedQuery,\n intercepts: interceptsArray,\n admit: (slots, scope) => admitArray(slots, scope, executePreparedQuery),\n};\n\n/**\n * The chain being built coordinated as `needed` asks, never less than it\n * was; `collect` is kept whatever the rank.\n */\nexport function coordinate(\n next: { coordination?: Coordination; collect?: typeof collect },\n needed: Coordination,\n collects?: typeof collect\n): void {\n if (collects) next.collect = collects;\n if (next.coordination === undefined || needed.rank > next.coordination.rank)\n next.coordination = needed;\n}\n\n/**\n * Run one transaction scope. A savepoint's scope is a child of its parent's;\n * the outermost one hears its commit phases where a part may register, for\n * the certainty of what was registered in it. What its calls register installs\n * the collector that ends it (`TransactionWriteOutcomes.end`). A body run\n * again (a driver that reruns a callback on a conflict) gets a scope of its\n * own: nothing the failed run registered is told. An array's scope is made\n * before its members are admitted, and passed.\n */\nexport function transact<T>(\n engine: QueryEngine,\n options: TransactionOptions | undefined,\n context: QueryExecutionContext,\n body: (driver: AnyDriver, scope: TransactionScope) => Promise<T>,\n made?: TransactionScope,\n root: CommitPhase = made?.root ?? {}\n): Promise<T> {\n const chain = engine.extensionChain;\n const parent = engine.transaction;\n let scope: TransactionScope | undefined;\n const end =\n (failed?: true) =>\n (settled: T): T | Promise<T> => {\n // A driver that reports no phase still committed what resolved.\n if (!(failed || parent)) root.certainty = \"committed\";\n if (!scope?.outcomes) {\n if (failed) throw settled;\n return settled;\n }\n // The promise this handler returns is taken a microtask later, and\n // workerd reports a rejection no handler holds by then.\n const ended = scope.outcomes.end(scope, settled, failed);\n ended.catch(() => undefined);\n return ended;\n };\n const ran = engine.driver.withTransaction(\n (driver) => {\n scope = made ?? scopeOf(engine, root);\n return body(driver, scope);\n },\n options,\n // Only where a part may register: a chain of `call` parts, rules or\n // defaults alone runs its transactions as an unextended client does.\n parent || !(chain?.coordination || chain?.methods)\n ? context\n : appendExecutionTransactionPhases(context, {\n readyToCommit: () => {\n root.certainty = \"may-have-committed\";\n },\n committed: () => {\n root.certainty = \"committed\";\n },\n })\n );\n // A savepoint that fails drops what it collected: no handler of its\n // rejection, which only the caller's own observes (an unobserved one fails\n // the outer transaction, and is reported there alone).\n return parent ? afterFulfilled(ran, end()) : ran.then(end(), end(true));\n}\n\n/**\n * A transaction scope inside `engine`'s, with the collector of a chain whose\n * parts hear writes installed from its start.\n */\nexport function scopeOf(\n engine: QueryEngine,\n root: CommitPhase\n): TransactionScope {\n const scope = { parent: engine.transaction, root };\n engine.extensionChain?.collect?.(scope);\n return scope;\n}\n"],"mappings":"+eAuBA,SAAgB,mBACd,EACA,EACA,EACO,CACP,GAAI,EAAQ,OAAS,aACnB,OAAO,IAAI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EpB,CAAC,CACP,CAID,OAAO,EAAS,EAAe,EAAK,KAAK,CAAC,CAAG,EAAI,KAAK,KAAK,CAAE,IAAI,GAAK,CAAC,CAOzE,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAQ,CAAE,OAAQ,EAAO,YAAa,OAAM,CAElD,OADA,EAAO,gBAAgB,UAAU,EAAM,CAChC"}
|
|
1
|
+
{"version":3,"file":"coordination-BY6Np3xV.mjs","names":["error","candidate","batch","scopeOf","failure","failure"],"sources":["../src/query-engine/batch-error-attribution.ts","../src/client/array-transaction.ts","../src/extensions/origin.ts","../src/extensions/query.ts","../src/extensions/array-admission.ts","../src/extensions/coordination.ts"],"sourcesContent":["import { batchMayContainAssertionCollision } from \"@drivers/error-mapping\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n ForbiddenError,\n ForeignKeyError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n TransactionError,\n VibORMErrorCode,\n} from \"@errors\";\nimport type { PreparedBatchGuard, PreparedGuardFailure } from \"./types\";\n\n/**\n * Materialize a guard's declared {@link PreparedGuardFailure} as its typed\n * error — the ONE failure-to-error construction, which the engine's own\n * referential refusal reuses when it runs outside a package\n * (`Commands.restrictFailure`). A `notFound` failure rebuilds\n * its sentence from the model and verb, so the declared message is never\n * user-facing for that kind; the `raceable` mark is what lets the routed retry\n * re-plan and converge, so it survives every arm.\n */\nexport function createFailureError(\n failure: PreparedGuardFailure,\n model: string,\n operation: string\n): Error {\n if (failure.kind === \"foreignKey\") {\n return new ForeignKeyError(failure.message, { meta: { model, operation } });\n }\n if (failure.kind === \"nestedWrite\") {\n const error = new NestedWriteError(failure.message, failure.relation ?? \"\");\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n }\n if (failure.kind === \"notFound\") {\n return new NotFoundError(model, operation);\n }\n if (failure.kind === \"forbidden\") {\n return new ForbiddenError(\n model,\n operation,\n failure.reason === undefined ? undefined : { reason: failure.reason }\n );\n }\n const error = new TransactionError(failure.message, {\n meta: { model, operation },\n });\n if (failure.raceable) {\n error.meta.raceable = true;\n }\n return error;\n}\n\n/**\n * Attribute a native-batch assertion failure to the guard that raised it (P6\n * pure-leaf extraction, consumed by the client's shared-batch path): a\n * `NestedWriteAssertionError` carries the index of the offending statement when\n * the driver surfaces it, else each guard's probe is re-run to locate the\n * violated precondition. The attributed error reconstructs the guard's typed\n * failure with the correct model/operation.\n *\n * The re-probe runs AFTER the atomic batch rolled back, which makes it blind to\n * one whole class: a premise broken by a SIBLING statement inside the same batch\n * is restored by that rollback and probes clean, so no guard is blamed. When\n * every guard in the batch would raise the same failure for the same\n * model/operation, that blindness costs nothing — whichever fired, the error is\n * the same one — but only once it is established that a guard fired AT ALL.\n *\n * That last part is not free. A native batch is normalized against the JOINED\n * SQL, so one assertion statement anywhere arms the detector\n * (`src/drivers/error-mapping.ts`) for every statement in the batch: an ordinary\n * statement that raises the same provider signature — `n / 0` from a literal\n * `divide: 0` on Postgres, a malformed-JSON argument on MySQL/SQLite — arrives\n * as a `NestedWriteAssertionError` no guard caused. Blaming a guard for it\n * asserts something false about the database (a `NotFoundError`/P2025 for a row\n * that is still there, which Prisma callers branch on). So the reconstruction\n * runs only when NO ordinary statement in the batch could have produced the\n * signature — viborm built every statement, so it can tell — and the raw\n * driver-mapped error stands whenever the failure cannot be tied to a guard.\n * A batch carrying guards that DISAGREE about what went wrong likewise stays\n * un-attributable.\n */\nexport async function attributeOperationBatchError(\n error: unknown,\n guards: readonly PreparedBatchGuard[],\n driver: AnyDriver,\n statements: readonly {\n readonly sql: string;\n readonly context?: QueryExecutionContext;\n }[] = []\n): Promise<unknown> {\n if (!(error instanceof NestedWriteAssertionError)) return error;\n const statementIndex = error.meta.statementIndex;\n if (typeof statementIndex === \"number\") {\n const guard = guards.find(\n (candidate) => candidate.queryIndex === statementIndex\n );\n if (guard) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n return error;\n }\n if (\n guards.length > 0 &&\n batchMayContainAssertionCollision(\n statements,\n driver.dialect,\n new Set(guards.map((guard) => guard.queryIndex))\n )\n ) {\n // A failed premise after rollback does not identify which statement failed.\n return error;\n }\n for (const guard of guards) {\n const result = await driver._execute(\n guard.probe,\n statements[guard.queryIndex]?.context\n );\n const exists = result.rows.length > 0;\n if (guard.premise === \"exists\" ? !exists : exists) {\n return createFailureError(guard.failure, guard.model, guard.operation);\n }\n }\n const [candidate] = guards;\n if (candidate) {\n const attributable = guards.every((guard) =>\n sameAttribution(guard, candidate)\n );\n return attributable\n ? createFailureError(\n candidate.failure,\n candidate.model,\n candidate.operation\n )\n : error;\n }\n return new NestedWriteError(NESTED_WRITE_ASSERTION_FLOOR_MESSAGE, \"\", {\n code: VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED,\n cause: error,\n });\n}\n\n/**\n * Two guards that would produce the SAME error: same model, same operation, and\n * a failure identical in every field the reconstruction below reads.\n */\nfunction sameAttribution(\n guard: PreparedBatchGuard,\n other: PreparedBatchGuard\n): boolean {\n return (\n guard.model === other.model &&\n guard.operation === other.operation &&\n guard.failure.kind === other.failure.kind &&\n guard.failure.message === other.failure.message &&\n guard.failure.relation === other.failure.relation &&\n guard.failure.reason === other.failure.reason &&\n guard.failure.raceable === other.failure.raceable\n );\n}\n","/**\n * The one executor of `$transaction([...])`. Every application runs it: one\n * transaction on a transaction driver, one native batch on a batch driver.\n * A chain whose parts intercept calls admits the members through its\n * coordination's `admit` hook (`@extensions/array-admission`), read from\n * the chain's state, so an application without one carries none of it.\n */\n\nimport { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type {\n AnyDriver,\n BatchQuery,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { assertNormalizedBatchResults } from \"@drivers/normalized-result\";\nimport type {\n BatchTransactionOptions,\n TransactionOptions,\n} from \"@drivers/shared/transaction-options\";\nimport {\n InvalidTransactionInputError,\n isVibORMError,\n PendingOperationError,\n TransactionError,\n} from \"@errors\";\nimport {\n type ArrayCertainty,\n type Coordination,\n scopeOf,\n transact,\n} from \"@extensions/coordination\";\nimport type {\n TransactionScope,\n WriteOutcome,\n WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport { attributeOperationBatchError } from \"@query-engine/batch-error-attribution\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport {\n readTransactionOperation,\n type TransactionOperationCapability,\n type TransactionOperationOwner,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport type { PreparedBatchGuard } from \"@query-engine/types\";\n\ntype ArrayOptions = TransactionOptions | BatchTransactionOptions | undefined;\n\n/** Each member's parser over the batch's results. */\ntype BatchParser = (batchResults: QueryResult<unknown>[]) => Promise<unknown>;\n\n/**\n * Execute one root or nested array transaction. Without an observer, every\n * member's request work (argument admission included) settles before any\n * provider effect; an observer runs it inside each member's unit instead.\n */\nexport function executeArrayTransaction(\n candidates: readonly unknown[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext\n): Promise<unknown[]> {\n let operations: unknown[] | undefined;\n let snapshotFailure: unknown;\n try {\n const length = candidates.length;\n if (\n typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xff_ff_ff_ff\n ) {\n throw new InvalidTransactionInputError();\n }\n const snapshot = new Array<unknown>(length);\n for (let index = 0; index < length; index += 1) {\n snapshot[index] = candidates[index];\n }\n operations = snapshot;\n } catch (error) {\n snapshotFailure = error;\n }\n const run = (batch?: ArrayCertainty): Promise<unknown[]> => {\n if (operations === undefined) throw snapshotFailure;\n assertOwnedOperations(operations, engine);\n if (operations.length === 0) return Promise.resolve(operations);\n if (batch === undefined)\n for (const phase of [\"input\", \"plan\"] as const)\n for (const operation of operations)\n transactionOperationOwner(operation).prepareAdmission(\n operation,\n phase\n );\n return executeMembers(operations, engine, options, context, batch);\n };\n const observation = engine.extensionChain?.observation;\n if (observation === undefined)\n return finishArrayResults(operations, engine, run);\n const batch: ArrayCertainty = {};\n return finishArrayResults(operations, engine, () =>\n observation.run(\n {\n kind: \"batch\",\n operation: \"$transaction([...])\",\n context,\n certainty: () => batch.certainty,\n },\n () => run(batch)\n )\n );\n}\n\n/**\n * Each member's value as its caller receives it: a chain that computes\n * result fields or watches writes finishes every member once the array has\n * settled.\n * The members are read before the run, which writes its values over them.\n */\nfunction finishArrayResults(\n operations: readonly unknown[] | undefined,\n engine: QueryEngine,\n run: () => Promise<unknown[]>\n): Promise<unknown[]> {\n const chain = engine.extensionChain;\n if (chain?.fields === undefined && chain?.watch === undefined) return run();\n const members = [...(operations ?? [])] as object[];\n return run().then(async (values) => {\n // One member at a time: a member's write hooks run in member order, and\n // one failing does not keep the next from running.\n const failures: unknown[] = [];\n for (const [index, operation] of members.entries()) {\n const owner = transactionOperationOwner(operation);\n try {\n if (owner.finishResult)\n values[index] = await owner.finishResult(operation, values[index]);\n } catch (failure) {\n failures.push(failure);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1)\n throw new AggregateError(\n failures,\n \"Several array members failed after commit.\",\n {\n cause: failures[0],\n }\n );\n return values;\n });\n}\n\n/**\n * The members sent as one transaction, or one native batch. On a chain that\n * may intercept them (its `admit` hook), or whose units observe a native\n * batch's members, each member gets a slot first: its unit entered, its\n * arguments admitted and its handlers started, all before anything is sent.\n */\nfunction executeMembers(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined\n): Promise<unknown[]> {\n const { driver } = engine;\n const native = !driver.supportsTransactions && driver.supportsBatch;\n if (!native) assertAtomicArraySupport(driver);\n const chain = engine.extensionChain;\n const coordination = chain?.coordination;\n // Observed members go through slots, but on a transaction driver only\n // where a part may intercept them; else each member's unit runs around\n // its own work, in order. Unobserved members, prepared already, only\n // where one is intercepted.\n return coordination &&\n (chain?.observation\n ? native || coordination.admit\n : coordination.intercepts?.(operations))\n ? executeSlots(\n operations,\n engine,\n options,\n context,\n batch,\n coordination,\n native\n )\n : native\n ? sendNativeBatch(operations, driver, options, context)\n : sendTransaction(operations, engine, options, context, batch);\n}\n\n/** One member of an observed or intercepted array. */\nexport interface ArraySlot {\n readonly operation: TransactionOperationCapability;\n readonly owner: TransactionOperationOwner<TransactionOperationCapability>;\n /** The core's result, which the member's handlers resume with. */\n readonly child: ArrayDeferred<unknown>;\n /** The member's handlers: its value as its caller receives it. */\n query?: Promise<unknown>;\n notifications?: WriteOutcomeNotifications;\n certainty?: WriteOutcome[\"certainty\"];\n admissionFailures?: unknown[];\n}\n\nasync function executeSlots(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n coordination: Coordination,\n native: boolean\n): Promise<unknown[]> {\n const { driver } = engine;\n // The array's scope, made before its members are admitted, which stage in it.\n const scope = scopeOf(engine, batch ?? {});\n const slots = operations.map(\n (operation): ArraySlot => ({\n operation,\n owner: transactionOperationOwner(operation),\n child: createArrayDeferred(),\n })\n );\n // Each member's unit starts before any member is prepared, and the array\n // waits until every unit reached its child: a handler that waits first\n // (for a tracer to load) does so before the array's work, which then runs\n // inside each member's unit, until its handlers settled.\n const units = await engine.extensionChain?.observation?.members(\n slots.map((slot) => [\n { ...slot.owner.unit(slot.operation), certainty: () => slot.certainty },\n () =>\n slot.child.promise.then(nothing, nothing).then(() => memberValue(slot)),\n ])\n );\n try {\n for (const slot of slots) slot.owner.reserveWith(slot.operation, driver);\n for (const phase of [\"input\", \"plan\"] as const)\n for (const slot of slots)\n await slot.owner.observeBatchPhase(slot.operation, driver, () =>\n slot.owner.prepareAdmission(slot.operation, phase)\n );\n } catch (error) {\n for (const slot of slots) slot.child.reject(error);\n throw error;\n }\n const failures = await coordination.admit?.(slots, scope);\n if (failures !== undefined)\n throw combineArrayFailures(failures[0], failures.slice(1));\n let values: unknown[];\n try {\n values = await (native\n ? sendNativeBatch(\n operations,\n driver,\n options,\n context,\n slots,\n scope,\n batch\n )\n : sendTransaction(\n operations,\n engine,\n options,\n context,\n batch,\n slots,\n scope\n ));\n } catch (failure) {\n // A transaction that failed before a member ran still lets that\n // member's handlers and unit end.\n for (const slot of slots) slot.child.reject(failure);\n throw failure;\n }\n // What a member's unit handler threw, once its child succeeded, fails the\n // array: the host contains nothing a handler does.\n await units?.done;\n return values;\n}\n\n/** The members in order inside one transaction, or a savepoint. */\nfunction sendTransaction(\n operations: TransactionOperationCapability[],\n engine: QueryEngine,\n options: ArrayOptions,\n context: QueryExecutionContext,\n batch: ArrayCertainty | undefined,\n slots?: ArraySlot[],\n scope?: TransactionScope\n): Promise<unknown[]> {\n const results: unknown[] = operations;\n const body = async (transactionDriver: AnyDriver): Promise<unknown[]> => {\n for (let index = 0; index < operations.length; index += 1) {\n const operation = operations[index]!;\n const slot = slots?.[index];\n if (slot === undefined) {\n results[index] = await transactionOperationOwner(operation).executeWith(\n operation,\n transactionDriver\n );\n continue;\n }\n // The reserved execution turns what its core throws into a rejection.\n slot.owner\n .executeCore(operation, transactionDriver, slot.notifications)\n .then(slot.child.resolve, slot.child.reject);\n try {\n results[index] = await memberValue(slot);\n } catch (failure) {\n // The members after a failed one never run: their handlers resume\n // with its failure before the rollback, which fails with it.\n await settleSlots(slots!.slice(index + 1), [failure]);\n }\n }\n return results;\n };\n return transact(engine, options, context, body, scope, batch);\n}\n\n/** The members prepared in order and sent as one native batch. */\nasync function sendNativeBatch(\n operations: TransactionOperationCapability[],\n driver: AnyDriver,\n options: ArrayOptions,\n context: QueryExecutionContext,\n slots?: ArraySlot[],\n scope?: TransactionScope,\n batch?: ArrayCertainty\n): Promise<unknown[]> {\n // Slots were reserved before they were admitted.\n if (slots === undefined)\n for (const operation of operations)\n transactionOperationOwner(operation).reserveWith(operation, driver);\n // What the sent batch reached, reported to every unit and published once,\n // and what publishing it failed with.\n let reached: WriteOutcome[\"certainty\"] | undefined;\n const late: unknown[] = [];\n const publish = async (certainty: WriteOutcome[\"certainty\"]) => {\n if (reached) return;\n reached = certainty;\n if (batch) batch.certainty = certainty;\n for (const slot of slots!) {\n slot.certainty = certainty;\n try {\n // Only a write's handlers are handed notifications.\n await slot.notifications?.[\n certainty === \"committed\" ? \"committed\" : \"mayHaveCommitted\"\n ]();\n } catch (error) {\n late.push(error);\n }\n }\n try {\n await scope?.outcomes?.publish(certainty);\n } catch (error) {\n late.push(error);\n }\n };\n // The failure to throw: every slot settled, it rejects with the folded one.\n const close = async (failure: unknown, sent?: true): Promise<unknown> => {\n if (slots === undefined) return failure;\n if (sent) await publish(\"may-have-committed\");\n await settleSlots(\n slots,\n [reached ? markCommitCertainty(failure, reached) : failure],\n late\n );\n };\n let queries: BatchQuery[];\n let guards: PreparedBatchGuard[];\n let parsers: BatchParser[];\n try {\n ({ queries, guards, parsers } = await prepareNativeBatch(\n operations,\n driver\n ));\n } catch (error) {\n throw await close(error);\n }\n let batchResults: QueryResult<unknown>[];\n try {\n batchResults = await executeNativeBatch(\n driver,\n queries,\n guards,\n options,\n context,\n slots && driver.supportsOrderedCommittedSegments\n ? () => publish(\"committed\")\n : undefined\n );\n if (slots) await publish(\"committed\");\n assertNativeBatchResults(driver, batchResults, queries.length);\n } catch (error) {\n throw await close(error, true);\n }\n const results: unknown[] = operations;\n for (let index = 0; index < parsers.length; index += 1) {\n const slot = slots?.[index];\n if (slot === undefined)\n results[index] = await parsers[index]!(batchResults);\n else\n try {\n slot.child.resolve(await parsers[index]!(batchResults));\n } catch (error) {\n slot.child.reject(markCommitCertainty(error, \"committed\"));\n }\n }\n if (slots)\n await settleSlots(\n slots,\n [],\n late.map((error) => markCommitCertainty(error, \"committed\")),\n results\n );\n return results;\n}\n\nconst nothing = (): undefined => undefined;\n\n/** The member's value as its handlers return it, or its core's before they start. */\nexport function memberValue(\n slot: Pick<ArraySlot, \"query\" | \"child\">\n): Promise<unknown> {\n return slot.query ?? slot.child.promise;\n}\n\n/**\n * Wait for every member's handlers, each child still unsettled rejected\n * with the first of `failures`, their values written into `values`; then\n * fail with the first failure, the distinct others and `extra` folded in.\n */\nexport async function settleSlots(\n slots: readonly ArraySlot[],\n failures: unknown[],\n extra: readonly unknown[] = [],\n values: unknown[] = []\n): Promise<void> {\n for (const slot of slots) slot.child.reject(failures[0]);\n for (const [index, settled] of (\n await Promise.allSettled(slots.map(memberValue))\n ).entries())\n if (settled.status === \"fulfilled\") values[index] = settled.value;\n else failures.push(settled.reason);\n failures.push(...extra);\n if (failures.length > 0)\n throw combineArrayFailures(failures[0], failures.slice(1));\n}\n\n/** The primary failure, with the distinct ones that settled beside it. */\nexport function combineArrayFailures(\n primary: unknown,\n suppressed: readonly unknown[]\n): unknown {\n const distinct = suppressed.filter((failure) => failure !== primary);\n if (distinct.length === 0) return primary;\n return new AggregateError(\n [primary, ...distinct],\n \"Array transaction and operation post-work both failed.\",\n { cause: primary }\n );\n}\n\n/** An error of viborm's own marked with the array's commit certainty. */\nfunction markCommitCertainty(\n error: unknown,\n certainty: WriteOutcome[\"certainty\"]\n): unknown {\n return isVibORMError(error) ? attachCommitCertainty(error, certainty) : error;\n}\n\nexport interface ArrayDeferred<Value> {\n readonly promise: Promise<Value>;\n readonly resolve: (value: Value) => void;\n readonly reject: (reason: unknown) => void;\n}\n\n/** A promise settled from outside; the first settlement holds. */\nexport function createArrayDeferred<Value>(): ArrayDeferred<Value> {\n // Promise executors run synchronously; TypeScript does not model that guarantee.\n let resolve!: (value: Value) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<Value>((ok, fail) => {\n resolve = ok;\n reject = fail;\n });\n promise.catch(nothing);\n return { promise, resolve, reject };\n}\n\n/** Prepare members in order into one native batch with per-member parsers. */\nexport async function prepareNativeBatch(\n operations: readonly TransactionOperationCapability[],\n driver: AnyDriver\n): Promise<{\n readonly queries: BatchQuery[];\n readonly guards: PreparedBatchGuard[];\n readonly parsers: BatchParser[];\n}> {\n const queries: BatchQuery[] = [];\n const guards: PreparedBatchGuard[] = [];\n const parsers: BatchParser[] = [];\n for (const operation of operations) {\n const owner = transactionOperationOwner(operation);\n const preparation = await owner.observeBatchPhase(\n operation,\n driver,\n async () => {\n const prepared = owner.prepare(operation, driver);\n if (prepared) return { prepared };\n return { preparedBatch: await owner.prepareBatch(operation) };\n }\n );\n const start = queries.length;\n if (preparation.prepared) {\n queries.push(preparation.prepared);\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () => {\n const result = batchResults[start];\n if (!result)\n throw arrayError(\n driver,\n `omitted the result for operation \"${owner.operation(operation)}\"`,\n { operation: owner.operation(operation) }\n );\n return owner.parseResult(operation, result);\n })\n );\n continue;\n }\n const { preparedBatch } = preparation;\n if (!preparedBatch) throw unbatchableArrayError(driver);\n const length = preparedBatch.queries.length;\n for (const query of preparedBatch.queries) queries.push(query);\n for (const guard of preparedBatch.guards ?? []) {\n guards.push({ ...guard, queryIndex: start + guard.queryIndex });\n }\n parsers.push((batchResults) =>\n owner.observeBatchPhase(operation, driver, () =>\n preparedBatch.parseResult(batchResults.slice(start, start + length))\n )\n );\n }\n return { queries, guards, parsers };\n}\n\nexport async function executeNativeBatch(\n driver: AnyDriver,\n queries: BatchQuery[],\n guards: PreparedBatchGuard[],\n options: ArrayOptions,\n context: QueryExecutionContext,\n committed?: () => Promise<void>\n): Promise<QueryResult<unknown>[]> {\n // The driver answers an empty batch itself, without sending it.\n try {\n return await driver._executeBatch(\n queries,\n options as BatchTransactionOptions | undefined,\n context,\n committed\n );\n } catch (error) {\n throw await attributeOperationBatchError(error, guards, driver, queries);\n }\n}\n\nexport function assertNativeBatchResults(\n driver: AnyDriver,\n results: QueryResult<unknown>[],\n queryCount: number\n): void {\n assertNormalizedBatchResults(results, queryCount, {\n provider: driver.driverName,\n operation: \"$transaction([...])\",\n });\n}\n\nexport function assertAtomicArraySupport(driver: AnyDriver): void {\n if (driver.supportsTransactions || driver.supportsBatch) return;\n throw arrayError(\n driver,\n \"supports neither transactions nor atomic batch execution\"\n );\n}\n\nexport function unbatchableArrayError(driver: AnyDriver): TransactionError {\n return arrayError(\n driver,\n \"does not support callback transactions and this transaction contains operations that cannot be batched atomically\"\n );\n}\n\nfunction arrayError(\n driver: AnyDriver,\n problem: string,\n meta: Record<string, unknown> = { method: \"$transaction([...])\" }\n): TransactionError {\n return new TransactionError(`Driver \"${driver.driverName}\" ${problem}.`, {\n meta: { driver: driver.driverName, ...meta },\n });\n}\n\nfunction assertOwnedOperations(\n candidates: unknown[],\n engine: QueryEngine\n): asserts candidates is TransactionOperationCapability[] {\n for (const candidate of candidates) {\n if (candidate === null || typeof candidate !== \"object\") {\n throw new InvalidTransactionInputError();\n }\n const owner = readTransactionOperation(candidate);\n if (owner === undefined) throw new InvalidTransactionInputError();\n if (owner.clientId(candidate) !== engine.clientId) {\n throw PendingOperationError.clientMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n if (owner.scopeId(candidate) !== engine.scopeId) {\n throw PendingOperationError.scopeMismatch(\n owner.model(candidate),\n owner.operation(candidate)\n );\n }\n }\n}\n","/**\n * Where a call's words find what they read: a first moment's context and a\n * second moment's `run` carry the call (`CALL`), a method's scope carries its\n * view (`SCOPE`). Symbols, so a call, a run or a scope shows them to the words\n * that import this module and to nothing else.\n */\nimport type { QueryExecutionContext } from \"@drivers/types\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport type { PreparedOperation } from \"@query-engine/raptor3/commands\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Seconds } from \"./call\";\nimport type { Attempt, WriteOutcomeRegistration } from \"./query\";\nimport type { Watched } from \"./watch-part\";\n\n/** The key of the call a first moment's context and a `run` belong to. */\nexport const CALL = Symbol(\"viborm.call\");\n/** The key of the view a method's scope serves. */\nexport const SCOPE = Symbol(\"viborm.scope\");\n/** The key of what a second moment's `run` started, which `again` and `via` read. */\nexport const ATTEMPT = Symbol(\"viborm.attempt\");\n\n/**\n * One call, as its words and its parts read it: a model call's own object, a\n * raw statement's resolved query. Each part that keeps something for the\n * call writes its own field, and only it reads that field: what it keeps\n * lives as long as the call, never on a chain or a part, which outlive it.\n */\nexport interface CallOrigin {\n /** The arguments of the extensions the call admitted. */\n readonly values?: AdmittedArgs;\n /** Set once the call is an operation of an engine: absent on a raw statement. */\n of?: {\n readonly engine: QueryEngine;\n readonly context: QueryExecutionContext;\n /** The call prepared once: what runs is this preparation. */\n readonly prepared: () => PreparedOperation;\n };\n /** `around` (`call.ts`): what each part's first moment left its second. */\n seconds?: Seconds;\n /** `watch` and `settled` on a model call (`watch-part.ts`): per extension. */\n watched?: Watched;\n /** `settled` on a raw statement, in an `around`'s first moment (`call.ts`). */\n told?: WriteOutcomeRegistration[];\n}\n\n/** The view one extension's method scope serves. */\ninterface ScopeOrigin {\n readonly engine: QueryEngine;\n readonly extension: string;\n}\n\n// Only this module and the core write these keys: what they hold is what\n// the core put there.\nconst isCall = <T = CallOrigin>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null;\nconst isScope = (value: unknown): value is ScopeOrigin =>\n typeof value === \"object\" && value !== null && \"engine\" in value;\n\n/** The call a first moment's context or a `run` belongs to, if it has one. */\nexport function callOf(x: object): CallOrigin | undefined {\n const call: unknown = Reflect.get(x, CALL);\n return isCall(call) ? call : undefined;\n}\n\n/**\n * What a second moment's `run` started: every `run` the host hands carries\n * it, and a forged one is not guarded against (D6).\n */\nexport function attemptOf(run: object): Attempt {\n return Reflect.get(run, ATTEMPT);\n}\n\n/** The view a method's scope serves, if `x` is one. */\nexport function scopeOf(x: object): ScopeOrigin | undefined {\n const scope: unknown = Reflect.get(x, SCOPE);\n return isScope(scope) ? scope : undefined;\n}\n\n/** The engine a call, a run or a scope works on. */\nexport function engineOf(x: object): QueryEngine | undefined {\n return callOf(x)?.of?.engine ?? scopeOf(x)?.engine;\n}\n","import { attachCommitCertainty } from \"@drivers/driver-error-context\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport {\n isVibORMError,\n QueryError,\n retainWriteOutcomeFailure,\n VibORMError,\n} from \"@errors\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\nimport { errorCause, isError } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallHandler } from \"./chain\";\nimport { ATTEMPT, CALL, type CallOrigin } from \"./origin\";\n\nexport type CallMode = \"direct\" | \"transaction\" | \"array\";\n\nexport type RawQueryKind =\n | \"queryRaw\"\n | \"executeRaw\"\n | \"queryRawUnsafe\"\n | \"executeRawUnsafe\";\n\ntype RawQueryOperation = `$${RawQueryKind}`;\n\ninterface PreparedQueryContextBase<Input extends object> {\n readonly mode: CallMode;\n readonly input: Readonly<Input>;\n /**\n * One object per call, the same one its first moments were handed: what\n * links an `around` part's two moments.\n */\n readonly call?: CallOrigin;\n}\n\nexport interface PreparedModelQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: \"model\";\n readonly model: string;\n readonly operation: string;\n /**\n * The call's admitted arguments. A handler sees only its own extension's,\n * and only when that extension declares any.\n */\n readonly values?: AdmittedArgs;\n}\n\nexport interface PreparedRawQueryContext<Input extends object>\n extends PreparedQueryContextBase<Input> {\n readonly kind: RawQueryKind;\n readonly model: undefined;\n readonly operation: RawQueryOperation;\n}\n\n/** The prepared logical-operation facts safe for `around` parts to inspect. */\nexport type PreparedQueryContext<\n Input extends object = Record<string, unknown>,\n> = PreparedModelQueryContext<Input> | PreparedRawQueryContext<Input>;\n\nexport type WriteOutcome = Readonly<{\n certainty: \"committed\" | \"may-have-committed\";\n}>;\n\nexport type WriteOutcomeListener = (\n outcome: WriteOutcome\n) => unknown | Promise<unknown>;\n\nexport interface WriteOutcomeRegistration {\n readonly extension: string;\n readonly listener: WriteOutcomeListener;\n /**\n * What installs a transaction scope's collector, brought by the word that\n * registered (`settled`); absent, the scope's own, installed at its start\n * by a chain whose parts hear writes.\n */\n readonly collect?: typeof collect;\n /**\n * What tells a call's registrations of its outcome, brought by what\n * registered (`settled`, the part that watches writes): a chain where\n * nothing registers carries none of it.\n */\n readonly tell?: typeof tell;\n /** In a transaction: the call reached its outcome, so it is told at the scope's end. */\n ok?: true;\n}\n\nexport interface WriteOutcomeNotifications {\n readonly committed: () => Promise<void>;\n readonly mayHaveCommitted: () => Promise<void>;\n}\n\n/** A `run()` no second moment may make once it returned. */\nconst AFTER_RETURN = \"called run() after its second moment returned\";\n\n/** The child a handler chain runs: on the driver a handler chose, if any. */\ntype Child<Result> = (driver?: AnyDriver) => Promise<Result>;\n\n/** What one `around` part runs for a call: its second moment, handed `run` by the runner. */\nexport type AroundRunner = (\n prepared: PreparedQueryContext<object>,\n run: () => Promise<unknown>\n) => unknown;\n\n/** The `around` parts one call runs, the first applied outermost. */\nexport type AroundHandlers = readonly CallHandler<AroundRunner>[];\n\ntype Certainty = WriteOutcome[\"certainty\"];\n\n/** Private coordination hooks used only while array members await admission. */\nexport interface AdmissionHooks {\n readonly reportAdmissionFailure?: (failure: unknown) => void;\n readonly readCommitCertainty?: () => Certainty | undefined;\n}\n\n/** The child of a prepared call, told of the commits it reaches. */\ntype PreparedChild<Result> = (\n notifications?: WriteOutcomeNotifications,\n driver?: AnyDriver\n) => Promise<Result>;\n\n/**\n * Execute one prepared operation through its `around` parts and under what\n * its write registered.\n */\nexport function executePreparedQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration\n): Promise<Result> {\n // A context is prepared only for a call some `around` part wraps.\n const intercepted = context !== undefined;\n if (!(intercepted || registration)) return child();\n return isWrite || registration\n ? executeRegisteredQuery(\n context,\n arounds,\n child,\n isWrite,\n scope,\n hooks,\n registration,\n runArounds\n )\n : runArounds(\n context!,\n arounds,\n (driver) => child(undefined, driver),\n hooks?.readCommitCertainty,\n hooks?.reportAdmissionFailure\n );\n}\n\n/**\n * One write under what it registered (the registration a model write's\n * watches made, or the `settled` functions a raw statement's first moments\n * kept on it), around its `around` parts when `intercept` runs them, which\n * {@link executePreparedQuery} passes: a chain without `around` parts does\n * not carry their runner. Each commit the child reports is told (outside a\n * transaction, the certainty it reached is what `again` reads), and a write\n * that succeeded without reporting one is told it committed.\n */\nexport function executeRegisteredQuery<Result, Input extends object>(\n context: PreparedQueryContext<Input> | undefined,\n arounds: AroundHandlers | undefined,\n child: PreparedChild<Result>,\n isWrite: boolean,\n scope?: TransactionScope,\n hooks?: AdmissionHooks,\n registration?: WriteOutcomeRegistration,\n intercept?: typeof runArounds\n): Promise<Result> {\n const registrations = registration ? [registration] : context?.call?.told;\n const told = registrations?.[0]?.tell?.(registrations, scope);\n let reported = false;\n let certainty: Certainty | undefined;\n const notified = (reached: Certainty) => async (): Promise<void> => {\n reported = true;\n if (!scope) certainty = reached;\n await told?.(reached);\n };\n const notifications: WriteOutcomeNotifications = {\n committed: notified(\"committed\"),\n mayHaveCommitted: notified(\"may-have-committed\"),\n };\n // What fails before its outcome is reached is never marked, so never told.\n const executeChild = async (driver?: AnyDriver): Promise<Result> => {\n const value = await child(notifications, driver);\n if (isWrite && !reported) await notifications.committed();\n return value;\n };\n return intercept && context && arounds?.length\n ? intercept(\n context,\n arounds,\n executeChild,\n () => certainty ?? hooks?.readCommitCertainty?.(),\n hooks?.reportAdmissionFailure\n )\n : executeChild();\n}\n\n/**\n * Run one already-compiled part chain around one prepared child, the\n * first handler outermost.\n *\n * The undefined/empty branch deliberately returns the child's promise directly:\n * unextended operations allocate no runner promise, context, closure, or list.\n */\nexport function runArounds<Result, Input extends object>(\n context: PreparedQueryContext<Input>,\n arounds: AroundHandlers | undefined,\n child: Child<Result>,\n readCommitCertainty?: () => Certainty | undefined,\n reportAdmissionFailure?: (failure: unknown) => void\n): Promise<Result> {\n const at = (index: number, driver?: AnyDriver): Promise<Result> => {\n const part = arounds?.[index];\n return part === undefined\n ? child(driver)\n : runAround(\n context,\n part,\n (chosen) => at(index + 1, chosen ?? driver),\n readCommitCertainty,\n reportAdmissionFailure,\n () => child(driver)\n );\n };\n return at(0);\n}\n\n/**\n * One `run` of one `around` part, as the words that read it find it\n * (`again`, `via`): what may start the child, and what happened to it.\n */\nexport interface Attempt {\n /** `run()` may start the child. */\n open: boolean;\n /** The child's last start failed. */\n failed: boolean;\n /** The second moment returned. */\n done: boolean;\n /** A direct call outside a transaction and an array. */\n readonly direct: boolean;\n /** A direct read: what `via` may run on another driver. */\n readonly routable: boolean;\n readonly certainty: (() => Certainty | undefined) | undefined;\n readonly start: (driver?: AnyDriver) => Promise<unknown>;\n}\n\n/**\n * One handler around its child. Once the child ran, its failure is the\n * call's, whatever the handler returns or throws after it; a handler that\n * breaks the protocol fails the call with that refusal once the child\n * succeeded.\n */\nasync function runAround<Result, Input extends object>(\n prepared: PreparedQueryContext<Input>,\n part: CallHandler<AroundRunner>,\n child: Child<Result>,\n readCommitCertainty: (() => Certainty | undefined) | undefined,\n reportAdmissionFailure: ((failure: unknown) => void) | undefined,\n core: () => Promise<Result>\n): Promise<Result> {\n const { extension } = part;\n const direct = prepared.mode === \"direct\";\n const routable =\n direct && prepared.kind === \"model\" && isReadOperation(prepared.operation);\n // A direct read may run once more after its handler returned (a value\n // served now and refreshed later): that run is the core's alone.\n let replayable = routable;\n let running: Promise<Result> | undefined;\n let protocolFailure: QueryError | undefined;\n const refuse = (failure: string): QueryError => {\n if (protocolFailure === undefined) {\n protocolFailure = aroundError(extension, prepared, failure);\n reportAdmissionFailure?.(protocolFailure);\n }\n return protocolFailure;\n };\n const attempt: Attempt = {\n open: true,\n failed: false,\n done: false,\n direct,\n routable,\n certainty: readCommitCertainty,\n start(driver) {\n if (!attempt.open) throw refuse(\"called run() more than once\");\n if (attempt.done) throw refuse(AFTER_RETURN);\n attempt.open = false;\n attempt.failed = false;\n // What the child throws, even at once, is its promise's rejection.\n running = (async () => child(driver))();\n // Attached first, so a handler's own `catch` already reads it.\n running.then(undefined, () => {\n attempt.failed = true;\n });\n return running;\n },\n };\n const run = Object.defineProperties(\n (): Promise<unknown> => {\n if (!attempt.done) return attempt.start();\n if (!replayable) throw refuse(AFTER_RETURN);\n replayable = false;\n return (async () => core())();\n },\n {\n // Read when asked: the context snapshots the input the first time.\n input: { get: () => prepared.input },\n mode: { value: prepared.mode },\n [CALL]: { value: prepared.kind === \"model\" ? prepared.call : undefined },\n [ATTEMPT]: { value: attempt },\n }\n );\n let outcome: { readonly value: Result } | { readonly reason: unknown };\n try {\n outcome = {\n // A second moment answers the call: `around`'s types hold its value\n // to the call's result.\n value: (await part.handler(prepared, run)) as Result,\n };\n } catch (reason) {\n outcome = { reason };\n }\n attempt.done = true;\n const failure =\n \"reason\" in outcome &&\n (protocolFailure === undefined || outcome.reason !== protocolFailure)\n ? aroundFailure(\n extension,\n prepared,\n outcome.reason,\n readCommitCertainty?.()\n )\n : undefined;\n if (running === undefined) {\n if (failure !== undefined) throw failure;\n if (\n prepared.mode === \"array\" ||\n prepared.kind !== \"model\" ||\n !isReadOperation(prepared.operation)\n )\n throw aroundError(extension, prepared, \"returned without run()\");\n } else {\n if (failure !== undefined && !attempt.failed)\n reportAdmissionFailure?.(failure);\n await running;\n }\n if (\"value\" in outcome && protocolFailure === undefined) return outcome.value;\n throw protocolFailure ?? failure;\n}\n\nfunction aroundFailure<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n reason: unknown,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): Error {\n if (isError(reason)) return reason;\n return aroundError(\n extension,\n context,\n \"failed\",\n errorCause(reason),\n commitCertainty\n );\n}\n\nfunction aroundError<Input extends object>(\n extension: string,\n context: PreparedQueryContext<Input>,\n failure: string,\n cause?: Error,\n commitCertainty?: WriteOutcome[\"certainty\"]\n): QueryError {\n return new QueryError(\n `Extension \"${extension}\" around() for ${context.kind === \"model\" ? `${context.model}.${context.operation}` : context.operation} ${failure}.`,\n {\n ...(cause && { cause }),\n meta: {\n method: \"around\",\n model: context.model,\n operation: context.operation,\n ...(commitCertainty === undefined ? {} : { commitCertainty }),\n },\n }\n );\n}\n\n/**\n * The collector of one transaction scope: the registrations its calls\n * staged, each told at the scope's end if its call reached its outcome.\n */\nexport class TransactionWriteOutcomes {\n readonly staged: WriteOutcomeRegistration[] = [];\n\n /** Tell what reached its outcome; a native batch's scope ends so. */\n publish(certainty: Certainty): Promise<void> {\n return publishWriteOutcomes(\n this.staged.filter((registration) => registration.ok),\n { certainty }\n );\n }\n\n /**\n * End the scope this collects for, with what its transaction settled\n * with. A savepoint that commits hands what it collected to its parent's\n * collector, which owns the decision; the outermost publishes it after\n * its commit, or, when its commit failed after COMMIT was sent, with the\n * certainty reached, which the failure then carries.\n */\n async end<T>(\n { parent, root }: TransactionScope,\n settled: T,\n failed?: true\n ): Promise<T> {\n if (!failed) {\n if (parent)\n collect(parent).staged.push(\n ...this.staged.filter((registration) => registration.ok)\n );\n else await this.publish(\"committed\");\n return settled;\n }\n const { certainty } = root;\n if (parent || certainty === undefined) throw settled;\n const primary = isVibORMError(settled)\n ? attachCommitCertainty(settled, certainty)\n : settled;\n try {\n await this.publish(certainty);\n } catch (outcomeFailure) {\n throw retainWriteOutcomeFailure(primary, outcomeFailure);\n }\n throw primary;\n }\n}\n\n/**\n * One transaction scope, as `transact` (`coordination.ts`) runs it: what its\n * calls register waits in it until it ends. The scope holds no code: the\n * first registration installs the collector (`collect`), which brings the\n * code that ends the scope, so a transaction where nothing registers runs\n * none of it.\n */\nexport interface TransactionScope {\n /** The scope this one is a savepoint of. */\n readonly parent: TransactionScope | undefined;\n /** The outermost scope's commit phase, as its driver reports it. */\n readonly root: CommitPhase;\n outcomes?: TransactionWriteOutcomes;\n}\n\n/** How far a transaction's commit went; nothing before COMMIT was sent. */\nexport interface CommitPhase {\n certainty?: Certainty;\n}\n\n/** The collector of a transaction scope, installed by its first registration. */\nexport function collect(scope: TransactionScope): TransactionWriteOutcomes {\n scope.outcomes ??= new TransactionWriteOutcomes();\n return scope.outcomes;\n}\n\n/**\n * What tells one call's registrations of the commits it reaches: inside a\n * transaction, each is staged in the scope and marked once the call reached\n * its outcome, told when the scope ends; outside one, each commit is told.\n */\nexport function tell(\n registrations: readonly WriteOutcomeRegistration[],\n scope: TransactionScope | undefined\n): (certainty: Certainty) => Promise<void> {\n if (scope === undefined)\n return (certainty) => publishWriteOutcomes(registrations, { certainty });\n for (const registration of registrations)\n (registration.collect?.(scope) ?? scope.outcomes)?.staged.push(\n registration\n );\n return async () => {\n for (const registration of registrations) registration.ok = true;\n };\n}\n\n/**\n * Deliver every registered listener in registration order, all of them. The\n * first fault rejects: an error of viborm's own as it is, any other value as\n * the cause of a `QueryError`; later faults are lost.\n */\nexport async function publishWriteOutcomes(\n registrations: readonly WriteOutcomeRegistration[],\n outcome: WriteOutcome\n): Promise<void> {\n let first: unknown;\n for (const { extension, listener } of registrations) {\n try {\n await listener(outcome);\n } catch (reason) {\n first ??=\n reason instanceof VibORMError\n ? reason\n : new QueryError(\n `Extension \"${extension}\" settled() failed (${outcome.certainty}).`,\n {\n cause: errorCause(reason),\n meta: {\n method: \"settled\",\n commitCertainty: outcome.certainty,\n },\n }\n );\n }\n }\n if (first) throw first;\n}\n","/**\n * The `admit` hooks of a chain whose parts concern a member of\n * `$transaction([...])`. Where `around` parts may wrap a member, before the\n * one executor (`@client/array-transaction`) sends anything, every member's\n * handlers start and the array waits until each reached `run()` or failed: a\n * refusal, a second `run()`, a late detached one or a handler that throws\n * aborts the array, and nothing is sent. Where parts only hear a member's\n * writes, nothing waits: each member's registration is staged and its child\n * handed what tells it of the commit (`stageArray`).\n */\nimport {\n type ArraySlot,\n createArrayDeferred,\n memberValue,\n} from \"@client/array-transaction\";\nimport {\n type TransactionOperationCapability,\n transactionOperationOwner,\n} from \"@query-engine/transaction-operation\";\nimport {\n type AdmissionHooks,\n type executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n type WriteOutcomeNotifications,\n} from \"./query\";\n\n/** What admission reads and writes of a slot. */\nexport type AdmissionSlot = Omit<ArraySlot, \"operation\" | \"owner\">;\n\n/** Whether a part intercepts one of the members, once they are prepared. */\nexport function interceptsArray(\n operations: readonly TransactionOperationCapability[]\n): boolean {\n return operations.some((operation) => {\n const { handlers, registration } =\n transactionOperationOwner(operation).around(operation);\n return handlers?.length || registration;\n });\n}\n\n/**\n * The hook of a chain whose parts hear writes and wrap no call: a member with\n * a registration runs under it, its child reached at once, so the array has\n * nothing to wait for. Its value is then the registration's run, whose\n * rejection the array reads in member order.\n */\nexport async function stageArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope\n): Promise<undefined> {\n for (const slot of slots) {\n const { write, registration } = slot.owner.around(slot.operation);\n if (registration === undefined) continue;\n const child = (notifications?: WriteOutcomeNotifications) => {\n slot.notifications = notifications;\n return slot.child.promise;\n };\n const query = executeRegisteredQuery(\n undefined,\n undefined,\n child,\n write,\n scope,\n undefined,\n registration\n );\n slot.query = query;\n // Read by the array in member order; one the array never reaches (it\n // failed before) is settled here.\n query.catch(ignore);\n }\n return undefined;\n}\n\nconst ignore = (): undefined => undefined;\n\n/**\n * The hook: each member's handlers started, in member order, by `execute`\n * (the chain's runner of a prepared call), which stages what it registered;\n * a member with nothing to intercept is admitted at once.\n */\nexport function admitArray(\n slots: readonly ArraySlot[],\n scope: TransactionScope,\n execute: typeof executePreparedQuery\n): Promise<readonly unknown[] | undefined> {\n const facts = slots.map((slot) => slot.owner.around(slot.operation));\n return admitArrayQueries(slots, (slot, child, hooks) => {\n const { context, handlers, write, registration } =\n facts[slots.indexOf(slot)]!;\n return handlers?.length || registration\n ? execute(context, handlers, child, write, scope, hooks, registration)\n : child();\n });\n}\n\n/**\n * Start every member's handlers and release the array only after each has\n * reached its child. On a failure, every child rejects with the first one,\n * and the distinct failures each member reported return in member order.\n */\nexport async function admitArrayQueries<Slot extends AdmissionSlot>(\n slots: readonly Slot[],\n start: (\n slot: Slot,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n hooks: AdmissionHooks\n ) => Promise<unknown>\n): Promise<readonly unknown[] | undefined> {\n let failed: { readonly failure: unknown } | undefined;\n let remaining = slots.length;\n const signal = createArrayDeferred<void>();\n if (remaining === 0) signal.resolve();\n\n for (const slot of slots) {\n const reportAdmissionFailure = (failure: unknown): void => {\n const failures = (slot.admissionFailures ??= []);\n if (!failures.includes(failure)) failures.push(failure);\n failed ??= { failure };\n signal.reject(failure);\n };\n let query: Promise<unknown>;\n try {\n query = start(\n slot,\n (notifications) => {\n slot.notifications = notifications;\n // Reached once: a second `run()` is refused before its child.\n remaining -= 1;\n if (remaining === 0) signal.resolve();\n return slot.child.promise;\n },\n {\n reportAdmissionFailure,\n readCommitCertainty: () => slot.certainty,\n }\n );\n } catch (error) {\n reportAdmissionFailure(error);\n query = Promise.reject(error);\n }\n slot.query = query;\n query.catch(reportAdmissionFailure);\n }\n\n try {\n await signal.promise;\n // A handler that fails in the turn its member was admitted still aborts.\n await Promise.resolve();\n if (failed) throw failed.failure;\n return undefined;\n } catch (failure) {\n for (const slot of slots) slot.child.reject(failure);\n await Promise.allSettled(slots.map(memberValue));\n const reported: unknown[] = [];\n for (const slot of slots)\n for (const failure of slot.admissionFailures ?? [])\n if (!reported.includes(failure)) reported.push(failure);\n return reported;\n }\n}\n","/**\n * What a part that wraps a call's execution brings beside its own state: how\n * a prepared call runs (under write-outcome registrations, under `around`\n * parts), and, for the parts an array member can be intercepted by, how the\n * one executor of `$transaction([...])` (`@client/array-transaction`)\n * admits its members. A chain of none of those parts carries none of it.\n *\n * And how every transaction scope runs (`transact`): what a call registers\n * there waits in its scope, and the first registration installs the\n * collector by value (`collect`, imported by what registers: `settled`, the\n * part that watches writes, `unit` parts), so an extension behaves the same\n * whatever else its chain holds, and a transaction where nothing registers\n * runs none of that code.\n */\nimport type { ArraySlot } from \"@client/array-transaction\";\nimport { appendExecutionTransactionPhases } from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { afterFulfilled } from \"@drivers/rejection-observed-promise\";\nimport type { TransactionOptions } from \"@drivers/shared/transaction-options\";\nimport type { QueryEngine } from \"@query-engine/query-engine\";\nimport { admitArray, interceptsArray, stageArray } from \"./array-admission\";\nimport {\n type CommitPhase,\n type collect,\n executePreparedQuery,\n executeRegisteredQuery,\n type TransactionScope,\n} from \"./query\";\n\n/** The commit certainty one array reports to its `batch` unit. */\nexport type ArrayCertainty = CommitPhase;\n\nexport interface Coordination {\n /** What it adds to the one before it: a chain keeps the highest it needs. */\n readonly rank: number;\n /**\n * Where its parts hear writes: the collector installed in each transaction\n * scope from its start, so the scope's failure carries its commit\n * certainty even when nothing registered.\n */\n readonly collect?: typeof collect;\n /**\n * What runs a prepared call under the chain's `around` parts and what it\n * registered: absent where neither exists (`unit` parts alone), since\n * core asks it only of a call that has handlers or a registration.\n */\n readonly executePreparedQuery?: typeof executePreparedQuery;\n /** Present with `admit`: whether a part intercepts one of the members. */\n readonly intercepts?: typeof interceptsArray;\n /**\n * Present where a member of `$transaction([...])` may be intercepted:\n * starts every member's handlers and waits until each reached `run()`,\n * before anything is sent. Resolves to the failures that abort the array.\n */\n readonly admit?: (\n slots: readonly ArraySlot[],\n scope: TransactionScope\n ) => ReturnType<typeof admitArray>;\n}\n\n/**\n * For `unit` parts: nothing of the chain wraps a call, the prepared call\n * runs as it is.\n */\nexport const UNITS: Coordination = { rank: -1 };\n\n/**\n * For the part that watches writes: an array member it hears runs under its\n * registration, and nothing waits, since no handler wraps it.\n */\nexport const ARRAYS: Coordination = {\n rank: 1,\n executePreparedQuery: executeRegisteredQuery,\n intercepts: interceptsArray,\n admit: stageArray,\n};\n\n/** For `around` parts: what runs their second moments around a call, too. */\nexport const QUERIES: Coordination = {\n rank: 2,\n executePreparedQuery,\n intercepts: interceptsArray,\n admit: (slots, scope) => admitArray(slots, scope, executePreparedQuery),\n};\n\n/**\n * The chain being built coordinated as `needed` asks, never less than it\n * was; `collect` is kept whatever the rank.\n */\nexport function coordinate(\n next: { coordination?: Coordination; collect?: typeof collect },\n needed: Coordination,\n collects?: typeof collect\n): void {\n if (collects) next.collect = collects;\n if (next.coordination === undefined || needed.rank > next.coordination.rank)\n next.coordination = needed;\n}\n\n/**\n * Run one transaction scope. A savepoint's scope is a child of its parent's;\n * the outermost one hears its commit phases where a part may register, for\n * the certainty of what was registered in it. What its calls register installs\n * the collector that ends it (`TransactionWriteOutcomes.end`). A body run\n * again (a driver that reruns a callback on a conflict) gets a scope of its\n * own: nothing the failed run registered is told. An array's scope is made\n * before its members are admitted, and passed.\n */\nexport function transact<T>(\n engine: QueryEngine,\n options: TransactionOptions | undefined,\n context: QueryExecutionContext,\n body: (driver: AnyDriver, scope: TransactionScope) => Promise<T>,\n made?: TransactionScope,\n root: CommitPhase = made?.root ?? {}\n): Promise<T> {\n const chain = engine.extensionChain;\n const parent = engine.transaction;\n let scope: TransactionScope | undefined;\n const end =\n (failed?: true) =>\n (settled: T): T | Promise<T> => {\n // A driver that reports no phase still committed what resolved.\n if (!(failed || parent)) root.certainty = \"committed\";\n if (!scope?.outcomes) {\n if (failed) throw settled;\n return settled;\n }\n // The promise this handler returns is taken a microtask later, and\n // workerd reports a rejection no handler holds by then.\n const ended = scope.outcomes.end(scope, settled, failed);\n ended.catch(() => undefined);\n return ended;\n };\n const ran = engine.driver.withTransaction(\n (driver) => {\n scope = made ?? scopeOf(engine, root);\n return body(driver, scope);\n },\n options,\n // Only where a part may register: a chain of `call` parts, rules or\n // defaults alone runs its transactions as an unextended client does.\n parent || !(chain?.coordination || chain?.methods)\n ? context\n : appendExecutionTransactionPhases(context, {\n readyToCommit: () => {\n root.certainty = \"may-have-committed\";\n },\n committed: () => {\n root.certainty = \"committed\";\n },\n })\n );\n // A savepoint that fails drops what it collected: no handler of its\n // rejection, which only the caller's own observes (an unobserved one fails\n // the outer transaction, and is reported there alone).\n return parent ? afterFulfilled(ran, end()) : ran.then(end(), end(true));\n}\n\n/**\n * A transaction scope inside `engine`'s, with the collector of a chain whose\n * parts hear writes installed from its start.\n */\nexport function scopeOf(\n engine: QueryEngine,\n root: CommitPhase\n): TransactionScope {\n const scope = { parent: engine.transaction, root };\n engine.extension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AE,GAAO,cAAgB,GAAO,SACtC,EACA,EAAiC,EAAS,CACxC,kBAAqB,CACnB,EAAK,UAAY,sBAEnB,cAAiB,CACf,EAAK,UAAY,aAEpB,CAAC,CACP,CAID,OAAO,EAAS,EAAe,EAAK,KAAK,CAAC,CAAG,EAAI,KAAK,KAAK,CAAE,IAAI,GAAK,CAAC,CAOzE,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAQ,CAAE,OAAQ,EAAO,YAAa,OAAM,CAElD,OADA,EAAO,gBAAgB,UAAU,EAAM,CAChC"}
|
package/dist/d1.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryResult, C as DriverResultParser, Qa as QueryExecutionContext, Xa as CommittedBatchNotification, Ya as BatchQuery, b as SqliteMigrationCapability, h as Driver, li as Schema, pt as VibORMClient, qa as TransactionOptionSupport, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, xi as LinkedClientConfig } from "./database-adapter-D62c-uC6.mjs";
|
|
2
2
|
import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/d1/index.d.ts
|
package/dist/d1.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{h as t}from"./error-mapping-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{h as t}from"./error-mapping-DIRlrmDK.mjs";import{p as n}from"./validation--qS7OPmg.mjs";import{i as r,n as i}from"./normalized-result-B8pifWS0.mjs";import{t as a}from"./bind-parameter-capacity-BMD-bxMO.mjs";import{d as o,n as s,p as c}from"./client-CVCC-D1j.mjs";import{r as l}from"./provider-parameter-snapshot-C0ehKSAA.mjs";import{c as u,r as d,t as f}from"./driver-Df88hu4U.mjs";import{l as p,o as m,r as h}from"./sqlite-utils-DcQct689.mjs";import{n as g,t as _}from"./sqlite-statement-classifier-BAHl-WXS.mjs";import{t as v}from"./sqlite-adapter-fIbNDvwO.mjs";const y={database:!0};function convertD1Parameters(e){return h(e).map(e=>typeof e==`bigint`?e.toString():e)}const b=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let r=e.operation??`execute`;return new n(`Driver "d1" returned a malformed result payload for operation "${r}": ${t}.`,{meta:{driver:`d1`,...e,operation:r}})}function assertD1BindingResult(e,t){if(!r(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(r))||!r(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&b.has(i)||_(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=g(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var x=class D1Driver extends d{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new v({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256,countsCascadedChanges:!0});maxBindParametersPerStatement=100;result=p;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;sqliteMigrationCapability=f;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,c(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,n,r)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,n,r);return i(a,{provider:this.driverName,operation:r.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(n),s=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(s)?s:[],u=c??[];if(!(Array.isArray(s)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(r,`the positional rows are malformed`);return o(l,u,{provider:this.driverName,operation:r.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===p&&e.result.parseField===m&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){let i=n??[];return a({values:i},this.driverName,this.maxBindParametersPerStatement,`raw statement`),await this.executeStatement(e,t,i,r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,n){return Promise.reject(t(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},o=[];for(let n of t){let t=n.context??i;l(n)&&a({values:n.params??[]},this.driverName,this.maxBindParametersPerStatement,`raw statement`);try{let t=n.params?convertD1Parameters(n.params):[];o.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let s=await e.batch(o);if(await r?.(),!Array.isArray(s)||s.length!==t.length){let e=Array.isArray(s)?s.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let c=[];for(let e=0;e<s.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);c.push(normalizeD1Result(s[e],n.sql,n.context??i,!1))}return c}};function createClient(e){u(e,`d1`,y);let{database:t}=e;return s(e,new x({database:t}))}export{x as D1Driver,createClient};
|
|
2
2
|
//# sourceMappingURL=d1.mjs.map
|