viborm 1.14.2 → 1.16.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-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- 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 +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs.map +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.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 +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- 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/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.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/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-mapping-B9rSvgG9.mjs","names":["#values","#lazyCorrelationId","readProperty","trusted"],"sources":["../src/drivers/execution-context.ts","../src/errors/cache.ts","../src/errors/constraints.ts","../src/errors/record-series-progress.ts","../src/query-engine/types.ts","../src/errors/logged-errors.ts","../src/drivers/shared/transactions.ts","../src/drivers/driver-error-context.ts","../src/drivers/error-mapping.ts"],"sourcesContent":["import type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { QueryExecutionContext } from \"./types\";\n\ninterface TrustedExecutionContext {\n readonly cs?: string;\n readonly id?: string;\n readonly ig?: () => string;\n readonly ec?: ResolvedExtensionChain;\n readonly m?: string;\n readonly n?: boolean;\n readonly o?: string;\n readonly tp?: TransactionPhaseNotifications;\n readonly rc?: true;\n}\n\n/** Private exact transaction lifecycle facts attached only to trusted contexts. */\nexport interface TransactionPhaseNotifications {\n readonly readyToCommit: () => void;\n readonly committed: () => void;\n}\n\nclass TrustedSnapshot {\n readonly #values: TrustedExecutionContext;\n readonly model?: string;\n readonly operation: string | undefined;\n declare readonly correlationId?: string;\n declare readonly named?: boolean;\n static readonly #lazyCorrelationId: PropertyDescriptor = {\n configurable: false,\n enumerable: true,\n get(this: object) {\n return TrustedSnapshot.values(this)?.ig?.();\n },\n };\n constructor(values: TrustedExecutionContext) {\n this.#values = values;\n if (values.m) this.model = values.m;\n this.operation = values.o;\n if (values.ig)\n Object.defineProperty(\n this,\n \"correlationId\",\n TrustedSnapshot.#lazyCorrelationId\n );\n else this.correlationId = values.id || undefined;\n if (values.n !== undefined) this.named = values.n;\n Object.freeze(this);\n }\n static values(context: object): TrustedExecutionContext | undefined {\n return #values in context\n ? (context as TrustedSnapshot).#values\n : undefined;\n }\n}\nconst trusted = (context: object) => TrustedSnapshot.values(context);\nconst valuesOf = (context: QueryExecutionContext): TrustedExecutionContext =>\n trusted(context) ?? snapshotExternalExecutionContext(context);\nconst deriveContext = (\n context: QueryExecutionContext,\n patch: Partial<TrustedExecutionContext>\n): QueryExecutionContext =>\n createTrustedExecutionContext({ ...valuesOf(context), ...patch });\n\nexport function createExecutionContext(\n values: QueryExecutionContext,\n correlationIdFactory?: () => string,\n extensionChain?: ResolvedExtensionChain,\n callsite?: string\n): QueryExecutionContext {\n if (!correlationIdFactory) {\n return snapshotExecutionContext(\n values,\n undefined,\n undefined,\n extensionChain\n );\n }\n\n let correlationId: string | undefined;\n return createTrustedExecutionContext({\n cs: callsite,\n ig: () => (correlationId ??= correlationIdFactory()),\n ec: extensionChain,\n m: readString(values, \"model\"),\n n: readBoolean(values),\n o: readString(values, \"operation\"),\n });\n}\n\nexport function snapshotExecutionContext(\n context: QueryExecutionContext | undefined,\n boundContext?: QueryExecutionContext,\n fallbackOperation?: string,\n extensionChainOverride?: ResolvedExtensionChain\n): QueryExecutionContext {\n const tc = context ? trusted(context) : undefined;\n const cv = tc ?? snapshotExternalExecutionContext(context);\n const tb = boundContext ? trusted(boundContext) : undefined;\n const bv =\n context === boundContext\n ? cv\n : (tb ?? snapshotExternalExecutionContext(boundContext));\n const ig = cv.ig ?? (cv.id === undefined ? bv.ig : undefined);\n const next: TrustedExecutionContext = {\n cs: cv.cs ?? bv.cs,\n id: ig ? undefined : (cv.id ?? bv.id),\n ig,\n ec: cv.ec ?? bv.ec ?? extensionChainOverride,\n m: cv.m ?? bv.m,\n n: cv.n ?? bv.n,\n o: cv.o ?? bv.o ?? fallbackOperation,\n tp: cv.tp ?? bv.tp,\n ...((cv.rc ?? bv.rc) && { rc: true as const }),\n };\n\n if (context && tc && sameContext(tc, next)) return context;\n if (boundContext && tb && sameContext(tb, next)) return boundContext;\n return createTrustedExecutionContext(next);\n}\n\nexport function deriveRecoverableExecutionContext(\n context: QueryExecutionContext\n): QueryExecutionContext {\n return deriveContext(context, { rc: true });\n}\n\n/** Whether this trusted context's failure is recovered by its owner. */\nexport function isRecoverableExecution(\n context: QueryExecutionContext | undefined\n): boolean {\n return context !== undefined && trusted(context)?.rc === true;\n}\n\nexport function deriveStatementExecutionContext(\n context: QueryExecutionContext,\n model: string\n): QueryExecutionContext {\n return deriveContext(context, { m: model });\n}\n\n/**\n * A client view answers this symbol with its official instrumentation's\n * `diagnostics`: what `createMigrationClient` discloses through `$driver`.\n */\nexport const CLIENT_DIAGNOSTICS = Symbol(\"viborm.client.diagnostics\");\n\n/** Read only the chain attached by the trusted context owner. */\nexport function getExecutionExtensionChain(\n context: QueryExecutionContext | undefined\n): ResolvedExtensionChain | undefined {\n return context ? trusted(context)?.ec : undefined;\n}\n\n/** `value` as a trusted execution context, if it is one. */\nexport function trustedExecutionContext(\n value: object\n): QueryExecutionContext | undefined {\n return trusted(value) === undefined ? undefined : value;\n}\n\n/** The origin belongs to the exact deferred operation, never caller-spoofed metadata. */\nexport function getExecutionCallsite(\n context: QueryExecutionContext | undefined\n): string | undefined {\n return context ? trusted(context)?.cs : undefined;\n}\n\n/** Attach private lifecycle notifications without accepting caller-spoofed state. */\nexport function bindExecutionTransactionPhases(\n context: QueryExecutionContext,\n transactionPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n return deriveContext(context, { tp: transactionPhases });\n}\n\n/** Add one private lifecycle reader without replacing an existing consumer. */\nexport function appendExecutionTransactionPhases(\n context: QueryExecutionContext,\n appendedPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = valuesOf(context);\n const existing = values.tp;\n return createTrustedExecutionContext({\n ...values,\n tp:\n existing === undefined\n ? appendedPhases\n : {\n readyToCommit: () => {\n appendedPhases.readyToCommit();\n existing.readyToCommit();\n },\n committed: () => {\n appendedPhases.committed();\n existing.committed();\n },\n },\n });\n}\n\n/** Read lifecycle notifications only from a context created by this owner. */\nexport function getExecutionTransactionPhases(\n context: QueryExecutionContext | undefined\n): TransactionPhaseNotifications | undefined {\n return context ? trusted(context)?.tp : undefined;\n}\n\nfunction createTrustedExecutionContext(\n values: TrustedExecutionContext\n): QueryExecutionContext {\n return new TrustedSnapshot(values) as QueryExecutionContext;\n}\n\nfunction snapshotExternalExecutionContext(\n value: QueryExecutionContext | undefined\n): TrustedExecutionContext {\n return {\n id: readString(value, \"correlationId\"),\n m: readString(value, \"model\"),\n n: readBoolean(value),\n o: readString(value, \"operation\"),\n };\n}\n\nfunction sameContext(\n a: TrustedExecutionContext,\n b: TrustedExecutionContext\n): boolean {\n return (\n a.rc === b.rc &&\n a.n === b.n &&\n a.cs === b.cs &&\n a.m === b.m &&\n a.o === b.o &&\n a.id === b.id &&\n a.ig === b.ig &&\n a.ec === b.ec &&\n a.tp === b.tp\n );\n}\n\nfunction readString(\n value: QueryExecutionContext | undefined,\n key: keyof QueryExecutionContext\n): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readBoolean(\n value: QueryExecutionContext | undefined\n): boolean | undefined {\n const member = readProperty(value, \"named\");\n return typeof member === \"boolean\" ? member : undefined;\n}\n\nfunction readProperty(value: unknown, key: PropertyKey): unknown {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || !value) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n","import {\n coded,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"./base\";\n\n/**\n * Invalid TTL format or value\n */\nexport class CacheInvalidTTLError extends coded<\n typeof VibORMErrorCode.CACHE_INVALID_TTL,\n { meta?: VibORMErrorMeta }\n>(\"CacheInvalidTTLError\", VibORMErrorCode.CACHE_INVALID_TTL) {}\n\n/**\n * Invalid cache key (circular reference, uncacheable type)\n */\nexport class CacheInvalidKeyError extends coded<\n typeof VibORMErrorCode.CACHE_INVALID_KEY,\n { meta?: VibORMErrorMeta }\n>(\"CacheInvalidKeyError\", VibORMErrorCode.CACHE_INVALID_KEY) {}\n\n/**\n * Operation cannot be cached (e.g., mutation operations)\n */\nexport class CacheOperationNotCacheableError extends VibORMError {\n static override readonly diagnosticName = \"CacheOperationNotCacheableError\";\n\n /** Literal discriminant: this class always carries `CACHE_OPERATION_NOT_CACHEABLE`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE;\n\n constructor(\n operation: string,\n cacheableOperations: string[],\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `\"${operation}\" is not cacheable; reads only: ${cacheableOperations.join(\", \")}`,\n VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE,\n {\n meta: { ...options?.meta, operation },\n }\n );\n }\n}\n\n/**\n * Invalid or missing cache configuration (options or driver)\n */\nexport class CacheConfigurationError extends coded<\n typeof VibORMErrorCode.CACHE_CONFIGURATION,\n { cause?: Error | undefined; meta?: VibORMErrorMeta }\n>(\"CacheConfigurationError\", VibORMErrorCode.CACHE_CONFIGURATION) {}\n","import { coded, VibORMErrorCode } from \"./base\";\n\n/**\n * Unique constraint violation\n */\nexport class UniqueConstraintError extends coded<\n typeof VibORMErrorCode.UNIQUE_CONSTRAINT\n>(\"UniqueConstraintError\", VibORMErrorCode.UNIQUE_CONSTRAINT) {}\n\n/**\n * Foreign key constraint violation\n */\nexport class ForeignKeyError extends coded<\n typeof VibORMErrorCode.FOREIGN_KEY_CONSTRAINT\n>(\"ForeignKeyError\", VibORMErrorCode.FOREIGN_KEY_CONSTRAINT) {}\n\n/**\n * Not-null constraint violation\n */\nexport class NotNullConstraintError extends coded<\n typeof VibORMErrorCode.NOT_NULL_CONSTRAINT\n>(\"NotNullConstraintError\", VibORMErrorCode.NOT_NULL_CONSTRAINT) {}\n\n/**\n * Check constraint violation\n */\nexport class CheckConstraintError extends coded<\n typeof VibORMErrorCode.CHECK_CONSTRAINT\n>(\"CheckConstraintError\", VibORMErrorCode.CHECK_CONSTRAINT) {}\n\n/**\n * Value too long for the column's declared type (Prisma P2000)\n *\n * Raised where the database enforces a column length: PostgreSQL SQLSTATE 22001\n * (`string_data_right_truncation`) and MySQL errno 1406 (`ER_DATA_TOO_LONG`).\n *\n * **SQLite raises nothing comparable.** SQLite ignores declared type lengths entirely\n * (`VARCHAR(5)` stores any string), so an over-long value is written, not rejected; the only\n * related error, `SQLITE_TOOBIG`, fires at the ~1GB `SQLITE_MAX_LENGTH` limit and means a\n * different thing. Prisma behaves the same way — quaint's SQLite connector has no arm for it,\n * so it falls through to a generic query error rather than P2000\n * (`quaint/src/connector/sqlite/error.rs`). VibORM therefore keeps `QueryError` on SQLite\n * instead of manufacturing a P2000 that the engine cannot honestly promise.\n */\nexport class ValueTooLongError extends coded<\n typeof VibORMErrorCode.VALUE_TOO_LONG\n>(\"ValueTooLongError\", VibORMErrorCode.VALUE_TOO_LONG) {}\n\n/**\n * Type guard for unique constraint errors\n */\nexport function isUniqueConstraintError(\n error: unknown\n): error is UniqueConstraintError {\n return error instanceof UniqueConstraintError;\n}\n\n/**\n * Type guard for foreign key errors\n */\nexport function isForeignKeyError(error: unknown): error is ForeignKeyError {\n return error instanceof ForeignKeyError;\n}\n\n/**\n * Type guard for not-null constraint errors\n */\nexport function isNotNullConstraintError(\n error: unknown\n): error is NotNullConstraintError {\n return error instanceof NotNullConstraintError;\n}\n\n/**\n * Type guard for check constraint errors\n */\nexport function isCheckConstraintError(\n error: unknown\n): error is CheckConstraintError {\n return error instanceof CheckConstraintError;\n}\n\n/**\n * Type guard for value-too-long errors\n */\nexport function isValueTooLongError(\n error: unknown\n): error is ValueTooLongError {\n return error instanceof ValueTooLongError;\n}\n","import { isVibORMError, type VibORMError } from \"./base\";\nimport {\n getTrustedRecordSeriesProgress,\n type RecordSeriesProgress,\n registerTrustedRecordSeriesProgress,\n sanitizeRecordSeriesProgress,\n} from \"./diagnostics\";\nimport { QueryEngineError } from \"./query\";\n\n/**\n * Enrich the owned failure after segment-atomic execution has stopped. The\n * database executor supplies counters only; this errors-layer boundary validates\n * them, updates direct metadata, and updates trusted serialization together.\n */\nexport function attachRecordSeriesProgress<T extends VibORMError>(\n error: T,\n progress: RecordSeriesProgress\n): T;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown {\n const ownedError = isVibORMError(error)\n ? error\n : new QueryEngineError(\n \"Record-series failed at committed segment.\",\n error instanceof Error ? { cause: error } : undefined\n );\n // One failure crosses one terminal series boundary. If a wrapper encounters\n // the same error again, retain the first trusted observation so public\n // metadata and trusted serialization cannot diverge.\n const trusted = getTrustedRecordSeriesProgress(ownedError);\n const sanitized = trusted ?? sanitizeRecordSeriesProgress(progress);\n if (!sanitized) return error;\n Object.defineProperty(ownedError.meta, \"recordSeriesProgress\", {\n configurable: true,\n enumerable: true,\n value: sanitized,\n writable: true,\n });\n if (!trusted) {\n registerTrustedRecordSeriesProgress(ownedError, sanitized);\n }\n return ownedError;\n}\n\n/** A committed prefix forbids the routed whole-operation retry. */\nexport function hasCommittedRecordSeriesProgress(error: unknown): boolean {\n if (!isVibORMError(error)) return false;\n const progress = getTrustedRecordSeriesProgress(error);\n return (\n (progress?.committedSegments ?? 0) > 0 ||\n progress?.mayHaveCommittedSegment === true\n );\n}\n","/**\n * Query Engine Types\n *\n * Shared types used across the query engine.\n */\n\nimport type { QueryExecutionContext } from \"@drivers/driver\";\nimport type { QueryResult } from \"@drivers/types\";\nimport type { Model } from \"@schema/model\";\nimport type { RelationCardinality } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\n\n// Re-export errors from unified error hierarchy\nexport {\n NestedWriteError,\n NotFoundError,\n QueryEngineError,\n ValidationError,\n} from \"@errors\";\n// Re-export Sql for convenience\nexport { Sql } from \"@sql\";\n\n// ============================================================\n// BATCH EXECUTION TYPES\n// ============================================================\n\n/**\n * Prepared query ready for batch execution\n */\nexport interface PreparedQuery {\n /** SQL string */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** Immutable attribution captured when the ORM operation was created. */\n context: QueryExecutionContext;\n}\n\n/**\n * One logical operation expanded into driver-level batch queries.\n */\nexport interface PreparedBatchOperation<T = unknown> {\n queries: PreparedQuery[];\n guards?: PreparedBatchGuard[];\n parseResult: (results: QueryResult<unknown>[]) => T;\n}\n\n/**\n * What a prepared guard publishes when its premise does not hold: the typed\n * failure taxonomy plus the `raceable` bit fixed by the guard's premise class.\n * `batch-error-attribution.ts` is the one algorithm that reads it, and the one\n * place it becomes an `Error`.\n */\nexport interface PreparedGuardFailure {\n readonly kind:\n | \"foreignKey\"\n | \"forbidden\"\n | \"nestedWrite\"\n | \"notFound\"\n | \"query\";\n readonly message: string;\n readonly relation?: string;\n /** A `forbidden` refusal's cause, where the operation alone does not say it. */\n readonly reason?: string;\n readonly raceable: boolean;\n}\n\n/** Declarative ownership for one assertion query in a prepared operation. */\nexport interface PreparedBatchGuard {\n readonly queryIndex: number;\n readonly premise: \"exists\" | \"notExists\";\n readonly probe: import(\"@sql\").Sql;\n readonly failure: PreparedGuardFailure;\n readonly model: string;\n readonly operation: Operation;\n}\n\n/**\n * Options for engine.prepare()\n */\nexport interface PrepareOptions {\n /** Throw NotFoundError if result is null (for OrThrow variants) */\n throwIfNotFound?: boolean;\n /** Original operation name for error messages */\n originalOperation?: string;\n /**\n * The client's last step on this operation's value (its chain's computed\n * fields), applied once, after every extension and the cache have run.\n */\n finishResult?: (value: unknown) => unknown;\n /**\n * The call's `named` option, taken out of its arguments by the client and\n * carried to every statement of the call by its execution context.\n */\n named?: boolean;\n}\n\n/**\n * All supported operations.\n *\n * NOTE — `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn`\n * are INTERNAL names, not client operations. The public surface has ONE name per\n * bulk family (maintainer decision D-1): `createMany` / `updateMany` /\n * `deleteMany` take an optional `select`, and its presence routes the tree to the\n * row-returning arm. These three tokens name that arm inside the SQL-building\n * substrate (result shape, program lowering, identity helpers); the client never\n * spells them, and they share their family's arg schema.\n */\nexport const OPERATIONS = [\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createMany\",\n \"createManyAndReturn\",\n \"update\",\n \"updateMany\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteMany\",\n \"deleteManyAndReturn\",\n \"upsert\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n] as const;\n\nexport type Operation = (typeof OPERATIONS)[number];\n\n/** Requested fields inside one aggregate JSON carrier. */\nexport interface ExpectedAggregateResultShape {\n /** Undefined only for the scalar `_count: true` result. */\n fields?: ReadonlySet<string>;\n}\n\n/**\n * One arm of a polymorphic projection that the selection reads\n * (`selectedArm`, result/result-shape.ts); an arm `only` excludes is absent.\n */\nexport interface ExpectedPolymorphicVariantShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n}\n\n/** Exact target-specific result contracts for one polymorphic projection. */\nexport interface ExpectedPolymorphicResultShape {\n /** Which carrier the read emitted: the singular tagged CASE, or the collection document. */\n readonly cardinality: \"one\" | \"many\";\n readonly optional: boolean;\n readonly variants: ReadonlyMap<string, ExpectedPolymorphicVariantShape>;\n}\n\n/** Exact public result contract for one ordinary relation projection. */\nexport interface ExpectedRelationResultShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n readonly cardinality: RelationCardinality;\n readonly optional: boolean;\n /**\n * The admitted recurrence of a recursive slot, the same normalized value\n * execution consumes. `shape` is then the ONE repeated node, and the slot's\n * own key recurs inside every occurrence: absent at a numeric cutoff,\n * present on every occurrence of an exhaustive traversal.\n */\n readonly recurrence?: NormalizedRecurrence;\n}\n\n/** One `_aggregate` entry: the target's own `aggregate` result for its selection. */\nexport interface ExpectedRelationAggregateShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n}\n\n/** Exact raw columns and nested projections expected for one returned row. */\nexport interface ExpectedResultShape {\n /** Raw statement carrier declared by the compiled operation result. */\n carrier: \"rows\" | \"count\" | \"existence\";\n rawKeys: readonly string[];\n /** Scalar whose selected `_distance` expression produced the private column. */\n readonly distanceScalar?: Scalar;\n relations: ReadonlyMap<string, ExpectedRelationResultShape>;\n polymorphic: ReadonlyMap<string, ExpectedPolymorphicResultShape>;\n aggregates: ReadonlyMap<string, ExpectedAggregateResultShape>;\n relationCounts: ReadonlySet<string>;\n /** Each relation a `_aggregate` names, in the order it names them. */\n readonly relationAggregates?: ReadonlyMap<\n string,\n ExpectedRelationAggregateShape\n >;\n /** `groupBy` fields grouped by a time step: each holds a period's day. */\n readonly periods?: ReadonlySet<string>;\n}\n","/**\n * The line of successors the package makes from one failure.\n *\n * One failure can reach a caller as several error objects: a statement fails,\n * then the package clones its error to add the operation's execution context\n * or a commit certainty. Whoever presents failures (the official\n * instrumentation logs a statement's, then the operation's) needs to know\n * that two of them are one: `errorOrigin` gives the first of the line.\n *\n * A `WeakMap` holds no strong reference: an entry disappears with the error\n * that keyed it, so nothing survives a request in a reused isolate.\n */\n\nconst origins = new WeakMap<object, Error>();\n\n/** Record that the package made `successor` from `source`. */\nexport function recordErrorSuccessor(source: Error, successor: Error): void {\n origins.set(successor, origins.get(source) ?? source);\n}\n\n/** The first error `error` was made from, or `error` itself. */\nexport function errorOrigin(error: Error): Error;\nexport function errorOrigin(error: unknown): unknown;\nexport function errorOrigin(error: unknown): unknown {\n return typeof error === \"object\" && error !== null\n ? (origins.get(error) ?? error)\n : error;\n}\n","import { TransactionError } from \"@errors\";\nimport type { TransactionPhaseNotifications } from \"../execution-context\";\n\nexport function nestedTransactionDispatchError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\": nested state outside tx.`,\n { meta: { driver: driverName, method: \"$transaction\" } }\n );\n}\n\nexport function unsupportedCallbackTransactionError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" lacks callback transactions.`,\n { meta: { driver: driverName, method: \"$transaction(callback)\" } }\n );\n}\n\n// A broken provider lifecycle cannot prove whether its handle remains safe.\nexport class ProviderTransactionContractError extends TransactionError {}\n\ntype LifecycleStep = () => unknown | Promise<unknown>;\n\nexport interface TransactionLifecycle<T> {\n readonly begin: LifecycleStep;\n readonly callback: () => Promise<T>;\n readonly commit: LifecycleStep;\n readonly rollback: LifecycleStep;\n readonly close?: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\nexport interface ProviderManagedTransaction<T, TTransaction> {\n readonly run: (\n callback: (tx: TTransaction) => Promise<T>\n ) => Promise<unknown>;\n readonly callback: (tx: TTransaction) => Promise<T>;\n readonly close: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\ntype ProviderCallbackOutcome<T> =\n | { readonly status: \"pending\" }\n | { readonly status: \"fulfilled\"; readonly value: T }\n | { readonly error: unknown; readonly status: \"rejected\" };\n\n/** Close provider-owned transaction state when its own cleanup/finalization fails. */\nexport async function runProviderManagedTransaction<T, TTransaction>(\n lifecycle: ProviderManagedTransaction<T, TTransaction>\n): Promise<T> {\n let callbackCallCount = 0;\n let callbackOutcome: ProviderCallbackOutcome<T> = {\n status: \"pending\",\n };\n const readCallbackOutcome = (): ProviderCallbackOutcome<T> => callbackOutcome;\n let callbackPromise: Promise<T> | undefined;\n let closeAttempted = false;\n const capturedCloseFailures: unknown[] = [];\n const drainPending = async (): Promise<boolean> => {\n const pending =\n callbackPromise !== undefined &&\n readCallbackOutcome().status === \"pending\";\n if (callbackPromise && pending) {\n closeAttempted = true;\n try {\n await lifecycle.close();\n } catch (error) {\n capturedCloseFailures.push(error);\n }\n await callbackPromise.catch(() => undefined);\n }\n return pending;\n };\n const contractError = (reason: string) =>\n new ProviderTransactionContractError(`Transaction provider ${reason}.`);\n try {\n await lifecycle.run((tx) => {\n callbackCallCount++;\n if (callbackCallCount > 1) {\n throw contractError(\"invoked callback more than once\");\n }\n callbackPromise = (async () => {\n try {\n const value = await lifecycle.callback(tx);\n lifecycle.phases?.readyToCommit();\n callbackOutcome = { status: \"fulfilled\", value };\n return value;\n } catch (error) {\n callbackOutcome = { status: \"rejected\", error };\n throw error;\n }\n })();\n callbackPromise.catch(() => undefined);\n return callbackPromise;\n });\n } catch (error) {\n const providerSettledBeforeCallback = await drainPending();\n const settledOutcome = readCallbackOutcome();\n if (\n settledOutcome.status === \"rejected\" &&\n !providerSettledBeforeCallback &&\n error === settledOutcome.error\n ) {\n throw error;\n }\n const primaryFailure =\n settledOutcome.status === \"rejected\" ? settledOutcome.error : error;\n const cleanupFailures: unknown[] = [];\n if (providerSettledBeforeCallback) {\n cleanupFailures.push(contractError(\"settled before callback\"));\n }\n if (\n settledOutcome.status === \"rejected\" &&\n error !== settledOutcome.error\n ) {\n cleanupFailures.push(\n ...readTransactionCleanupFailures(error, settledOutcome.error)\n );\n }\n cleanupFailures.push(...capturedCloseFailures);\n const cleanupSteps = cleanupFailures.map(failureStep);\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n const providerSettledBeforeCallback = await drainPending();\n const settledOutcome = readCallbackOutcome();\n const contractFailures: TransactionError[] = [];\n if (callbackCallCount !== 1) {\n contractFailures.push(\n contractError(\n callbackCallCount === 0\n ? \"completed without invoking callback\"\n : \"invoked callback more than once\"\n )\n );\n }\n if (providerSettledBeforeCallback) {\n contractFailures.push(contractError(\"completed before callback settled\"));\n }\n if (settledOutcome.status === \"rejected\") {\n contractFailures.push(contractError(\"resolved after callback rejected\"));\n }\n if (contractFailures.length > 0) {\n const primaryFailure =\n settledOutcome.status === \"rejected\"\n ? settledOutcome.error\n : contractFailures.shift();\n const cleanupSteps = [\n ...contractFailures.map(failureStep),\n ...capturedCloseFailures.map(failureStep),\n ];\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n if (settledOutcome.status !== \"fulfilled\") {\n return throwAfterCleanup(\n new ProviderTransactionContractError(\"Callback outcome not recorded.\"),\n [lifecycle.close]\n );\n }\n lifecycle.phases?.committed();\n return settledOutcome.value;\n}\n\n/** Run a top-level provider transaction without losing cleanup failures. */\nexport async function runTransactionLifecycle<T>(\n lifecycle: TransactionLifecycle<T>\n): Promise<T> {\n const rollbackCleanup = () =>\n lifecycle.close\n ? [lifecycle.rollback, lifecycle.close]\n : [lifecycle.rollback];\n try {\n await lifecycle.begin();\n } catch (error) {\n return throwAfterCleanup(error, lifecycle.close ? [lifecycle.close] : []);\n }\n\n let result: T;\n try {\n result = await lifecycle.callback();\n } catch (error) {\n return throwAfterCleanup(error, rollbackCleanup());\n }\n\n lifecycle.phases?.readyToCommit();\n\n try {\n await lifecycle.commit();\n } catch (error) {\n return throwAfterCleanup(error, rollbackCleanup());\n }\n\n lifecycle.phases?.committed();\n\n if (lifecycle.close) await lifecycle.close();\n return result;\n}\n\nexport const runSavepoint = async <T>(\n executeStatement: (statement: string) => unknown | Promise<unknown>,\n fn: () => Promise<T>\n): Promise<T> => {\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n await executeStatement(`SAVEPOINT ${savepointName}`);\n const cleanup = [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ];\n\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n return throwAfterCleanup(error, cleanup);\n }\n\n try {\n await executeStatement(`RELEASE SAVEPOINT ${savepointName}`);\n } catch (error) {\n return throwAfterCleanup(error, cleanup);\n }\n return result;\n};\n\nexport function createTransactionCleanupError(\n primaryFailure: unknown,\n cleanupFailures: readonly unknown[]\n): AggregateError {\n return new AggregateError(\n [primaryFailure, ...cleanupFailures],\n readFailureMessage(primaryFailure),\n { cause: primaryFailure }\n );\n}\n\nexport function readTransactionCleanupFailures(\n error: unknown,\n primaryFailure: unknown\n): readonly unknown[] {\n try {\n if (!(error instanceof AggregateError) || error.cause !== primaryFailure) {\n return [error];\n }\n return error.errors[0] === primaryFailure ? error.errors.slice(1) : [error];\n } catch {\n return [error];\n }\n}\n\nasync function throwAfterCleanup(\n primaryFailure: unknown,\n cleanupSteps: readonly LifecycleStep[]\n): Promise<never> {\n const cleanupFailures: unknown[] = [];\n for (const cleanupStep of cleanupSteps) {\n try {\n await cleanupStep();\n } catch (error) {\n cleanupFailures.push(error);\n }\n }\n\n if (cleanupFailures.length > 0) {\n throw createTransactionCleanupError(primaryFailure, cleanupFailures);\n }\n throw primaryFailure;\n}\n\nfunction failureStep(failure: unknown): LifecycleStep {\n return () => {\n throw failure;\n };\n}\n\nfunction readFailureMessage(error: unknown): string {\n try {\n return error instanceof Error && typeof error.message === \"string\"\n ? error.message\n : \"Transaction failed\";\n } catch {\n return \"Transaction failed\";\n }\n}\n","import {\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n getTrustedErrorCause,\n getTrustedErrorDisclosure,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n resolveDiagnosticDisclosure,\n sanitizeErrorMetadata,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValidationError,\n type ValidationErrorSource,\n ValueTooLongError,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport { OPERATIONS, type Operation } from \"@query-engine/types\";\nimport {\n defineSafe,\n isArrayValue,\n isError,\n isRecord,\n isTrustedCode,\n safeArrayLength,\n safeOwnPropertyDescriptor,\n sanitizeSqlState,\n} from \"../errors/diagnostic-safety\";\nimport { recordErrorSuccessor } from \"../errors/logged-errors\";\nimport {\n readSuppressedFailures,\n withSuppressedFailure,\n} from \"./shared/suppressed-failure\";\nimport { ProviderTransactionContractError } from \"./shared/transactions\";\nimport type { Dialect } from \"./types\";\n\nexport interface DriverErrorShape {\n code?: string | number;\n bodyCode?: string | number;\n errno?: number;\n stringErrno?: string;\n constraint?: string;\n table?: string;\n column?: string;\n constraint_name?: string;\n table_name?: string;\n column_name?: string;\n sqlState?: string;\n sqlstate?: string;\n status?: string | number;\n statusCode?: string | number;\n}\n\nexport interface DriverErrorContext {\n driverName: string;\n /**\n * The SQL family that raised the error, when the normalizing call site knows\n * it. Only numeric provider codes need it: a symbolic name or a message\n * symbol identifies its own provider, but a bare integer does not.\n */\n dialect?: Dialect;\n model?: string;\n operation?: Operation | string;\n correlationId?: string;\n statementIndex?: number;\n query?: string;\n params?: unknown[];\n diagnostics?: DiagnosticDisclosure;\n callsite?: string;\n forceContext?: boolean;\n}\n\nconst EXECUTION_META_KEYS =\n \"driver model operation correlationId callsite query params\".split(\" \");\nconst MYSQL_SQLSTATE_IN_MESSAGE_PATTERN = /\\(sqlstate ([^)]+)\\)/i;\nconst MYSQL_KEY_IN_MESSAGE_PATTERN = /for key '([^']+)'/;\n\nexport function readProperty(value: object, key: string): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nfunction readErrorSnapshot(\n error: VibORMError,\n diagnostics: DiagnosticDisclosure | undefined\n): { snapshot: Record<string, unknown>; meta: VibORMErrorMeta } {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n return {\n snapshot,\n meta: sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n diagnostics\n ),\n };\n}\n\nexport function attachExecutionContext(\n error: VibORMError,\n context: DriverErrorContext\n): VibORMError {\n const { snapshot, meta: mergedMeta } = readErrorSnapshot(\n error,\n context.diagnostics\n );\n const forceContext = context.forceContext !== false;\n if (!forceContext) {\n if (\n resolveDiagnosticDisclosure(context.diagnostics).includeCallsite &&\n context.callsite\n )\n mergedMeta.callsite = context.callsite;\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n }\n const additions = sanitizeErrorMetadata(\n buildMeta({}, context, \"\"),\n context.diagnostics\n );\n for (const key of EXECUTION_META_KEYS) {\n Reflect.deleteProperty(mergedMeta, key);\n }\n for (const key of Object.keys(additions)) {\n defineSafe(mergedMeta, key, additions[key]);\n }\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n}\n\nfunction withErrorMeta(\n error: VibORMError,\n update: (meta: VibORMErrorMeta) => boolean\n): VibORMError {\n const diagnostics = getTrustedErrorDisclosure(error);\n const { snapshot, meta } = readErrorSnapshot(error, diagnostics);\n return update(meta)\n ? cloneVibORMError(error, meta, snapshot, diagnostics)\n : error;\n}\n\n/**\n * Clone one trusted failure with `additions` on the meta keys it lacks, its\n * class, code, cause and disclosure kept: the inner owner of a fact wins.\n */\nexport function attachMissingMeta(\n error: VibORMError,\n additions: VibORMErrorMeta\n): VibORMError {\n return withErrorMeta(error, (meta) => {\n let added = false;\n for (const [key, value] of Object.entries(additions)) {\n if (value === undefined || meta[key] !== undefined) continue;\n meta[key] = value;\n added = true;\n }\n return added;\n });\n}\n\n/** Clone one trusted failure with the exact durable write state now known. */\nexport function attachCommitCertainty(\n error: VibORMError,\n commitCertainty: NonNullable<VibORMErrorMeta[\"commitCertainty\"]>\n): VibORMError {\n return withErrorMeta(error, (meta) => {\n meta.commitCertainty = commitCertainty;\n return true;\n });\n}\n\nfunction cloneVibORMError(\n error: VibORMError,\n meta: VibORMErrorMeta,\n snapshot: Record<string, unknown>,\n diagnostics: DiagnosticDisclosure | undefined\n): VibORMError {\n // The clone runs only the base constructor under the chosen class.\n // ValidationError owns state that constructor cannot rebuild, so it is\n // rebuilt from its snapshot here; every other class keeps its identity only\n // when it is one VibORM defines without such state.\n let cloneConstructor: unknown = VibORMError;\n if (error instanceof ValidationError) {\n const validationClone = cloneValidationError(\n error,\n snapshot,\n meta,\n diagnostics\n );\n if (validationClone) {\n recordErrorSuccessor(error, validationClone);\n return transferSuppressedFailureEvidence(error, validationClone);\n }\n } else {\n cloneConstructor = getCloneConstructor(error);\n }\n const message =\n typeof snapshot.message === \"string\"\n ? snapshot.message\n : \"VibORM operation failed\";\n const code = isVibORMErrorCode(snapshot.code)\n ? snapshot.code\n : VibORMErrorCode.INTERNAL_ERROR;\n const cause = getTrustedErrorCause(error);\n const options = {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n };\n const newTarget =\n typeof cloneConstructor === \"function\" ? cloneConstructor : VibORMError;\n let candidate: unknown;\n try {\n candidate = Reflect.construct(\n VibORMError,\n [message, code, options],\n newTarget\n );\n } catch {\n candidate = new VibORMError(message, code, options);\n }\n const clonedError =\n candidate instanceof VibORMError\n ? candidate\n : new VibORMError(message, code, options);\n recordErrorSuccessor(error, clonedError);\n return transferSuppressedFailureEvidence(error, clonedError);\n}\n\n/**\n * Carry the evidence a failure retained onto the failure that replaces it, so\n * rebuilding a primary (a clone, a mapped provider error) never drops it.\n */\nexport function transferSuppressedFailureEvidence(\n source: unknown,\n target: VibORMError\n): VibORMError {\n for (const failure of readSuppressedFailures(source)) {\n withSuppressedFailure(target, failure);\n }\n return target;\n}\n\nfunction cloneValidationError(\n error: ValidationError,\n serialized: Record<string, unknown>,\n meta: VibORMErrorMeta,\n diagnostics: DiagnosticDisclosure | undefined\n): ValidationError | undefined {\n const source = snapshotValidationSource(readProperty(serialized, \"source\"));\n const issues = readProperty(serialized, \"issues\");\n if (!(source && isArrayValue(issues))) return undefined;\n const issueSnapshot = snapshotValidationIssues(issues);\n const cause = getTrustedErrorCause(error);\n return new ValidationError(source, issueSnapshot, {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n });\n}\n\nfunction snapshotValidationSource(\n value: unknown\n): ValidationErrorSource | undefined {\n if (!isRecord(value)) return undefined;\n const str = (key: string) => {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n };\n const opt = (key: string) => {\n const s = str(key);\n return s !== undefined ? { [key]: s } : undefined;\n };\n const kind = readProperty(value, \"kind\");\n if (kind === \"operation\") {\n const operation = readProperty(value, \"operation\");\n return isOperation(operation)\n ? { kind, operation, ...opt(\"model\") }\n : undefined;\n }\n if (kind === \"registry\") return { kind, ...opt(\"model\"), ...opt(\"property\") };\n if (kind === \"schema-builder\") {\n const builder = str(\"builder\");\n const path = str(\"path\");\n return builder !== undefined && path !== undefined\n ? { kind, builder, path }\n : undefined;\n }\n if (kind === \"json-schema\")\n return { kind, ...opt(\"target\"), ...opt(\"schemaType\") };\n return undefined;\n}\n\nfunction snapshotValidationIssues(value: unknown[]): Array<{\n path: string;\n message: string;\n}> {\n const issues: Array<{ path: string; message: string }> = [];\n const length = Math.min(safeArrayLength(value), 128);\n for (let index = 0; index < length; index += 1) {\n const descriptor = safeOwnPropertyDescriptor(value, String(index));\n if (!(descriptor && \"value\" in descriptor && isRecord(descriptor.value))) {\n continue;\n }\n const path = readProperty(descriptor.value, \"path\");\n const message = readProperty(descriptor.value, \"message\");\n if (typeof path !== \"string\" || typeof message !== \"string\") continue;\n issues.push({ path, message });\n }\n return issues;\n}\n\nfunction isOperation(value: unknown): value is Operation {\n return (\n typeof value === \"string\" &&\n (OPERATIONS as readonly string[]).includes(value)\n );\n}\n\n// Every VibORM error class whose state the base constructor rebuilds, so its\n// identity survives cloning. A class outside it — a caller's subclass, which\n// may own state no clone can reconstruct, or SchemaValidationError with its\n// issues — degrades to the base class rather than a hollow instance that\n// passes \\`instanceof\\` but breaks on its own members. ValidationError is\n// absent on purpose: it is rebuilt from its snapshot.\nconst CLONE_CONSTRUCTORS = [\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValueTooLongError,\n] as const;\n\nfunction getCloneConstructor(error: VibORMError): unknown {\n try {\n const prototype = Object.getPrototypeOf(error);\n if (prototype === ProviderTransactionContractError.prototype)\n return TransactionError;\n return (\n CLONE_CONSTRUCTORS.find((ctor) => ctor.prototype === prototype) ??\n VibORMError\n );\n } catch {\n return VibORMError;\n }\n}\n\n// The code shape rule, not membership in the enum object: reading the enum's\n// values would keep the whole object in every bundle, while member accesses\n// are inlined. The snapshot already passed the same rule when it was taken.\nfunction isVibORMErrorCode(value: unknown): value is VibORMErrorCode {\n return isTrustedCode(value);\n}\n\nexport function buildMeta(\n error: DriverErrorShape,\n context: DriverErrorContext,\n message: string\n): VibORMErrorMeta {\n const meta: VibORMErrorMeta = { driver: context.driverName };\n const disclosure = resolveDiagnosticDisclosure(context.diagnostics);\n const setIf = (key: string, value: unknown) => {\n if (value) meta[key] = value;\n };\n\n if (disclosure.includeCallsite) setIf(\"callsite\", context.callsite);\n setIf(\"model\", context.model);\n setIf(\"operation\", context.operation);\n setIf(\"correlationId\", context.correlationId);\n if (context.statementIndex !== undefined)\n meta.statementIndex = context.statementIndex;\n if (disclosure.includeSql && context.query !== undefined)\n meta.query = context.query;\n if (disclosure.includeParams && context.params !== undefined)\n meta.params = context.params;\n\n const setSN = (key: string, value: unknown) => {\n if (typeof value === \"string\" || typeof value === \"number\")\n meta[key] = value;\n };\n const providerCode = error.code ?? error.bodyCode;\n setSN(\"providerCode\", providerCode);\n if (typeof error.errno === \"number\") meta.providerErrno = error.errno;\n const sqlState =\n error.sqlState ??\n error.sqlstate ??\n sanitizeSqlState(providerCode) ??\n MYSQL_SQLSTATE_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (typeof sqlState === \"string\") meta.providerSqlState = sqlState;\n setSN(\"providerStatus\", error.status ?? error.statusCode);\n\n setIf(\"constraint\", error.constraint ?? error.constraint_name);\n setIf(\"table\", error.table ?? error.table_name);\n const column = error.column ?? error.column_name;\n if (column) meta.columns = [column];\n\n if (!meta.constraint) {\n const key = MYSQL_KEY_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (key) {\n const dot = key.indexOf(\".\");\n meta.constraint = dot === -1 ? key : key.slice(dot + 1);\n if (dot !== -1 && !meta.table) meta.table = key.slice(0, dot);\n }\n }\n return meta;\n}\n","import {\n attachRecordSeriesProgress,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n ForeignKeyError,\n getTrustedRecordSeriesProgress,\n isVibORMError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NotNullConstraintError,\n QueryError,\n type QueryErrorCode,\n TransactionError,\n type TransactionErrorCode,\n UniqueConstraintError,\n ValueTooLongError,\n type VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport {\n attachExecutionContext,\n buildMeta,\n type DriverErrorContext,\n type DriverErrorShape,\n readProperty,\n transferSuppressedFailureEvidence,\n} from \"./driver-error-context\";\nimport type { Dialect } from \"./types\";\n\n// Stop at \":\" so D1's \"users.email: SQLITE_CONSTRAINT\" suffix isn't captured\nconst BUN_SQL_STATE_PATTERN = /^[0-9A-Z]{5}$/;\nconst PROVIDER_CONNECTION_CODE_PATTERN =\n /^(?:CONNECTION_(?:CLOSED|DESTROYED|ENDED)$|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE$|ERR_POSTGRES_CONNECTION_|08[0-9A-Z]{3}$|57P0[123]$)/;\nconst SQLITE_CONSTRAINT_COLUMNS_PATTERN = /constraint failed: ([^:]+)/;\n// node-postgres (and the pg-compatible Neon pool) give a connection that\n// dropped under a statement, and every use of that client after it, no code:\n// only these messages. Unrecognized, both read as a refused statement (V2001).\nconst POSTGRES_CONNECTION_LOST_MESSAGES = new Set([\n \"Connection terminated unexpectedly\",\n \"Client has encountered a connection error and is not queryable\",\n]);\n// Symbolic BUSY/LOCKED codes are the exact base name or an underscore-delimited\n// extended family member. The delimiter is load-bearing: startsWith accepted\n// unrelated provider codes such as SQLITE_BUSYWORK and SQLITE_LOCKEDNESS.\nconst SQLITE_CONTENTION_NAME_PATTERN =\n /^SQLITE_(?:BUSY|LOCKED)(?:_[A-Z0-9]+)*$/;\nconst ASCII_PROVIDER_SYMBOL_PATTERN = /[A-Za-z0-9_]+/g;\n// An extended result code is `base | (sub << 8)`, so the whole family keeps its\n// base in the low byte. That byte alone proves nothing across providers —\n// MySQL errno 1029 also ends in 5 — so numeric recognition needs the dialect.\nconst SQLITE_BASE_CODE_MASK = 0xff;\nconst SQLITE_BUSY_BASE_CODE = 5;\nconst SQLITE_LOCKED_BASE_CODE = 6;\nconst MYSQL_ERRNO_IN_MESSAGE_PATTERN = /\\(errno (\\d+)\\)/;\n// Batch-plan assertions (adapter.assertions) fail on purpose with a\n// dialect-specific trick: division by zero on PG (SQLSTATE 22012), invalid\n// JSON via JSON_EXTRACT/json_extract on MySQL (errno 3141) and SQLite\n// (\"malformed JSON\"). The statements are identifiable by their column alias.\nexport const ASSERTION_MARKER = \"__viborm_assert__\";\n/**\n * A write judging the row it produces (`adapter.assertions.holds`) carries\n * this alias, and fails on its own refusal: the sentinel text its guard\n * names (PostgreSQL, SQLite: in the message) or, on MySQL, the invalid path\n * its sentinel is (errno 3143). Nothing else the statement raises is a\n * refusal, so a caller's division by zero or invalid JSON in it stays the\n * provider's failure (E5.6).\n */\nexport const JUDGEMENT_MARKER = \"__viborm_judged__\";\nconst REFUSAL_SENTINEL = \"__viborm_refused__\";\nconst MYSQL_INVALID_JSON_PATH = 3143;\nconst POSTGRES_DIVISION_BY_ZERO = \"22012\";\nconst MYSQL_INVALID_JSON_TEXT = 3141;\n\n// `json_each(?))` closes a bound member list (SQLite's `literals.list`): JSON\n// text the adapter stringified, which cannot raise \"malformed JSON\".\nconst JSON_ACCESS_SIGNATURE = /json(?!_each\\(\\?\\)\\))|->/i;\n\n/**\n * The dialects nothing collides with: SurrealDB raises no batch assertion,\n * and Snowflake runs no batch.\n */\ntype NoAssertionCollision = \"surrealql\" | \"snowflake\";\n\n// Every other dialect states its signature: one added to `Dialect` does not\n// compile until it is here or above. Checked by the type only, so the\n// dialects above cost an application no byte.\nconst FOREIGN_ASSERTION_SIGNATURE: Readonly<Partial<Record<Dialect, RegExp>>> =\n {\n postgresql: /[/%]/,\n mysql: JSON_ACCESS_SIGNATURE,\n sqlite: JSON_ACCESS_SIGNATURE,\n } satisfies Record<Exclude<Dialect, NoAssertionCollision>, RegExp>;\n\n/**\n * Report whether an ordinary statement can raise the same provider error as a\n * batch assertion. Assertion statements carry {@link ASSERTION_MARKER}; all\n * other statements are checked against the executing dialect's failure\n * signature. With an ownership set, assertions outside that set also collide.\n * A conservative match leaves the raw provider error unattributed.\n */\nexport function batchMayContainAssertionCollision(\n statements: readonly { readonly sql: string }[],\n dialect: Dialect,\n ownedAssertions?: ReadonlySet<number>\n): boolean {\n const signature = FOREIGN_ASSERTION_SIGNATURE[dialect];\n for (const [index, statement] of statements.entries()) {\n if (\n statement.sql.includes(ASSERTION_MARKER) ||\n statement.sql.includes(JUDGEMENT_MARKER)\n ) {\n if (ownedAssertions && !ownedAssertions.has(index)) return true;\n continue;\n }\n if (signature?.test(statement.sql)) return true;\n }\n return false;\n}\n\nconst ASSERTION_MESSAGE_PATTERN =\n /division by zero|malformed JSON|Invalid JSON text/;\n\nfunction isSQLiteContentionResultCode(\n value: string | number | undefined\n): boolean {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n return false;\n }\n // biome-ignore lint/suspicious/noBitwiseOperators: SQLite defines an extended result code as `base | (sub << 8)`.\n const base = value & SQLITE_BASE_CODE_MASK;\n return base === SQLITE_BUSY_BASE_CODE || base === SQLITE_LOCKED_BASE_CODE;\n}\n\n/**\n * Report whether a provider error is SQLite lock contention, across the three\n * shapes drivers use: an extended symbolic code, an extended numeric result\n * code, or a message carrying the symbol (D1, libsql).\n */\nfunction isSQLiteContention(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n dialect: Dialect | undefined\n): boolean {\n if (dialect !== \"sqlite\") return false;\n if (typeof code === \"string\" && SQLITE_CONTENTION_NAME_PATTERN.test(code))\n return true;\n if (isSQLiteContentionResultCode(code) || isSQLiteContentionResultCode(errno))\n return true;\n for (const match of message.matchAll(ASCII_PROVIDER_SYMBOL_PATTERN)) {\n if (SQLITE_CONTENTION_NAME_PATTERN.test(match[0])) return true;\n }\n return false;\n}\n\n/**\n * A recognized failure's class, called with one options shape. `QueryError`\n * is not one: it is the unrecognized fallback, and its `code` family differs.\n */\ntype FailureClass = new (\n message: string,\n options: {\n cause: Error;\n code: TransactionErrorCode | undefined;\n diagnostics: DiagnosticDisclosure | undefined;\n meta: VibORMErrorMeta;\n }\n) => DriverFailure;\n\n/** What one recognized provider failure becomes: class, message, and code when the class has a family. */\ntype FailureConstruction = readonly [\n failure: FailureClass,\n message: string,\n code?: TransactionErrorCode | undefined,\n ...rest: unknown[],\n];\n\ntype ProviderFailure = readonly [\n failure: FailureClass,\n message: string,\n code: TransactionErrorCode | undefined,\n /** PostgreSQL SQLSTATEs and SQLite extended symbolic codes, matched against `code`. */\n providerCodes: readonly unknown[],\n /** MySQL errnos, matched against `errno`. */\n mysqlErrnos?: readonly unknown[],\n /** MySQL symbolic names, matched against `code`. */\n mysqlNames?: readonly unknown[],\n /** A fragment of the SQLite message that names this failure. */\n sqliteMessage?: string,\n /** Whether that SQLite message lists the failing columns. */\n sqliteColumns?: true,\n];\n\nconst ASSERTION_FAILURE: FailureConstruction = [\n NestedWriteAssertionError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n];\n// SQLite lock refusal is contention, not proof of a deadlock.\nconst SQLITE_CONTENTION_FAILURE: FailureConstruction = [\n TransactionError,\n \"Database is locked\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n];\n\n/**\n * The recognized provider failures. Precedence is the table read three times:\n * every row's provider code first, then every row's MySQL errno or name, then\n * (after SQLite lock contention) every row's SQLite message fragment. Within a\n * pass, the earlier row wins, so a MySQL errno outranks a later row's name.\n */\nconst PROVIDER_FAILURES: readonly ProviderFailure[] = [\n [\n UniqueConstraintError,\n \"Unique constraint violation\",\n undefined,\n [\"23505\", \"SQLITE_CONSTRAINT_UNIQUE\"],\n [1062],\n [\"ER_DUP_ENTRY\"],\n \"UNIQUE constraint failed\",\n true,\n ],\n [\n ForeignKeyError,\n \"Foreign key constraint violation\",\n undefined,\n [\"23503\", \"23001\", \"SQLITE_CONSTRAINT_FOREIGNKEY\"],\n [1452, 1451],\n [\"ER_NO_REFERENCED_ROW_2\", \"ER_ROW_IS_REFERENCED_2\"],\n \"FOREIGN KEY constraint failed\",\n ],\n [\n NotNullConstraintError,\n \"Not-null constraint violation\",\n undefined,\n [\"23502\", \"SQLITE_CONSTRAINT_NOTNULL\"],\n [1048],\n [\"ER_BAD_NULL_ERROR\"],\n \"NOT NULL constraint failed\",\n true,\n ],\n [\n CheckConstraintError,\n \"Check constraint violation\",\n undefined,\n [\"23514\", \"SQLITE_CONSTRAINT_CHECK\"],\n [3819],\n [\"ER_CHECK_CONSTRAINT_VIOLATED\"],\n \"CHECK constraint failed\",\n ],\n [\n ValueTooLongError,\n \"Value too long for column type\",\n undefined,\n [\"22001\"],\n [1406],\n [\"ER_DATA_TOO_LONG\"],\n ],\n [\n TransactionError,\n \"Transaction serialization failure\",\n VibORMErrorCode.SERIALIZATION_FAILURE,\n [\"40001\"],\n ],\n [\n TransactionError,\n \"Database lock is unavailable\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n [\"55P03\"],\n ],\n [\n TransactionError,\n \"Transaction deadlock detected\",\n VibORMErrorCode.DEADLOCK,\n [\"40P01\"],\n [1213],\n [\"ER_LOCK_DEADLOCK\"],\n ],\n];\n\n/**\n * Every error class {@link mapProviderError} constructs — the driver layer's failure\n * vocabulary, named so it is visible at the call sites instead of erased to `Error`.\n *\n * The members are disjoint by `code` — each class carries its literal — so this union is a\n * discriminated union: `if (failure.code === VibORMErrorCode.UNIQUE_CONSTRAINT)` selects\n * `UniqueConstraintError`, and an exhaustive `switch` over the codes bottoms out at `never`.\n *\n * `mapProviderError` is annotated with it, which is the point: adding a ninth class to the\n * mapper without adding it here is a compile error, not a silently widened return.\n */\nexport type DriverFailure =\n | ClientInitializationError\n | CheckConstraintError\n | ConnectionError\n | ForeignKeyError\n | NestedWriteAssertionError\n | NotNullConstraintError\n | QueryError\n | TransactionError\n | UniqueConstraintError\n | ValueTooLongError;\n\nconst codeSet = (codes: string): ReadonlySet<string> =>\n new Set(codes.split(\" \"));\n\nconst CONFIG_CODES = codeSet(\n \"28P01 28000 3D000 ER_ACCESS_DENIED_ERROR ER_BAD_DB_ERROR\"\n);\nconst CAPACITY_CODES = codeSet(\n \"53300 ER_CON_COUNT_ERROR ER_TOO_MANY_USER_CONNECTIONS\"\n);\n\nconst QUERY_FAILURES: readonly (readonly [\n string,\n QueryErrorCode,\n ReadonlySet<string>,\n readonly number[],\n RegExp?,\n])[] = [\n [\n \"Table or column not found\",\n VibORMErrorCode.QUERY_SCHEMA_MISMATCH,\n codeSet(\"42P01 42703 ER_NO_SUCH_TABLE ER_BAD_FIELD_ERROR\"),\n [1146, 1054],\n /no such (?:table|column):|has no column named/,\n ],\n [\n \"Numeric value out of range\",\n VibORMErrorCode.QUERY_OUT_OF_RANGE,\n codeSet(\"22003 ER_WARN_DATA_OUT_OF_RANGE ER_DATA_OUT_OF_RANGE\"),\n [1264, 1690],\n /integer overflow/,\n ],\n [\n \"Query timed out\",\n VibORMErrorCode.QUERY_TIMEOUT,\n codeSet(\"57014 ER_LOCK_WAIT_TIMEOUT QUERY_TIMEOUT\"),\n [1205],\n ],\n];\n\nconst UNKNOWN_PROVIDER_ERROR = \"Unknown provider error\";\n\nconst matchesCode = (\n code: string | number | undefined,\n errno: number | undefined,\n codes: ReadonlySet<string>,\n a: number,\n b: number\n): boolean =>\n (typeof code === \"string\" && codes.has(code)) || errno === a || errno === b;\n\nconst isConfigurationFailure = (\n code: string | number | undefined,\n errno?: number\n): boolean => matchesCode(code, errno, CONFIG_CODES, 1045, 1049);\n\nconst isConnectionCapacityFailure = (\n code: string | number | undefined,\n errno?: number\n): boolean => matchesCode(code, errno, CAPACITY_CODES, 1040, 1203);\n\nfunction configurationFailure(\n cause: Error,\n context: DriverErrorContext,\n meta: VibORMErrorMeta\n): ClientInitializationError {\n return new ClientInitializationError(\"Database auth/config failed\", {\n cause,\n meta,\n diagnostics: context.diagnostics,\n });\n}\n\nfunction extractProviderInfo(error: unknown, context: DriverErrorContext) {\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n return { cause, rawMessage, dbError, meta };\n}\n\nfunction connectionError(\n code: string | number | undefined,\n cause: Error,\n context: DriverErrorContext,\n meta: VibORMErrorMeta,\n message: string,\n capacity = false\n): ConnectionError {\n return new ConnectionError(\n capacity ? \"Connection capacity exhausted\" : message,\n {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code: capacity\n ? VibORMErrorCode.CONNECTION_CAPACITY\n : code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n }\n );\n}\n\n/**\n * What {@link normalizeDriverError} can hand back.\n *\n * Two arms, and the type is the union of both. A raw provider error is mapped to a\n * {@link DriverFailure}. An error that is ALREADY a VibORM error is passed through with\n * execution context attached — and that arm is honestly `VibORMError`, not `DriverFailure`:\n * the incoming error can be any VibORM error the layers above threw (a `ValidationError`, an\n * engine refusal), `attachExecutionContext` clones it under its own class, and a stateful\n * class it cannot rebuild degrades to the base `VibORMError` (`driver-error-context.ts`).\n * Typing the whole function `DriverFailure` would be a claim this arm cannot keep.\n */\nexport type NormalizedDriverError = DriverFailure | VibORMError;\n\nexport function normalizeDriverError(\n error: unknown,\n context: DriverErrorContext\n): NormalizedDriverError {\n if (isKnownVibORMError(error)) {\n const normalized = attachExecutionContext(error, context);\n const progress = getTrustedRecordSeriesProgress(error);\n return progress\n ? attachRecordSeriesProgress(normalized, progress)\n : normalized;\n }\n return mapProviderError(error, context);\n}\n\n/**\n * Map a raw provider error onto the {@link DriverFailure} vocabulary. Split out of\n * {@link normalizeDriverError} so the constructed union has a return type to be checked\n * against — the passthrough arm above cannot carry that annotation, and a function has one\n * return type. {@link recognizeProviderFailure} decides which failure it is; this is the\n * one place it is constructed.\n */\nfunction mapProviderError(\n error: unknown,\n context: DriverErrorContext\n): DriverFailure {\n const { cause, rawMessage, dbError, meta } = extractProviderInfo(\n error,\n context\n );\n const stringErrno = dbError.stringErrno;\n const bunSqlState =\n context.driverName === \"bun-sql\" &&\n typeof dbError.code === \"string\" &&\n dbError.code.startsWith(\"ERR_POSTGRES\") &&\n BUN_SQL_STATE_PATTERN.test(stringErrno ?? \"\")\n ? stringErrno\n : undefined;\n const code = bunSqlState ?? dbError.sqlstate ?? dbError.code;\n if (bunSqlState) meta.providerCode = bunSqlState;\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n const base = { cause, diagnostics: context.diagnostics, meta };\n let failure: DriverFailure;\n if (isConfigurationFailure(code, dbError.errno)) {\n failure = configurationFailure(cause, context, meta);\n } else if (\n (code === undefined &&\n context.dialect === \"postgresql\" &&\n POSTGRES_CONNECTION_LOST_MESSAGES.has(rawMessage)) ||\n (typeof code === \"string\" && PROVIDER_CONNECTION_CODE_PATTERN.test(code))\n ) {\n failure = connectionError(\n code,\n cause,\n context,\n meta,\n \"Database connection failed\"\n );\n } else {\n if (errno !== undefined && meta.providerErrno === undefined)\n meta.providerErrno = errno;\n const isStr = typeof code === \"string\";\n const isSqlite = context.dialect === \"sqlite\";\n if (isConnectionCapacityFailure(code, errno)) {\n failure = connectionError(code, cause, context, meta, \"\", true);\n } else {\n const queryMatch = QUERY_FAILURES.find(\n ([, , codes, errnos, sqlitePattern]) =>\n (isStr && codes.has(code)) ||\n (errno !== undefined && errnos.includes(errno)) ||\n (isSqlite && sqlitePattern?.test(rawMessage) === true)\n );\n if (queryMatch) {\n failure = new QueryError(queryMatch[0], {\n ...base,\n code: queryMatch[1],\n });\n } else {\n const recognized = recognizeProviderFailure(\n code,\n errno,\n rawMessage,\n meta,\n context\n );\n failure = recognized\n ? new recognized[0](recognized[1], { ...base, code: recognized[2] })\n : new QueryError(\"Query execution failed\", base);\n }\n }\n }\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * Which failure a raw provider error is. An assertion statement's own failure\n * comes first; then {@link PROVIDER_FAILURES} in its three passes, with SQLite\n * lock contention before the SQLite message pass. Anything else is not\n * recognized.\n */\nfunction recognizeProviderFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n meta: VibORMErrorMeta,\n context: DriverErrorContext\n): FailureConstruction | undefined {\n if (\n (context.query?.includes(JUDGEMENT_MARKER) &&\n (message.includes(REFUSAL_SENTINEL) ||\n errno === MYSQL_INVALID_JSON_PATH ||\n code === \"ER_INVALID_JSON_PATH\")) ||\n (context.query?.includes(ASSERTION_MARKER) &&\n (code === POSTGRES_DIVISION_BY_ZERO ||\n code === \"ER_INVALID_JSON_TEXT_IN_PARAM\" ||\n errno === MYSQL_INVALID_JSON_TEXT ||\n ASSERTION_MESSAGE_PATTERN.test(message)))\n ) {\n return ASSERTION_FAILURE;\n }\n const recognized =\n PROVIDER_FAILURES.find((row) => row[3].includes(code)) ??\n PROVIDER_FAILURES.find(\n (row) => row[4]?.includes(errno) || row[5]?.includes(code)\n );\n if (recognized) {\n if (recognized[7] && typeof code === \"string\" && code.startsWith(\"SQLITE_\"))\n attachSQLiteColumns(message, meta);\n return recognized;\n }\n if (isSQLiteContention(code, errno, message, context.dialect)) {\n return SQLITE_CONTENTION_FAILURE;\n }\n return findSQLiteMessageFailure(message, meta);\n}\n\n/**\n * What {@link normalizeDriverConnectionError} can hand back — the connection variant of\n * {@link NormalizedDriverError}. The constructed arm is exactly {@link ConnectionError}; the\n * passthrough arm is `VibORMError` for the same two reasons documented there.\n */\nexport type NormalizedConnectionError = ConnectionError | VibORMError;\n\nexport function normalizeDriverConnectionError(\n error: unknown,\n context: DriverErrorContext,\n message = \"Database connection failed\"\n): NormalizedConnectionError {\n if (isKnownVibORMError(error)) {\n return attachExecutionContext(error, context);\n }\n\n const { cause, rawMessage, dbError, meta } = extractProviderInfo(\n error,\n context\n );\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n const code = dbError.sqlstate ?? dbError.code;\n const failure: DriverFailure = isConfigurationFailure(code, errno)\n ? configurationFailure(cause, context, meta)\n : connectionError(\n code,\n cause,\n context,\n meta,\n message,\n isConnectionCapacityFailure(code, errno)\n );\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\nconst safe = <T>(fn: () => T, fallback: T): T => {\n try {\n return fn();\n } catch {\n return fallback;\n }\n};\n\nfunction isKnownVibORMError(error: unknown): error is VibORMError {\n return safe(() => isVibORMError(error), false);\n}\n\nconst toError = (error: unknown): Error =>\n safe(() => (error instanceof Error ? error : undefined), undefined) ??\n new Error(UNKNOWN_PROVIDER_ERROR);\n\nconst getErrorMessage = (error: Error): string =>\n safe(\n () =>\n typeof error.message === \"string\"\n ? error.message\n : UNKNOWN_PROVIDER_ERROR,\n UNKNOWN_PROVIDER_ERROR\n );\n\nconst isObjectLike = (value: unknown): value is object =>\n value !== null && (typeof value === \"object\" || typeof value === \"function\");\n\nconst SHAPE_STR_KEYS =\n \"constraint table column constraint_name table_name column_name sqlState sqlstate\".split(\n \" \"\n );\nconst SHAPE_SN_KEYS = [\"code\", \"status\", \"statusCode\"];\n\nfunction readDriverErrorShape(error: unknown): DriverErrorShape {\n if (!isObjectLike(error)) return {};\n const body = readProperty(error, \"body\");\n const errno = readProperty(error, \"errno\");\n const out: DriverErrorShape = {\n bodyCode: isObjectLike(body) ? readStringOrNumber(body, \"code\") : undefined,\n errno: typeof errno === \"number\" ? errno : undefined,\n stringErrno: typeof errno === \"string\" ? errno : undefined,\n };\n for (const key of SHAPE_STR_KEYS) {\n const member = readProperty(error, key);\n if (typeof member === \"string\") Reflect.set(out, key, member);\n }\n for (const key of SHAPE_SN_KEYS) {\n const member = readStringOrNumber(error, key);\n if (member !== undefined) Reflect.set(out, key, member);\n }\n return out;\n}\n\nfunction readStringOrNumber(\n value: object,\n key: string\n): string | number | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" || typeof member === \"number\"\n ? member\n : undefined;\n}\n\nfunction parseMessageErrno(message: string): number | undefined {\n const m = MYSQL_ERRNO_IN_MESSAGE_PATTERN.exec(message)?.[1];\n return m ? +m : undefined;\n}\n\n/**\n * The first row whose SQLite message fragment the provider message carries, in\n * table order. UNIQUE and NOT NULL messages also name their columns.\n */\nfunction findSQLiteMessageFailure(\n message: string,\n meta: VibORMErrorMeta\n): ProviderFailure | undefined {\n const row = PROVIDER_FAILURES.find(\n (candidate) => candidate[6] && message.includes(candidate[6])\n );\n if (row?.[7]) attachSQLiteColumns(message, meta);\n return row;\n}\n\nconst SQLITE_IDENT_SRC = String.raw`(?:\"(?:[^\"]|\"\")*\"|\\`(?:[^\\`]|\\`\\`)*\\`|\\[[^\\]]+\\]|[A-Za-z_][A-Za-z0-9_$]*)`;\nconst SQLITE_PATH_SRC = `${SQLITE_IDENT_SRC}(?:\\\\s*\\\\.\\\\s*${SQLITE_IDENT_SRC})*`;\nconst SQLITE_LIST_RE = new RegExp(\n `^\\\\s*${SQLITE_PATH_SRC}(?:\\\\s*,\\\\s*${SQLITE_PATH_SRC})*\\\\s*$`\n);\nconst SQLITE_PATH_RE = new RegExp(SQLITE_PATH_SRC, \"g\");\nconst SQLITE_IDENT_RE = new RegExp(SQLITE_IDENT_SRC, \"g\");\n\nfunction attachSQLiteColumns(message: string, meta: VibORMErrorMeta): void {\n const match = SQLITE_CONSTRAINT_COLUMNS_PATTERN.exec(message);\n if (!(match?.[1] && SQLITE_LIST_RE.test(match[1]))) return;\n const paths = match[1].match(SQLITE_PATH_RE);\n if (!paths) return;\n const columns: string[] = [];\n const tables = new Set<string>();\n for (const qualified of paths) {\n const parts = qualified.match(SQLITE_IDENT_RE);\n if (!parts?.length) return;\n const names = parts.map((part) => {\n const q = part[0];\n if (q === '\"' || q === \"`\") return part.slice(1, -1).replaceAll(q + q, q);\n return q === \"[\" ? part.slice(1, -1) : part;\n });\n const column = names.pop();\n if (column === undefined) return;\n columns.push(column);\n if (names.length) tables.add(names.join(\".\"));\n }\n meta.columns = columns;\n if (tables.size === 1) meta.table = tables.values().next().value;\n}\n"],"mappings":"6cAqBA,IAAM,GAAN,MAAM,CAAgB,CACpB,GACA,MACA,UAGA,OAAA,EAAyD,CACvD,aAAc,GACd,WAAY,GACZ,KAAkB,CAChB,OAAO,EAAgB,OAAO,KAAK,EAAE,MAAM,EAE9C,CACD,YAAY,EAAiC,CAC3C,MAAA,EAAe,EACX,EAAO,IAAG,KAAK,MAAQ,EAAO,GAClC,KAAK,UAAY,EAAO,EACpB,EAAO,GACT,OAAO,eACL,KACA,gBACA,GAAA,EACD,CACE,KAAK,cAAgB,EAAO,IAAM,IAAA,GACnC,EAAO,IAAM,IAAA,KAAW,KAAK,MAAQ,EAAO,GAChD,OAAO,OAAO,KAAK,CAErB,OAAO,OAAO,EAAsD,CAClE,MAAO,MAAW,EACb,GAAA,EACD,IAAA,KAGR,MAAM,EAAW,GAAoB,GAAgB,OAAO,EAAQ,CAC9D,GAAY,GAChB,EAAQ,EAAQ,EAAI,EAAiC,EAAQ,CACzD,GACJ,EACA,IAEA,EAA8B,CAAE,GAAG,GAAS,EAAQ,CAAE,GAAG,EAAO,CAAC,CAEnE,SAAgB,GACd,EACA,EACA,EACA,EACuB,CACvB,GAAI,CAAC,EACH,OAAO,GACL,EACA,IAAA,GACA,IAAA,GACA,EACD,CAGH,IAAI,EACJ,OAAO,EAA8B,CACnC,GAAI,EACJ,OAAW,IAAkB,GAAsB,CACnD,GAAI,EACJ,EAAG,EAAW,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AAG,GAAG,CAAC,WAAW,EAAI,EAAG,EAAE,CAClE,IAAM,IAAM,EAAK,MAAM,EAAG,GAAG,CAAG,GACvC,CACI,EAAS,EAAM,KAAK,CAC1B,GAAI,IAAW,IAAA,GAAW,OAC1B,EAAQ,KAAK,EAAO,CAChB,EAAM,QAAQ,EAAO,IAAI,EAAM,KAAK,IAAI,CAAC,CAE/C,EAAK,QAAU,EACX,EAAO,OAAS,IAAG,EAAK,MAAQ,EAAO,QAAQ,CAAC,MAAM,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{x as e}from"./serializer-ettLu5xG.mjs";import{n as t,t as n}from"./libsql-DEZ0uhK2.mjs";import{t as r}from"./mysql-BFPF8xyv.mjs";import{t as i}from"./postgres-DQQE2ys_.mjs";import{t as a}from"./snowflake-BfF8xwfP.mjs";import{t as o}from"./surrealql-DY74AUeD.mjs";function s(){e(i),e(t),e(n),e(r),e(o),e(a)}export{s as t};
|
|
2
|
+
//# sourceMappingURL=every-JpbiHdMb.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"every-
|
|
1
|
+
{"version":3,"file":"every-JpbiHdMb.mjs","names":[],"sources":["../src/migrations/dialects/every.ts"],"sourcesContent":["/**\n * Every dialect's migration driver. Callers register from their own entry\n * statement (`viborm/migrations`, the CLI), so the registration stays with\n * the entry a bundler keeps.\n */\n\nimport { registerMigrationDriver } from \"../drivers\";\nimport { libsqlMigrationDriver } from \"../drivers/libsql\";\nimport { mysqlMigrationDriver } from \"../drivers/mysql\";\nimport { postgresMigrationDriver } from \"../drivers/postgres\";\nimport { snowflakeMigrationDriver } from \"../drivers/snowflake\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\nimport { surrealMigrationDriver } from \"../drivers/surrealql\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n registerMigrationDriver(surrealMigrationDriver);\n registerMigrationDriver(snowflakeMigrationDriver);\n}\n"],"mappings":"8QAcA,SAAgB,GAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB,CAC7C,EAAwB,EAAuB,CAC/C,EAAwB,EAAyB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{F as e,R as t,a as n,r,z as i}from"./error-mapping-B9rSvgG9.mjs";import{t as a}from"./base-17NSFtrA.mjs";function o(t,n,r,i){let a=r?.disclosure?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return e({model:t,operation:n,named:i},l,r,a)}function s(e,r){let o=t(e);if(o===void 0)return r();let s=i(e)?.disclosure,c=t=>{throw t instanceof a?n(t,{hb:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:o,diagnostics:s}):t};try{return r().catch(c)}catch(e){return Promise.reject().catch(()=>c(e))}}async function c(e,n,a){let o=i(e)?.disclosure;try{return await a()}catch(i){throw r(i,{driverName:n.driverName,dialect:n.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:t(e),diagnostics:o,hb:!0})}}function l(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}export{c as n,s as r,o as t};
|
|
2
|
+
//# sourceMappingURL=execution-context-couU2tgh.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-couU2tgh.mjs","names":[],"sources":["../src/query-engine/execution-context.ts"],"sourcesContent":["import { attachExecutionContext } from \"@drivers/driver-error-context\";\nimport { normalizeDriverError } from \"@drivers/error-mapping\";\nimport {\n createExecutionContext,\n getExecutionCallsite,\n getExecutionExtensionChain,\n} from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { VibORMError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { Operation } from \"./types\";\n\nexport function createOperationExecutionContext(\n model: string,\n operation: Operation | string,\n extensionChain?: ResolvedExtensionChain,\n named?: boolean\n): QueryExecutionContext {\n // Capture before asynchronous request/plan/provider work, and allocate no stack by default.\n const origin =\n extensionChain?.disclosure?.includeCallsite === true\n ? new Error(\"VibORM operation created here\").stack\n : undefined;\n return createExecutionContext(\n { model, operation, named },\n createCorrelationId,\n extensionChain,\n origin\n );\n}\n\n/** Preserve an ORM failure's deferred origin without wrapping errors returned by user extensions. */\nexport function withOperationErrorContext<T>(\n context: QueryExecutionContext,\n execute: () => Promise<T>\n): Promise<T> {\n const callsite = getExecutionCallsite(context);\n if (callsite === undefined) return execute();\n const diagnostics = getExecutionExtensionChain(context)?.disclosure;\n const annotate = (error: unknown): never => {\n throw error instanceof VibORMError\n ? attachExecutionContext(error, {\n forceContext: false,\n driverName:\n typeof error.meta.driver === \"string\"\n ? error.meta.driver\n : \"unknown\",\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n callsite,\n diagnostics,\n })\n : error;\n };\n try {\n return execute().catch(annotate);\n } catch (error) {\n return Promise.reject().catch(() => annotate(error));\n }\n}\n\n/** Observe native-batch preparation and parsing as one logical operation. */\nexport async function observeTransactionBatchPhase<R>(\n executionContext: QueryExecutionContext,\n driver: AnyDriver,\n execute: () => R | Promise<R>\n): Promise<R> {\n const diagnostics = getExecutionExtensionChain(executionContext)?.disclosure;\n try {\n return await execute();\n } catch (error) {\n throw normalizeDriverError(error, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n model: executionContext.model,\n operation: executionContext.operation,\n correlationId: executionContext.correlationId,\n callsite: getExecutionCallsite(executionContext),\n diagnostics,\n forceContext: true,\n });\n }\n}\n\nexport function createCorrelationId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `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
1
|
+
import { Gi as AnyModel, I as Extension, L as Facts, O as AnyTarget, wi as ClientSchema } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/client/omit.d.ts
|
|
4
4
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as e}from"./validation-ATmgN5RE.mjs";import{o as t}from"./value-guards-CBVIJXlI.mjs";const n=[`declare`,`join`,`seal`];function r(t,n){throw new e(t,{meta:n?{extension:n}:void 0})}function i(e,t,i,a,o,s){t?.extensions.some(e=>e.name===i)&&r(`Extension "${i}" is already present on this client.`,i);let c=new Set(e),l={...t,extensions:[...t?.extensions??[],{name:i}]},u={name:i,u9:t,next:l,owner:{name:i},schema:a,registry:s,wh:e=>{c.add(e)},g4:o};for(let e of n)for(let t of c)t[e]?.(u);return l}function a({g4:e,schema:t},n,r){let i=e.get(t),a=Object.keys(t);(i===void 0||a.length!==Object.keys(i.models).length||a.some(e=>i.models[e]!==t[e]))&&(i={models:{...t},values:new Map},e.set(t,i));let{values:o}=i;return o.has(n)||o.set(n,r()),o.get(n)}const o=e=>t(e)&&(typeof e.declare==`function`||typeof e.join==`function`||typeof e.seal==`function`);function s(e,...t){(typeof e!=`string`||e.trim().length===0)&&r(`An extension's name must be a non-empty string.`),t.every(o)||r(`Extension "${e}" takes parts built by viborm's part builders.`,e);let n=new WeakMap,a={name:e,append:(r,a,o)=>i(t,r,e,a,n,o)};return Object.freeze(a)}const c=e=>typeof e==`object`&&!!e&&`append`in e&&typeof e.append==`function`;export{a as i,c as n,r,s as t};
|
|
2
|
+
//# sourceMappingURL=extension-Dh1ddrlA.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-
|
|
1
|
+
{"version":3,"file":"extension-Dh1ddrlA.mjs","names":["extension"],"sources":["../src/extensions/chain.ts","../src/extensions/extension.ts"],"sourcesContent":["/**\n * The one mechanism that hosts extensions. A chain is the ordered list of the\n * extensions applied to a client, with what the parts each was built from\n * wrote on it. The chain knows no member and no part: an extension value is\n * its name and its parts (`extension.ts`), each part carries its own state\n * and writes it on the chain, and a program that builds no part of a kind\n * holds no code of that kind.\n */\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport type { ResolvedExtensionChain } from \"./chain-state\";\n\nexport type * from \"./chain-state\";\n\ntype Draft = {\n -readonly [K in keyof ResolvedExtensionChain]: ResolvedExtensionChain[K];\n};\n\n/**\n * One application of one extension: what its parts read and write. Two\n * parts of one extension meet here and only here: what one writes in\n * `declare` the others read in `join` (the extension's own arguments, on\n * `next` and `owner`; one rule layer for its `rule` parts, in `shared`).\n */\nexport interface Application {\n /** The extension's name. */\n readonly name: string;\n /** The chain the extension is applied to. */\n readonly chain: ResolvedExtensionChain | undefined;\n /** The chain being built: each part writes its own state on it. */\n readonly next: Draft;\n /** Who owns the handlers appended: the extension and its own arguments. */\n owner: { readonly name: string; readonly args?: readonly string[] };\n readonly schema: Schema;\n readonly registry?: SchemaRegistryLookup<Schema>;\n /**\n * Run `part` with the others, once: what a word written in a part needs\n * beside it (`keep` the kept rows, `omitted` the omission). Its phases\n * from the current one on run.\n */\n readonly bring: (part: ExtensionPart) => void;\n /** What the extension's parts made, per schema (`shared`). */\n readonly made: WeakMap<Schema, Made>;\n}\n\n/** What one extension's parts made of one schema, as its models were then. */\ninterface Made {\n readonly models: Schema;\n readonly values: Map<object, unknown>;\n}\n\n/**\n * One part an extension is built from, with its own state. Its phases run\n * for every part of the extension before the next phase starts, so a part\n * never depends on the order the parts were named in.\n */\nexport interface ExtensionPart {\n /** Write what the other parts of the same extension read. */\n readonly declare?: (application: Application) => void;\n readonly join?: (application: Application) => void;\n /** Once every part has joined. */\n readonly seal?: (application: Application) => void;\n}\n\nconst PHASES = [\"declare\", \"join\", \"seal\"] as const;\n\nexport function extensionError(message: string, extension?: string): never {\n throw new ClientInitializationError(message, {\n meta: extension ? { extension } : undefined,\n });\n}\n\n/**\n * `chain` with one extension appended by the parts named, by the parts they\n * use and by those their words bring, each once.\n */\nexport function appendParts(\n named: readonly ExtensionPart[],\n chain: ResolvedExtensionChain | undefined,\n name: string,\n schema: Schema,\n made: WeakMap<Schema, Made>,\n registry?: SchemaRegistryLookup<Schema>\n): ResolvedExtensionChain {\n if (chain?.extensions.some((extension) => extension.name === name))\n extensionError(\n `Extension \"${name}\" is already present on this client.`,\n name\n );\n // Insertion order: a part brought while a phase runs is reached by it.\n const parts = new Set(named);\n const next: Draft = {\n ...chain,\n extensions: [...(chain?.extensions ?? []), { name }],\n };\n const application: Application = {\n name,\n chain,\n next,\n owner: { name },\n schema,\n registry,\n bring: (part) => {\n parts.add(part);\n },\n made,\n };\n for (const phase of PHASES)\n for (const part of parts) part[phase]?.(application);\n return next;\n}\n\n/**\n * What the extension's parts make of this schema, by the key each part\n * chose, made once per schema: every client of a schema applies the same\n * values, so what is admitted once stays admitted. A schema object that\n * gained or swapped a model since is another schema.\n */\nexport function shared<T>(\n { made, schema }: Application,\n key: object,\n make: () => T\n): T {\n let known = made.get(schema);\n const names = Object.keys(schema);\n if (\n known === undefined ||\n names.length !== Object.keys(known.models).length ||\n names.some((name) => known!.models[name] !== schema[name])\n ) {\n known = { models: { ...schema }, values: new Map() };\n made.set(schema, known);\n }\n const { values } = known;\n if (!values.has(key)) values.set(key, make());\n // What `make` returned for this key, by the key's owner's contract.\n return values.get(key) as T;\n}\n","/**\n * `extension(name, ...parts)`: the one way an extension is written. Each part\n * is built by a function imported from `viborm` (`call`, `unit`, `rule`,\n * `defaults`, `args`, `methods`, `fields`, `disclosure`) and is the\n * `ExtensionPart` that joins the chain with its own state, so a program\n * holds the code of the parts it builds and nothing else. The value is\n * applied by `client.$extends(value)`.\n */\n\nimport type { Schema } from \"@client/types\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { appendParts, type ExtensionPart, extensionError } from \"./chain\";\nimport type { ResolvedExtensionChain } from \"./chain-state\";\nimport type {\n AnyFacts,\n AnyTarget,\n EmptyFacts,\n Extension,\n MergeAll,\n Part,\n With,\n} from \"./contract\";\n\n/** What `client.$extends` reads of an extension value. */\ninterface AppliedExtension {\n readonly name: string;\n readonly append: (\n chain: ResolvedExtensionChain | undefined,\n schema: Schema,\n registry?: SchemaRegistryLookup<Schema>\n ) => ResolvedExtensionChain;\n}\n\n/**\n * Whether `part` is one a builder made: a phase to run. Neither a builder\n * passed uncalled (`call` for `call(fn)`) nor an object of the old contract\n * (`{ query }`) is.\n */\nconst isPart = (part: unknown): part is ExtensionPart =>\n isRecord(part) &&\n (typeof part.declare === \"function\" ||\n typeof part.join === \"function\" ||\n typeof part.seal === \"function\");\n\n/**\n * An extension: a non-empty name and its parts, in order. At most eight: a\n * limit of the types (each part is typed against those before it), which\n * the runtime does not repeat.\n */\nexport function extension<\n T extends AnyTarget,\n F1 extends AnyFacts = EmptyFacts,\n F2 extends AnyFacts = EmptyFacts,\n F3 extends AnyFacts = EmptyFacts,\n F4 extends AnyFacts = EmptyFacts,\n F5 extends AnyFacts = EmptyFacts,\n F6 extends AnyFacts = EmptyFacts,\n F7 extends AnyFacts = EmptyFacts,\n F8 extends AnyFacts = EmptyFacts,\n>(\n name: string,\n p1?: Part<T, F1>,\n p2?: Part<With<T, F1>, F2>,\n p3?: Part<With<With<T, F1>, F2>, F3>,\n p4?: Part<With<With<With<T, F1>, F2>, F3>, F4>,\n p5?: Part<With<With<With<With<T, F1>, F2>, F3>, F4>, F5>,\n p6?: Part<With<With<With<With<With<T, F1>, F2>, F3>, F4>, F5>, F6>,\n p7?: Part<With<With<With<With<With<With<T, F1>, F2>, F3>, F4>, F5>, F6>, F7>,\n p8?: Part<\n With<With<With<With<With<With<With<T, F1>, F2>, F3>, F4>, F5>, F6>, F7>,\n F8\n >\n): Extension<T, MergeAll<F1, F2, F3, F4, F5, F6, F7, F8>>;\nexport function extension(name: string, ...parts: unknown[]): unknown {\n if (typeof name !== \"string\" || name.trim().length === 0)\n extensionError(\"An extension's name must be a non-empty string.\");\n if (!parts.every(isPart))\n extensionError(\n `Extension \"${name}\" takes parts built by viborm's part builders.`,\n name\n );\n const made = new WeakMap();\n const applied: AppliedExtension = {\n name,\n append: (chain, schema, registry) =>\n appendParts(parts, chain, name, schema, made, registry),\n };\n return Object.freeze(applied);\n}\n\n/** Whether `value` is an extension value `$extends` can apply. */\nexport const isAppliedExtension = (value: unknown): value is AppliedExtension =>\n typeof value === \"object\" &&\n value !== null &&\n \"append\" in value &&\n typeof value.append === \"function\";\n"],"mappings":"8FAiEA,MAAM,EAAS,CAAC,UAAW,OAAQ,OAAO,CAE1C,SAAgB,EAAe,EAAiB,EAA2B,CACzE,MAAM,IAAI,EAA0B,EAAS,CAC3C,KAAMA,EAAY,CAAE,UAAA,EAAW,CAAG,IAAA,GACnC,CAAC,CAOJ,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACwB,CACpB,GAAO,WAAW,KAAM,GAAcA,EAAU,OAAS,EAAK,EAChE,EACE,cAAc,EAAK,sCACnB,EACD,CAEH,IAAM,EAAQ,IAAI,IAAI,EAAM,CACtB,EAAc,CAClB,GAAG,EACH,WAAY,CAAC,GAAI,GAAO,YAAc,EAAE,CAAG,CAAE,OAAM,CAAC,CACrD,CACK,EAA2B,CAC/B,OACA,QACA,OACA,MAAO,CAAE,OAAM,CACf,SACA,WACA,MAAQ,GAAS,CACf,EAAM,IAAI,EAAK,EAEjB,OACD,CACD,IAAK,IAAM,KAAS,EAClB,IAAK,IAAM,KAAQ,EAAO,EAAK,KAAS,EAAY,CACtD,OAAO,EAST,SAAgB,EACd,CAAE,OAAM,UACR,EACA,EACG,CACH,IAAI,EAAQ,EAAK,IAAI,EAAO,CACtB,EAAQ,OAAO,KAAK,EAAO,EAE/B,IAAU,IAAA,IACV,EAAM,SAAW,OAAO,KAAK,EAAM,OAAO,CAAC,QAC3C,EAAM,KAAM,GAAS,EAAO,OAAO,KAAU,EAAO,GAAM,IAE1D,EAAQ,CAAE,OAAQ,CAAE,GAAG,EAAQ,CAAE,OAAQ,IAAI,IAAO,CACpD,EAAK,IAAI,EAAQ,EAAM,EAEzB,GAAM,CAAE,UAAW,EAGnB,OAFK,EAAO,IAAI,EAAI,EAAE,EAAO,IAAI,EAAK,GAAM,CAAC,CAEtC,EAAO,IAAI,EAAI,CClGxB,MAAM,EAAU,GACd,EAAS,EAAK,GACb,OAAO,EAAK,SAAY,YACvB,OAAO,EAAK,MAAS,YACrB,OAAO,EAAK,MAAS,YA+BzB,SAAgB,EAAU,EAAc,GAAG,EAA2B,EAChE,OAAO,GAAS,UAAY,EAAK,MAAM,CAAC,SAAW,IACrD,EAAe,kDAAkD,CAC9D,EAAM,MAAM,EAAO,EACtB,EACE,cAAc,EAAK,gDACnB,EACD,CACH,IAAM,EAAO,IAAI,QACX,EAA4B,CAChC,OACA,QAAS,EAAO,EAAQ,IACtB,EAAY,EAAO,EAAO,EAAM,EAAQ,EAAM,EAAS,CAC1D,CACD,OAAO,OAAO,OAAO,EAAQ,CAI/B,MAAa,EAAsB,GACjC,OAAO,GAAU,YACjB,GACA,WAAY,GACZ,OAAO,EAAM,QAAW"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./migrations-DIUltjr3.mjs";import{a as t,s as n}from"./identity-CJlRQA-m.mjs";import{closeSync as r,constants as i,existsSync as a,fsyncSync as o,linkSync as s,lstatSync as c,mkdirSync as l,openSync as u,readFileSync as d,readdirSync as f,unlinkSync as p,writeSync as m}from"node:fs";import{dirname as h,join as g,resolve as _}from"node:path";const v=`estate.json`;var y=class{le;constructor(e){this.le=_(e)}async readEstate(){return x(g(this.le,v))}async listStates(){return S(g(this.le,`states`),`.json`)}async listSnapshots(){return S(g(this.le,`snapshots`),`.json`)}async listSql(){return S(g(this.le,`sql`),`.sql`)}async readState(e){return x(g(this.le,`states`,`${e}.json`))}async readSnapshot(e){return x(g(this.le,`snapshots`,`${e}.json`))}async readSql(e){return x(g(this.le,`sql`,`${e}.sql`))}async publishEstate(e){return C(this.le,g(this.le,v),e)}async publishSnapshot(e,t){return C(this.le,g(this.le,`snapshots`,`${e}.json`),t)}async publishSql(e,t){return C(this.le,g(this.le,`sql`,`${e}.sql`),t)}async publishState(e,t){return C(this.le,g(this.le,`states`,`${e}.json`),t)}};function b(e){return new y(e)}function x(e){return a(e)?(T(e),new Uint8Array(d(e))):null}function S(e,n){if(!a(e))return[];T(e);let r=f(e),i=[];for(let e of r){if(e.startsWith(`.`)||e.endsWith(`.tmp`)||!e.endsWith(n))continue;let r=e.slice(0,-n.length);t(r)&&i.push(r)}return i.sort()}function C(t,c,f){A(t,c);let _=h(c);if(l(_,{recursive:!0}),T(_),a(c))return T(c),w(c,f);let v=g(_,`.${k()}.tmp`),y=u(v,i.O_CREAT|i.O_EXCL|i.O_WRONLY,420);try{m(y,f),o(y)}finally{r(y)}if(n(d(v))!==n(f))throw p(v),new e(`Temporary estate write did not round-trip`,`V11022`);try{s(v,c)}catch(t){if(D(v),O(t,`EEXIST`))return w(c,f);throw O(t,`EXDEV`)||O(t,`ENOSYS`)||O(t,`EPERM`)?new e(`Filesystem cannot atomically publish with a no-replace hard link`,`V11011`,{cause:t instanceof Error?t:void 0}):t}return D(v),E(_),{outcome:`created`}}function w(t,r){if(n(d(t))!==n(r))throw new e(`Content-addressed path ${t} already holds different bytes`,`V11022`);return E(h(t)),{outcome:`identical`}}function T(t){if(c(t).isSymbolicLink())throw new e(`Estate storage refuses to follow symlinks`,`V11012`)}function E(e){let t=u(e,i.O_RDONLY|i.O_DIRECTORY);try{o(t)}finally{r(t)}}function D(e){try{p(e)}catch{}}function O(e,t){return!!(e&&typeof e==`object`&&`code`in e&&e.code===t)}function k(){return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function A(t,n){let r=_(n),i=t.endsWith(`/`)?t:`${t}/`;if(r!==_(t)&&!r.startsWith(i))throw new e(`Estate path escapes the storage root`,`V11012`)}export{b as t};
|
|
2
|
+
//# sourceMappingURL=fs-estate-n-QpsFqb.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs-estate-D1Nsg9G1.mjs","names":[],"sources":["../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"2bA2BA,MAAM,EAAc,cAEpB,IAAM,gBAAN,KAAwD,CACtD,QAEA,YAAY,EAAiB,CAC3B,KAAK,QAAU,EAAQ,EAAQ,CAGjC,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,EAAY,CAAC,CAGtD,MAAM,YAAyC,CAC7C,OAAO,aAAa,EAAK,KAAK,QAAS,SAAS,CAAE,QAAQ,CAG5D,MAAM,eAA4C,CAChD,OAAO,aAAa,EAAK,KAAK,QAAS,YAAY,CAAE,QAAQ,CAG/D,MAAM,SAAsC,CAC1C,OAAO,aAAa,EAAK,KAAK,QAAS,MAAM,CAAE,OAAO,CAGxD,MAAM,UAAU,EAAwC,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,SAAU,GAAG,EAAG,OAAO,CAAC,CAGjE,MAAM,aAAa,EAA0C,CAC3D,OAAO,aAAa,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAAC,CAGtE,MAAM,QAAQ,EAA0C,CACtD,OAAO,aAAa,EAAK,KAAK,QAAS,MAAO,GAAG,EAAK,MAAM,CAAC,CAG/D,MAAM,cAAc,EAA2C,CAC7D,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,EAAY,CAC/B,EACD,CAGH,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,iBACL,KAAK,QACL,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAC/C,EACD,CAGH,MAAM,WAAW,EAAc,EAA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,EAAW,EAAQ,EAAK,CACxB,EAAO,EAAQ,SAAS,IAAI,CAAG,EAAU,GAAG,EAAQ,GAC1D,GAAI,IAAa,EAAQ,EAAQ,EAAI,CAAC,EAAS,WAAW,EAAK,CAC7D,MAAM,IAAI,EACR,uCACA,EAAgB,yBACjB"}
|
|
1
|
+
{"version":3,"file":"fs-estate-n-QpsFqb.mjs","names":[],"sources":["../src/migrations/storage/fs-estate.ts"],"sourcesContent":["/**\n * Filesystem estate writer.\n *\n * Publication is write-temp → fsync → rehash → hard-link no-replace →\n * verify EEXIST bytes → unlink temp → fsync directory. Check-then-rename\n * is forbidden.\n */\n\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n unlinkSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { isSha256, type Sha256, sha256Hex } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nconst ESTATE_NAME = \"estate.json\";\n\nclass FsEstateStorage implements MigrationStorageWriter {\n readonly baseDir: string;\n\n constructor(baseDir: string) {\n this.baseDir = resolve(baseDir);\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, ESTATE_NAME));\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"states\"), \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"snapshots\"), \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return listHexFiles(join(this.baseDir, \"sql\"), \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"states\", `${id}.json`));\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"snapshots\", `${hash}.json`));\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return readOptional(join(this.baseDir, \"sql\", `${hash}.sql`));\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, ESTATE_NAME),\n bytes\n );\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"snapshots\", `${hash}.json`),\n bytes\n );\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"sql\", `${hash}.sql`),\n bytes\n );\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishNoReplace(\n this.baseDir,\n join(this.baseDir, \"states\", `${id}.json`),\n bytes\n );\n }\n}\n\nexport function createFsStorageWriter(baseDir: string): MigrationStorageWriter {\n return new FsEstateStorage(baseDir);\n}\n\nfunction readOptional(path: string): Uint8Array | null {\n if (!existsSync(path)) return null;\n refuseSymlink(path);\n return new Uint8Array(readFileSync(path));\n}\n\nfunction listHexFiles(directory: string, suffix: string): Sha256[] {\n if (!existsSync(directory)) return [];\n refuseSymlink(directory);\n const names = readdirSync(directory);\n const hashes: Sha256[] = [];\n for (const name of names) {\n if (name.startsWith(\".\") || name.endsWith(\".tmp\")) continue;\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (!isSha256(hex)) continue;\n hashes.push(hex);\n }\n return hashes.sort();\n}\n\nfunction publishNoReplace(\n baseDir: string,\n finalPath: string,\n bytes: Uint8Array\n): PublishResult {\n assertInsideBase(baseDir, finalPath);\n const directory = dirname(finalPath);\n mkdirSync(directory, { recursive: true });\n refuseSymlink(directory);\n if (existsSync(finalPath)) {\n refuseSymlink(finalPath);\n return compareExisting(finalPath, bytes);\n }\n\n const tempPath = join(directory, `.${randomSuffix()}.tmp`);\n const fd = openSync(\n tempPath,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o644\n );\n try {\n writeSync(fd, bytes);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n\n const reread = readFileSync(tempPath);\n if (sha256Hex(reread) !== sha256Hex(bytes)) {\n unlinkSync(tempPath);\n throw new MigrationError(\n \"Temporary estate write did not round-trip\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n\n try {\n linkSync(tempPath, finalPath);\n } catch (error) {\n unlinkQuiet(tempPath);\n if (isErrno(error, \"EEXIST\")) {\n return compareExisting(finalPath, bytes);\n }\n if (\n isErrno(error, \"EXDEV\") ||\n isErrno(error, \"ENOSYS\") ||\n isErrno(error, \"EPERM\")\n ) {\n throw new MigrationError(\n \"Filesystem cannot atomically publish with a no-replace hard link\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n throw error;\n }\n\n unlinkQuiet(tempPath);\n fsyncDirectory(directory);\n return { outcome: \"created\" };\n}\n\nfunction compareExisting(path: string, bytes: Uint8Array): PublishResult {\n const existing = readFileSync(path);\n if (sha256Hex(existing) !== sha256Hex(bytes)) {\n throw new MigrationError(\n `Content-addressed path ${path} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n fsyncDirectory(dirname(path));\n return { outcome: \"identical\" };\n}\n\nfunction refuseSymlink(path: string): void {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n throw new MigrationError(\n \"Estate storage refuses to follow symlinks\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction fsyncDirectory(directory: string): void {\n const fd = openSync(\n directory,\n // biome-ignore lint/suspicious/noBitwiseOperators: POSIX open flags are one mask\n constants.O_RDONLY | constants.O_DIRECTORY\n );\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nfunction unlinkQuiet(path: string): void {\n try {\n unlinkSync(path);\n } catch {\n // temp cleanup is best-effort after the final name is visible\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return Boolean(\n error && typeof error === \"object\" && \"code\" in error && error.code === code\n );\n}\n\nfunction randomSuffix(): string {\n return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;\n}\n\nfunction assertInsideBase(baseDir: string, path: string): void {\n const resolved = resolve(path);\n const root = baseDir.endsWith(\"/\") ? baseDir : `${baseDir}/`;\n if (resolved !== resolve(baseDir) && !resolved.startsWith(root)) {\n throw new MigrationError(\n \"Estate path escapes the storage root\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n"],"mappings":"0WA2BA,MAAM,EAAc,cAEpB,IAAM,EAAN,KAAwD,CACtD,QAEA,YAAY,EAAiB,CAC3B,KAAK,QAAU,EAAQ,EAAQ,CAGjC,MAAM,YAAyC,CAC7C,OAAO,EAAa,EAAK,KAAK,QAAS,EAAY,CAAC,CAGtD,MAAM,YAAyC,CAC7C,OAAO,EAAa,EAAK,KAAK,QAAS,SAAS,CAAE,QAAQ,CAG5D,MAAM,eAA4C,CAChD,OAAO,EAAa,EAAK,KAAK,QAAS,YAAY,CAAE,QAAQ,CAG/D,MAAM,SAAsC,CAC1C,OAAO,EAAa,EAAK,KAAK,QAAS,MAAM,CAAE,OAAO,CAGxD,MAAM,UAAU,EAAwC,CACtD,OAAO,EAAa,EAAK,KAAK,QAAS,SAAU,GAAG,EAAG,OAAO,CAAC,CAGjE,MAAM,aAAa,EAA0C,CAC3D,OAAO,EAAa,EAAK,KAAK,QAAS,YAAa,GAAG,EAAK,OAAO,CAAC,CAGtE,MAAM,QAAQ,EAA0C,CACtD,OAAO,EAAa,EAAK,KAAK,QAAS,MAAO,GAAG,EAAK,MAAM,CAAC,CAG/D,MAAM,cAAc,EAA2C,CAC7D,OAAO,EACL,KAAK,QACL,EAAK,KAAK,QAAS,EAAY,CAC/B,EACD,CAGH,MAAM,gBAC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,GAAG,CAAC,MAAM,EAAE,GAG1E,SAAS,EAAiB,EAAiB,EAAoB,CAC7D,IAAM,EAAW,EAAQ,EAAK,CACxB,EAAO,EAAQ,SAAS,IAAI,CAAG,EAAU,GAAG,EAAQ,GAC1D,GAAI,IAAa,EAAQ,EAAQ,EAAI,CAAC,EAAS,WAAW,EAAK,CAC7D,MAAM,IAAI,EACR,uCACA,SACD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{J as e,Q as t,S as n,Ut as r,Y as i,d as a,f as o,it as s,rt as c,u as l,w as u}from"./native-types-1ewJXVks.mjs";const d=1e-10,f=Math.PI/180,p=6371008.8,m=(e=-90,t=90)=>({south:e,west:-180,north:t,east:180});function h({latitude:e,longitude:t},n){if(n<=0)return{south:e,west:t,north:e,east:t};let r=n/p;if(r>=Math.PI)return m();let i=r/f,a=Math.max(-90,e-i-d),o=Math.min(90,e+i+d);if(a===-90||o===90)return m(a,o);let s=Math.asin(Math.min(1,Math.sin(r)/Math.cos(e*f)))/f+d;return{south:a,west:g(t-s),north:o,east:g(t+s)}}function g(e){return((e+180)%360+360)%360-180}const _=n({south:l,west:a,north:l,east:a},{partial:!1});function v(e){let t=s(_,e);return t.issues?t:t.value.south>t.value.north?i(`south > north`,[`south`]):t}const y=(e,t)=>i(`GeoPolygon ${e}`,t);function b(e){let n=c(e,t);return n.issues?n:n.value.length<r?y(`ring needs >= ${r} vertices`):c(n.value,o)}const x=n({outer:e(`array`,b),holes:u(e(`array`,e=>c(e,b)))},{partial:!1}),S=1e-9*f,C=2*Math.sin(.005*f),w=`contains pole`,T=`self-intersects`,E=`hole outside ring`,D=`holes overlap`,O=1/0;function k(e,t){let n=Math.cos(t*f);return[n*Math.cos(e*f),n*Math.sin(e*f),Math.sin(t*f)]}function A(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function j(e,t){let n=e[0]-t[0],r=e[1]-t[1],i=e[2]-t[2],a=e[0]+t[0],o=e[1]+t[1],s=e[2]+t[2];return[(r*s-i*o)/2,(i*a-n*s)/2,(n*o-r*a)/2]}function M(e){let t=Math.hypot(...e);return[e[0]/t,e[1]/t,e[2]/t]}function N(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2])}function P(e){return[-e[0],-e[1],-e[2]]}const F=e=>e>180?-360:e<-180?360:0,I=e=>e===180?-180:e;function L(e,n){let r=[];for(let t=0;t<e.length;t++){let i=e[t],a=k(i.longitude,i.latitude);if(Math.hypot(a[0],a[1])<=S)return y(w,[...n,t]);let o=r.at(-1);(!o||N(o.v,a)>S)&&r.push({pt:i,i:t,v:a})}let i=r[0],a=r.at(-1);i&&a&&N(a.v,i.v)>S&&r.push(i);let o=0;for(let e=1;e<r.length;e++)o+=F(r[e].pt.longitude-r[e-1].pt.longitude);let s=[],c=0,l,u;for(let{pt:e,i:t,v:i}of r){let r;if(l){let t=e.longitude-l.raw;Math.abs(t)===180&&(r=[0,0,Math.sign(e.latitude+l.g5)],Math.abs(t-o)===180&&(c-=o)),c+=F(t)}let a={f8:e.longitude+c,g5:e.latitude,raw:e.longitude,v:i};if(l){if(N(P(l.v),i)<C)return y(`antipodal edge`,[...n,t]);if(r&&u&&r[2]!==u[2])return y(w,[...n]);u??=r,s.push({f:l,t:a,s:l.v,e:i,n:M(j(l.v,i)),p:r})}l=a}if(c!==0)return y(w,[...n]);let[d,...f]=s;if(!d||f.length<3&&f.every(({s:e})=>Math.abs(R(d,e))<=S))return y(`zero area ring`,[...n]);for(let e=0;e<s.length;e++){let t=s[e],r=s[(e+1)%s.length];if(z(r.e,t)||z(t.s,r))return y(T,[...n])}return t([d,...f])}function R(e,t){return A(e.n,t)}function z(e,t){return Math.abs(R(t,e))<=S&&A(j(t.s,e),t.n)>=-S&&A(j(e,t.e),t.n)>=-S}function B(e,t){return e>S&&t<-S||e<-S&&t>S}function V(e,t){if(!(B(R(e,t.s),R(e,t.e))&&B(R(t,e.s),R(t,e.e))))return!1;let n=j(e.n,t.n);return A(n,e.s)+A(n,e.e)>0==A(n,t.s)+A(n,t.e)>0}function H(e,t){return V(e,t)||z(e.s,t)||z(e.e,t)||z(t.s,e)||z(t.e,e)}function U(e,t){let n=A(t.n,e.w);return Math.abs(n)>S?n<0:A(t.n,e.e)<0}function W(e,t){let n=e;for(let e=23;e>=0;e--){let r=n.n[e];for(;r?.s&&A(r.s.n,t)>S;)n=r,r=n.n[e]}return n}function G(e,t,n){let r={s:t,p:Array(n),n:Array(n)},i=e;for(let e=23;e>=0;e--){let a=i.n[e];for(;a?.s&&!U(t,a.s);)i=a,a=i.n[e];e<n&&(r.p[e]=i,r.n[e]=a,a&&(a.p[e]=r),i.n[e]=r)}return r}function K(e){for(let t=0;t<e.p.length;t++){let n=e.p[t],r=e.n[t];n.n[t]=r,r&&(r.p[t]=n)}}const q=k(180,0);function J(e){let t=M(j(e.n,[-q[1],q[0],0]));return A(t,q)<0?P(t):t}function Y(e,t,n,r,i){let a={s:i,e:void 0};e.push({x:t,k:1,s:a},{x:n,k:r,s:a})}function X(e,t){let{f:n,t:r,n:i,p:a}=e.a,o=I(n.raw),s=I(r.raw);if(o===s){let[i,a]=n.g5<r.g5?[n,r]:[r,n];t.push({x:o,k:2,u:{p:e,s:i.v,n:a.v}});return}let c=n.f8<r.f8,[l,u]=c?[n,r]:[r,n],d=c?i:P(i),[f,p]=c?[o,s]:[s,o],m=(n,r,i,a,o)=>Y(t,n,r,i,{p:e,w:a,e:o,n:d,ew:c});if(a){for(let{raw:i,v:o}of[n,r])t.push({x:I(i),k:2,u:{p:e,s:a[2]>0?o:a,n:a[2]>0?a:o}});f<p?m(f,p,0,a,a):(m(f,180,0,a,a),p>-180&&m(-180,p,0,a,a));return}f<p?m(f,p,3,l.v,u.v):(m(f,180,3,l.v,u.v),m(-180,p,3,J(e.a),u.v))}function Z(e){return Math.atan2(e[2],Math.hypot(e[0],e[1]))}function Q(e,t){let n=[];for(let t of e)X(t,n);n.sort((e,t)=>e.x-t.x||e.k-t.k);let r={s:void 0,p:Array(24),n:Array(24)},i=(e,n)=>e&&n&&!t(e,n)&&H(e.a,n.a)?[e,n]:void 0,a=[],o=new Map,s=()=>{let e=Array.from(o,([e,{e:t,w:n}])=>{let r=t.n[0];for(;r?.s?.p.r===e;)r=r.n[0];return{r:e,h:Z(n),n:r?.s}});e.sort((e,t)=>t.h-e.h);for(let t of e)a.push(t);o.clear()},c=new Set;for(let e=0;e<n.length;e++){let t=n[e];if(t.k===1){let a=1+Math.floor(-Math.log2(1-Math.random())),l=t.s.s,u=G(r,l,Math.min(24,a));t.s.e=u;let d=i(u.p[0]?.s?.p,l.p)??i(l.p,u.n[0]?.s?.p);if(d)return{m:d};let{p:f,w:p}=l,m=o.get(f.r);(!c.has(f.r)||m&&Z(p)>Z(m.w))&&(c.add(f.r),o.set(f.r,{e:u,w:p}));let h=n[e+1];(h?.k!==1||h.x!==t.x)&&s()}else if(t.k===2){let{u:e}=t,n=W(r,e.s);for(n=n.s?n:n.n[0];n?.s;){let t=i(e.p,n.s.p);if(t)return{m:t};if(A(n.s.n,e.n)<-S)break;n=n.n[0]}}else if(t.s.e){let e=t.s.e;K(e);let n=i(e.p[0]?.s?.p,e.n[0]?.s?.p);if(n)return{m:n}}}return{p:a}}function ee(e){let t=0,n=0,r,i=0;for(let a of e){let e=j(a.s,a.e)[2],o=1+A(a.s,a.e),s=a.s[2]+a.e[2];s>=0?(t+=2*Math.atan2(e,o+s),r!==void 0&&(n+=a.f.f8-r),r=void 0):(t+=2*Math.atan2(-e,o-s),r??=a.f.f8),i=a.t.f8}return r!==void 0&&(n+=i-r),t+2*n*f}function $(e,t,n){return{i:n,h:n===0?O:n-1,g6:e,a:t,g1:ee(t)>0,out:void 0,in:!1,fa:O,fw:O}}function te(e){let n=s(x,e);if(n.issues)return n;let r=L(n.value.outer,[`outer`]);if(r.issues)return r;let i=$(n.value.outer,r.value,0),a=[],o=n.value.holes??[];for(let e=0;e<o.length;e++){let t=o[e],n=L(t,[`holes`,e]);if(n.issues)return n;a.push($(t,n.value,e+1))}let c=[];for(let e=0;e<=a.length;e++){let t=e===0?i:a[e-1];for(let e=0;e<t.a.length;e++)c.push({a:t.a[e],r:t,i:e})}let l=Q(c,(e,t)=>{if(e.r!==t.r)return!1;let n=Math.abs(e.i-t.i);return n<=1||n===e.r.a.length-1});if(l.m){let[e,t]=l.m,n=Math.max(e.r.i,t.r.i),r=n===0?[`outer`]:[`holes`,n-1];return y(e.r===t.r?T:Math.min(e.r.i,t.r.i)===0?E:D,r)}for(let{r:e,n:t}of l.p){let n=t?.p.r,r=n===void 0||n.g1!==t?.ew?n:n.out;e.out=r,e.in=r!==void 0&&(r.i===0||r.in),e.fa=r?Math.min(r.h,r.fa):O}for(let{r:e}of l.p.reverse()){let{out:t}=e;t&&(t.fw=Math.min(t.fw,e.h,e.fw))}for(let{h:e,in:t,fa:n,fw:r}of a){if(!t)return y(E,[`holes`,e]);if(Math.min(n,r)<e)return y(D,[`holes`,e])}let u=i.g1?i.g6:i.g6.reverse(),d=a.map(({g6:e,g1:t})=>t?e.reverse():e);return t(d.length>0?{outer:u,holes:d}:{outer:u})}const ne=n({bounds:e(`object`,v),polygon:e(`object`,te)});function re(e){let n=s(ne,e);if(n.issues)return n;let{bounds:r,polygon:a}=n.value;return r&&!a?t({bounds:r}):a&&!r?t({polygon:a}):i(`Expected bounds or polygon`)}function ie(){return e(`geo_area`,re)}export{ie as n,h as r,p as t};
|
|
2
|
+
//# sourceMappingURL=geo-area-codec-Bti2PA2i.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"geo-area-codec-Bti2PA2i.mjs","names":["latitude","north"],"sources":["../src/validation/primitives/geo-area-codec.ts"],"sourcesContent":["import type { ValidationResult, VibSchema } from \"../types\";\nimport { geoLatitude, geoLongitude, validateGeoPoint } from \"./geo-point-codec\";\nimport {\n GEO_POLYGON_MIN_RING_POINTS,\n type GeoArea,\n type GeoBounds,\n type GeoPoint,\n type GeoPolygon,\n} from \"./geo-values\";\nimport {\n createSchema,\n fail,\n ok,\n validateArray,\n validateSchema,\n} from \"./helpers\";\nimport { object } from \"./object\";\nimport { optional } from \"./optional\";\n\nexport type { GeoArea, GeoBounds, GeoPolygon } from \"./geo-values\";\n\nconst OUTWARD_BOUND_DEGREES = 1e-10;\nconst RADIANS = Math.PI / 180;\n\n/** The fixed spherical Earth model shared by portable GeoPoint distance SQL. */\nexport const GEO_POINT_EARTH_RADIUS_METERS = 6_371_008.8;\n\n/**\n * Construct the smallest conservative latitude/longitude rectangle around a\n * trusted spherical distance cap. The exact distance predicate remains the\n * membership owner; this rectangle is only an index-friendly superset.\n */\nconst fullBounds = (south = -90, north = 90): GeoBounds => ({\n south,\n west: -180,\n north,\n east: 180,\n});\n\nexport function geoBoundsForDistance(\n { latitude, longitude }: GeoPoint,\n meters: number\n): GeoBounds {\n if (meters <= 0) {\n return {\n south: latitude,\n west: longitude,\n north: latitude,\n east: longitude,\n };\n }\n\n const angularRadius = meters / GEO_POINT_EARTH_RADIUS_METERS;\n if (angularRadius >= Math.PI) return fullBounds();\n\n const latitudeDelta = angularRadius / RADIANS;\n const south = Math.max(-90, latitude - latitudeDelta - OUTWARD_BOUND_DEGREES);\n const north = Math.min(90, latitude + latitudeDelta + OUTWARD_BOUND_DEGREES);\n if (south === -90 || north === 90) return fullBounds(south, north);\n\n const longitudeDelta =\n Math.asin(\n Math.min(1, Math.sin(angularRadius) / Math.cos(latitude * RADIANS))\n ) /\n RADIANS +\n OUTWARD_BOUND_DEGREES;\n return {\n south,\n west: normalizeLongitude(longitude - longitudeDelta),\n north,\n east: normalizeLongitude(longitude + longitudeDelta),\n };\n}\n\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n\nconst boundsRecord = object(\n {\n south: geoLatitude,\n west: geoLongitude,\n north: geoLatitude,\n east: geoLongitude,\n },\n { partial: false }\n);\n\nexport function validateGeoBounds(value: unknown): ValidationResult<GeoBounds> {\n const bounds = validateSchema(boundsRecord, value);\n if (bounds.issues) return bounds;\n if (bounds.value.south > bounds.value.north) {\n return fail(\"south > north\", [\"south\"]);\n }\n return bounds;\n}\n\nconst polyFail = (message: string, path?: PropertyKey[]) =>\n fail(`GeoPolygon ${message}`, path);\n\nfunction validateRing(value: unknown): ValidationResult<GeoPoint[]> {\n const members = validateArray(value, ok);\n if (members.issues) return members;\n if (members.value.length < GEO_POLYGON_MIN_RING_POINTS) {\n return polyFail(`ring needs >= ${GEO_POLYGON_MIN_RING_POINTS} vertices`);\n }\n return validateArray(members.value, validateGeoPoint);\n}\n\nconst polygonRecord = object(\n {\n outer: createSchema(\"array\", validateRing),\n holes: optional(\n createSchema(\"array\", (value) => validateArray(value, validateRing))\n ),\n },\n { partial: false }\n);\n\n/*\n * Polygon geometry, judged after the record walker admitted the shape.\n * VibORM reads an edge as the great-circle arc between its vertices, so\n * crossings, touches and containment are judged on the unit sphere, never on\n * straight longitude/latitude lines, and the polygon is the side of its outer\n * ring away from both poles.\n *\n * Refused as having no single meaning on that reading: a ring crossing,\n * touching or retracing itself, a ring of zero area, a hole not strictly\n * inside its outer ring, holes touching or overlapping.\n *\n * DOMAIN CHOICES, each made for the reason given, not a property every valid\n * polygon lacks. A new refusal needs a reason of this kind; \"invalid\n * geometry\" is not one.\n * - Resolution, TOLERANCE (1e-9 degrees): exact tests on float64 vectors need\n * a margin for rounding, one for every ring size. Within it a point is on\n * what it touches: rings closer than it touch and are refused, and an edge\n * shorter than it is a repeated vertex.\n * - Near-antipodal edges, NEAREST_ANTIPODE (0.01 degrees): nearer to\n * antipodal, one float64 step of a written coordinate turns the edge's\n * great circle by more than a third of TOLERANCE, so the coordinates do not\n * fix the edge; it is refused.\n * - Poles: a vertex within TOLERANCE of a pole has no longitude, and a ring\n * winding around a pole or running over both has no side away from both;\n * both are refused. An edge whose longitudes differ by exactly 180 degrees\n * runs over the pole on its vertices' side, and is admitted.\n *\n * A valid polygon is not refused because a database reads it differently:\n * MySQL draws edges on the ellipsoid, PostGIS misreads some rings reaching\n * across all three coordinate planes (docs/content/docs/schema/scalars/\n * point.mdx, \"How each database reads a polygon\", gives the measured\n * differences).\n */\n\ntype Vector = readonly [x: number, y: number, z: number];\n\n/** One ring vertex, its longitude unwrapped past ±180 along the ring. */\ninterface UnwrappedPoint {\n readonly lon: number;\n readonly phi: number;\n /** The longitude as written, where `sweep` places it. */\n readonly raw: number;\n /** The vertex on the unit sphere, from its written coordinates. */\n readonly v: Vector;\n}\n\n/** One ring edge: the great-circle arc from `f` to `t`. */\ninterface Arc {\n readonly f: UnwrappedPoint;\n readonly t: UnwrappedPoint;\n readonly s: Vector;\n readonly e: Vector;\n /** The unit normal of the arc's great circle, start × end. */\n readonly n: Vector;\n /** The pole the arc runs over when its longitudes differ by exactly 180 degrees. */\n readonly p: Vector | undefined;\n}\n\n/** A ring's arcs; a ring is refused before it could have fewer than two. */\ntype Ring = readonly [Arc, ...Arc[]];\n\n/**\n * Resolution (1e-9 degrees, ~0.1 mm): a point this near an arc is on it, and\n * an edge this short is a repeated vertex.\n */\nconst TOLERANCE = 1e-9 * RADIANS;\n/**\n * Near-antipodal chord cutoff (0.01 degrees): closer than this, one float64\n * coordinate step turns the edge's great circle past a third of TOLERANCE.\n */\nconst NEAREST_ANTIPODE = 2 * Math.sin(0.005 * RADIANS);\n\nconst ERR_POLE = \"contains pole\";\nconst ERR_SELF = \"self-intersects\";\nconst ERR_OUTSIDE = \"hole outside ring\";\nconst ERR_OVERLAP = \"holes overlap\";\nconst INF = Number.POSITIVE_INFINITY;\n\nfunction toVector(longitude: number, latitude: number): Vector {\n const cosine = Math.cos(latitude * RADIANS);\n return [\n cosine * Math.cos(longitude * RADIANS),\n cosine * Math.sin(longitude * RADIANS),\n Math.sin(latitude * RADIANS),\n ];\n}\n\nfunction dot(first: Vector, second: Vector): number {\n return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];\n}\n\n/**\n * first × second, taken as (first − second) × (first + second) / 2 so short\n * arcs keep their exact normal direction.\n */\nfunction cross(first: Vector, second: Vector): Vector {\n const dx = first[0] - second[0];\n const dy = first[1] - second[1];\n const dz = first[2] - second[2];\n const sx = first[0] + second[0];\n const sy = first[1] + second[1];\n const sz = first[2] + second[2];\n return [\n (dy * sz - dz * sy) / 2,\n (dz * sx - dx * sz) / 2,\n (dx * sy - dy * sx) / 2,\n ];\n}\n\nfunction unit(vector: Vector): Vector {\n const length = Math.hypot(...vector);\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nfunction chord(first: Vector, second: Vector): number {\n return Math.hypot(\n first[0] - second[0],\n first[1] - second[1],\n first[2] - second[2]\n );\n}\n\nfunction antipode(vector: Vector): Vector {\n return [-vector[0], -vector[1], -vector[2]];\n}\n\n/** What an edge adds to its end's longitude to take the short way round. */\nconst shortWay = (delta: number): number =>\n delta > 180 ? -360 : delta < -180 ? 360 : 0;\n\nconst wrapLon = (w: number): number => (w === 180 ? -180 : w);\n\n/**\n * The ring's arcs, each taking the short way round in longitude. An edge\n * whose longitudes differ by exactly 180 degrees runs over the pole on the\n * side of its endpoints' mean latitude.\n */\nfunction ringArcs(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Ring> {\n const distinct: {\n readonly pt: GeoPoint;\n readonly i: number;\n readonly v: Vector;\n }[] = [];\n for (let i = 0; i < ring.length; i++) {\n const pt = ring[i]!;\n const v = toVector(pt.longitude, pt.latitude);\n if (Math.hypot(v[0], v[1]) <= TOLERANCE) {\n return polyFail(ERR_POLE, [...path, i]);\n }\n const last = distinct.at(-1);\n if (!last || chord(last.v, v) > TOLERANCE) {\n distinct.push({ pt, i, v });\n }\n }\n const firstVertex = distinct[0];\n const lastVertex = distinct.at(-1);\n if (\n firstVertex &&\n lastVertex &&\n chord(lastVertex.v, firstVertex.v) > TOLERANCE\n ) {\n distinct.push(firstVertex);\n }\n let turn = 0;\n for (let i = 1; i < distinct.length; i++) {\n turn += shortWay(distinct[i]!.pt.longitude - distinct[i - 1]!.pt.longitude);\n }\n const arcs: Arc[] = [];\n let wrap = 0;\n let from: UnwrappedPoint | undefined;\n let overPole: Vector | undefined;\n for (const { pt, i, v } of distinct) {\n let p: Vector | undefined;\n if (from) {\n const delta = pt.longitude - from.raw;\n if (Math.abs(delta) === 180) {\n p = [0, 0, Math.sign(pt.latitude + from.phi)];\n if (Math.abs(delta - turn) === 180) wrap -= turn;\n }\n wrap += shortWay(delta);\n }\n const to: UnwrappedPoint = {\n lon: pt.longitude + wrap,\n phi: pt.latitude,\n raw: pt.longitude,\n v,\n };\n if (from) {\n if (chord(antipode(from.v), v) < NEAREST_ANTIPODE) {\n return polyFail(\"antipodal edge\", [...path, i]);\n }\n if (p && overPole && p[2] !== overPole[2]) {\n return polyFail(ERR_POLE, [...path]);\n }\n overPole ??= p;\n arcs.push({\n f: from,\n t: to,\n s: from.v,\n e: v,\n n: unit(cross(from.v, v)),\n p,\n });\n }\n from = to;\n }\n if (wrap !== 0) return polyFail(ERR_POLE, [...path]);\n const [first, ...rest] = arcs;\n if (\n !first ||\n (rest.length < 3 &&\n rest.every(({ s }) => Math.abs(side(first, s)) <= TOLERANCE))\n ) {\n return polyFail(\"zero area ring\", [...path]);\n }\n for (let i = 0; i < arcs.length; i++) {\n const behind = arcs[i]!;\n const arc = arcs[(i + 1) % arcs.length]!;\n if (onArc(arc.e, behind) || onArc(behind.s, arc)) {\n return polyFail(ERR_SELF, [...path]);\n }\n }\n return ok([first, ...rest]);\n}\n\n/** The sine of the point's signed angular distance from the arc's circle. */\nfunction side(arc: Arc, point: Vector): number {\n return dot(arc.n, point);\n}\n\nfunction onArc(point: Vector, arc: Arc): boolean {\n return (\n Math.abs(side(arc, point)) <= TOLERANCE &&\n dot(cross(arc.s, point), arc.n) >= -TOLERANCE &&\n dot(cross(point, arc.e), arc.n) >= -TOLERANCE\n );\n}\n\nfunction opposite(first: number, second: number): boolean {\n return (\n (first > TOLERANCE && second < -TOLERANCE) ||\n (first < -TOLERANCE && second > TOLERANCE)\n );\n}\n\nfunction crosses(first: Arc, second: Arc): boolean {\n if (\n !(\n opposite(side(first, second.s), side(first, second.e)) &&\n opposite(side(second, first.s), side(second, first.e))\n )\n ) {\n return false;\n }\n const meeting = cross(first.n, second.n);\n return (\n dot(meeting, first.s) + dot(meeting, first.e) > 0 ===\n dot(meeting, second.s) + dot(meeting, second.e) > 0\n );\n}\n\nfunction meet(first: Arc, second: Arc): boolean {\n return (\n crosses(first, second) ||\n onArc(first.s, second) ||\n onArc(first.e, second) ||\n onArc(second.s, first) ||\n onArc(second.e, first)\n );\n}\n\n/** One ring of the polygon, and where `sweep` places it among the others. */\ninterface RingNode {\n /** 0 the outer ring, then the holes. */\n readonly i: number;\n /** The ring's index in `holes`, Infinity for the outer ring. */\n readonly h: number;\n readonly pts: GeoPoint[];\n readonly a: Ring;\n readonly ccw: boolean;\n out: RingNode | undefined;\n in: boolean;\n fa: number;\n fw: number;\n}\n\n/** An arc of `r` at `i` along it. */\ninterface Placed {\n readonly a: Arc;\n readonly r: RingNode;\n readonly i: number;\n}\n\n/** One stretch of an arc between two meridians, ordered from its west end. */\ninterface Stretch {\n readonly p: Placed;\n readonly w: Vector;\n readonly e: Vector;\n /** The arc's unit normal, turned north. */\n readonly n: Vector;\n /** Whether the arc runs east, so that its normal is `n`. */\n readonly ew: boolean;\n}\n\n/** An arc along a meridian, which the sweep meets at one longitude. */\ninterface Upright {\n readonly p: Placed;\n readonly s: Vector;\n readonly n: Vector;\n}\n\n/** A stretch in the sweep's south-to-north order, a skip list. */\ninterface Entry {\n readonly s: Stretch | undefined;\n readonly p: (Entry | undefined)[];\n readonly n: (Entry | undefined)[];\n}\n\nconst LEVELS = 24;\n\nfunction below(entering: Stretch, resident: Stretch): boolean {\n const height = dot(resident.n, entering.w);\n return Math.abs(height) > TOLERANCE\n ? height < 0\n : dot(resident.n, entering.e) < 0;\n}\n\n/** The last entry south of `point` on the sweep's meridian, or the head. */\nfunction southOf(head: Entry, point: Vector): Entry {\n let cursor = head;\n for (let at = LEVELS - 1; at >= 0; at--) {\n let next = cursor.n[at];\n while (next?.s && dot(next.s.n, point) > TOLERANCE) {\n cursor = next;\n next = cursor.n[at];\n }\n }\n return cursor;\n}\n\nfunction enter(head: Entry, s: Stretch, height: number): Entry {\n const entry: Entry = { s, p: new Array(height), n: new Array(height) };\n let cursor = head;\n for (let level = LEVELS - 1; level >= 0; level--) {\n let next = cursor.n[level];\n while (next?.s && !below(s, next.s)) {\n cursor = next;\n next = cursor.n[level];\n }\n if (level < height) {\n entry.p[level] = cursor;\n entry.n[level] = next;\n if (next) next.p[level] = entry;\n cursor.n[level] = entry;\n }\n }\n return entry;\n}\n\nfunction leave(entry: Entry): void {\n for (let level = 0; level < entry.p.length; level++) {\n const before = entry.p[level]!;\n const after = entry.n[level];\n before.n[level] = after;\n if (after) after.p[level] = before;\n }\n}\n\n/** The antimeridian on the equator. */\nconst ANTIMERIDIAN = toVector(180, 0);\n\n/** The point where the arc crosses the antimeridian. */\nfunction atAntimeridian(arc: Arc): Vector {\n const meeting = unit(cross(arc.n, [-ANTIMERIDIAN[1], ANTIMERIDIAN[0], 0]));\n return dot(meeting, ANTIMERIDIAN) < 0 ? antipode(meeting) : meeting;\n}\n\ntype Event =\n | { readonly x: number; readonly k: 0 | 3; readonly s: Slot }\n | { readonly x: number; readonly k: 1; readonly s: Slot }\n | { readonly x: number; readonly k: 2; readonly u: Upright };\n\ninterface Slot {\n readonly s: Stretch;\n e: Entry | undefined;\n}\n\nfunction addSlotEvents(\n events: Event[],\n start: number,\n end: number,\n endKind: 0 | 3,\n s: Stretch\n): void {\n const slot: Slot = { s, e: undefined };\n events.push({ x: start, k: 1, s: slot }, { x: end, k: endKind, s: slot });\n}\n\nfunction addArcEvents(p: Placed, events: Event[]): void {\n const { f, t, n, p: pole } = p.a;\n const first = wrapLon(f.raw);\n const second = wrapLon(t.raw);\n if (first === second) {\n const [south, north] = f.phi < t.phi ? [f, t] : [t, f];\n events.push({ x: first, k: 2, u: { p, s: south.v, n: north.v } });\n return;\n }\n const ew = f.lon < t.lon;\n const [west, east] = ew ? [f, t] : [t, f];\n const north = ew ? n : antipode(n);\n const [low, high] = ew ? [first, second] : [second, first];\n const emit = (\n start: number,\n end: number,\n endKind: 0 | 3,\n w: Vector,\n e: Vector\n ) => addSlotEvents(events, start, end, endKind, { p, w, e, n: north, ew });\n if (pole) {\n for (const { raw, v } of [f, t]) {\n events.push({\n x: wrapLon(raw),\n k: 2,\n u: { p, s: pole[2] > 0 ? v : pole, n: pole[2] > 0 ? pole : v },\n });\n }\n if (low < high) emit(low, high, 0, pole, pole);\n else {\n emit(low, 180, 0, pole, pole);\n if (high > -180) emit(-180, high, 0, pole, pole);\n }\n return;\n }\n if (low < high) emit(low, high, 3, west.v, east.v);\n else {\n emit(low, 180, 3, west.v, east.v);\n emit(-180, high, 3, atAntimeridian(p.a), east.v);\n }\n}\n\nfunction latitude(point: Vector): number {\n return Math.atan2(point[2], Math.hypot(point[0], point[1]));\n}\n\ninterface Placement {\n readonly r: RingNode;\n readonly n: Stretch | undefined;\n}\n\ntype Swept =\n | { readonly m: readonly [Placed, Placed] }\n | { readonly m?: undefined; readonly p: Placement[] };\n\nfunction sweep(\n arcs: readonly Placed[],\n apart: (first: Placed, second: Placed) => boolean\n): Swept {\n const events: Event[] = [];\n for (const arc of arcs) addArcEvents(arc, events);\n events.sort((left, right) => left.x - right.x || left.k - right.k);\n const head: Entry = {\n s: undefined,\n p: new Array(LEVELS),\n n: new Array(LEVELS),\n };\n const meeting = (\n first: Placed | undefined,\n second: Placed | undefined\n ): readonly [Placed, Placed] | undefined =>\n first && second && !apart(first, second) && meet(first.a, second.a)\n ? [first, second]\n : undefined;\n const placements: Placement[] = [];\n const arrivals = new Map<RingNode, { e: Entry; w: Vector }>();\n const placeArrivals = (): void => {\n const arrived = Array.from(arrivals, ([r, { e, w }]) => {\n let next = e.n[0];\n while (next?.s?.p.r === r) next = next.n[0];\n return { r, h: latitude(w), n: next?.s };\n });\n arrived.sort((left, right) => right.h - left.h);\n for (const item of arrived) placements.push(item);\n arrivals.clear();\n };\n const met = new Set<RingNode>();\n for (let index = 0; index < events.length; index++) {\n const event = events[index]!;\n if (event.k === 1) {\n const height = 1 + Math.floor(-Math.log2(1 - Math.random()));\n const stretch = event.s.s;\n const entry = enter(head, stretch, Math.min(LEVELS, height));\n event.s.e = entry;\n const found =\n meeting(entry.p[0]?.s?.p, stretch.p) ??\n meeting(stretch.p, entry.n[0]?.s?.p);\n if (found) return { m: found };\n const { p, w } = stretch;\n const top = arrivals.get(p.r);\n if (!met.has(p.r) || (top && latitude(w) > latitude(top.w))) {\n met.add(p.r);\n arrivals.set(p.r, { e: entry, w });\n }\n const next = events[index + 1];\n if (next?.k !== 1 || next.x !== event.x) placeArrivals();\n } else if (event.k === 2) {\n const { u } = event;\n let entry: Entry | undefined = southOf(head, u.s);\n entry = entry.s ? entry : entry.n[0];\n while (entry?.s) {\n const found = meeting(u.p, entry.s.p);\n if (found) return { m: found };\n if (dot(entry.s.n, u.n) < -TOLERANCE) break;\n entry = entry.n[0];\n }\n } else if (event.s.e) {\n const e = event.s.e;\n leave(e);\n const found = meeting(e.p[0]?.s?.p, e.n[0]?.s?.p);\n if (found) return { m: found };\n }\n }\n return { p: placements };\n}\n\nfunction signedArea(ring: Ring): number {\n let sum = 0;\n let lune = 0;\n let run: number | undefined;\n let end = 0;\n for (const arc of ring) {\n const turn = cross(arc.s, arc.e)[2];\n const along = 1 + dot(arc.s, arc.e);\n const lift = arc.s[2] + arc.e[2];\n if (lift >= 0) {\n sum += 2 * Math.atan2(turn, along + lift);\n if (run !== undefined) lune += arc.f.lon - run;\n run = undefined;\n } else {\n sum += 2 * Math.atan2(-turn, along - lift);\n run ??= arc.f.lon;\n }\n end = arc.t.lon;\n }\n if (run !== undefined) lune += end - run;\n return sum + 2 * lune * RADIANS;\n}\n\nfunction ringNode(pts: GeoPoint[], a: Ring, i: number): RingNode {\n return {\n i,\n h: i === 0 ? INF : i - 1,\n pts,\n a,\n ccw: signedArea(a) > 0,\n out: undefined,\n in: false,\n fa: INF,\n fw: INF,\n };\n}\n\nexport function validateGeoPolygon(\n value: unknown\n): ValidationResult<GeoPolygon> {\n const polygon = validateSchema(polygonRecord, value);\n if (polygon.issues) return polygon;\n const outer = ringArcs(polygon.value.outer, [\"outer\"]);\n if (outer.issues) return outer;\n const shell = ringNode(polygon.value.outer, outer.value, 0);\n const holes: RingNode[] = [];\n const rawHoles = polygon.value.holes ?? [];\n for (let index = 0; index < rawHoles.length; index++) {\n const points = rawHoles[index]!;\n const hole = ringArcs(points, [\"holes\", index]);\n if (hole.issues) return hole;\n holes.push(ringNode(points, hole.value, index + 1));\n }\n const placed: Placed[] = [];\n for (let k = 0; k <= holes.length; k++) {\n const r = k === 0 ? shell : holes[k - 1]!;\n for (let i = 0; i < r.a.length; i++) placed.push({ a: r.a[i]!, r, i });\n }\n const swept = sweep(placed, (first, second) => {\n if (first.r !== second.r) return false;\n const d = Math.abs(first.i - second.i);\n return d <= 1 || d === first.r.a.length - 1;\n });\n if (swept.m) {\n const [first, second] = swept.m;\n const maxRing = Math.max(first.r.i, second.r.i);\n const later: PropertyKey[] =\n maxRing === 0 ? [\"outer\"] : [\"holes\", maxRing - 1];\n return polyFail(\n first.r === second.r\n ? ERR_SELF\n : Math.min(first.r.i, second.r.i) === 0\n ? ERR_OUTSIDE\n : ERR_OVERLAP,\n later\n );\n }\n for (const { r, n } of swept.p) {\n const other = n?.p.r;\n const out = other === undefined || other.ccw !== n?.ew ? other : other.out;\n r.out = out;\n r.in = out !== undefined && (out.i === 0 || out.in);\n r.fa = out ? Math.min(out.h, out.fa) : INF;\n }\n for (const { r } of swept.p.reverse()) {\n const { out } = r;\n if (out) out.fw = Math.min(out.fw, r.h, r.fw);\n }\n for (const { h, in: inside, fa, fw } of holes) {\n if (!inside) return polyFail(ERR_OUTSIDE, [\"holes\", h]);\n if (Math.min(fa, fw) < h) return polyFail(ERR_OVERLAP, [\"holes\", h]);\n }\n const wide = shell.ccw ? shell.pts : shell.pts.reverse();\n const cut = holes.map(({ pts, ccw }) => (ccw ? pts.reverse() : pts));\n return ok(cut.length > 0 ? { outer: wide, holes: cut } : { outer: wide });\n}\n\nconst areaRecord = object({\n bounds: createSchema(\"object\", validateGeoBounds),\n polygon: createSchema(\"object\", validateGeoPolygon),\n});\n\nexport function validateGeoArea(value: unknown): ValidationResult<GeoArea> {\n const area = validateSchema(areaRecord, value);\n if (area.issues) return area;\n const { bounds, polygon } = area.value;\n if (bounds && !polygon) return ok({ bounds });\n if (polygon && !bounds) return ok({ polygon });\n return fail(\"Expected bounds or polygon\");\n}\n\nexport function geoAreaSchema(): VibSchema<GeoArea, GeoArea> {\n return createSchema(\"geo_area\", validateGeoArea);\n}\n"],"mappings":"yHAqBA,MAAM,EAAwB,MACxB,EAAU,KAAK,GAAK,IAGb,EAAgC,UAOvC,GAAc,EAAQ,IAAK,EAAQ,MAAmB,CAC1D,QACA,KAAM,KACN,QACA,KAAM,IACP,EAED,SAAgB,EACd,CAAE,SAAA,EAAU,aACZ,EACW,CACX,GAAI,GAAU,EACZ,MAAO,CACL,MAAOA,EACP,KAAM,EACN,MAAOA,EACP,KAAM,EACP,CAGH,IAAM,EAAgB,EAAS,EAC/B,GAAI,GAAiB,KAAK,GAAI,OAAO,GAAY,CAEjD,IAAM,EAAgB,EAAgB,EAChC,EAAQ,KAAK,IAAI,IAAKA,EAAW,EAAgB,EAAsB,CACvE,EAAQ,KAAK,IAAI,GAAIA,EAAW,EAAgB,EAAsB,CAC5E,GAAI,IAAU,KAAO,IAAU,GAAI,OAAO,EAAW,EAAO,EAAM,CAElE,IAAM,EACJ,KAAK,KACH,KAAK,IAAI,EAAG,KAAK,IAAI,EAAc,CAAG,KAAK,IAAIA,EAAW,EAAQ,CAAC,CACpE,CACC,EACF,EACF,MAAO,CACL,QACA,KAAM,EAAmB,EAAY,EAAe,CACpD,QACA,KAAM,EAAmB,EAAY,EAAe,CACrD,CAGH,SAAS,EAAmB,EAA2B,CACrD,QAAW,EAAY,KA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AAG,EAAI,GAAG,CAAG,EAEzC,IAAK,GAAM,CAAE,OAAO,EAAM,EAAE,SAAS,CAAE,CACrC,GAAM,CAAE,OAAQ,EACZ,IAAK,EAAI,GAAK,KAAK,IAAI,EAAI,GAAI,EAAE,EAAG,EAAE,GAAG,EAE/C,IAAK,GAAM,CAAE,IAAG,GAAI,EAAQ,KAAI,QAAQ,EAAO,CAC7C,GAAI,CAAC,EAAQ,OAAO,EAAS,EAAa,CAAC,QAAS,EAAE,CAAC,CACvD,GAAI,KAAK,IAAI,EAAI,EAAG,CAAG,EAAG,OAAO,EAAS,EAAa,CAAC,QAAS,EAAE,CAAC,CAEtE,IAAM,EAAO,EAAM,IAAM,EAAM,IAAM,EAAM,IAAI,SAAS,CAClD,EAAM,EAAM,KAAK,CAAE,MAAK,SAAW,EAAM,EAAI,SAAS,CAAG,EAAK,CACpE,OAAO,EAAG,EAAI,OAAS,EAAI,CAAE,MAAO,EAAM,MAAO,EAAK,CAAG,CAAE,MAAO,EAAM,CAAC,CAG3E,MAAM,GAAa,EAAO,CACxB,OAAQ,EAAa,SAAU,EAAkB,CACjD,QAAS,EAAa,SAAU,GAAmB,CACpD,CAAC,CAEF,SAAgB,GAAgB,EAA2C,CACzE,IAAM,EAAO,EAAe,GAAY,EAAM,CAC9C,GAAI,EAAK,OAAQ,OAAO,EACxB,GAAM,CAAE,SAAQ,WAAY,EAAK,MAGjC,OAFI,GAAU,CAAC,EAAgB,EAAG,CAAE,SAAQ,CAAC,CACzC,GAAW,CAAC,EAAe,EAAG,CAAE,UAAS,CAAC,CACvC,EAAK,6BAA6B,CAG3C,SAAgB,IAA6C,CAC3D,OAAO,EAAa,WAAY,GAAgB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{_t as e,ht as t,o as n}from"./native-types-1ewJXVks.mjs";const r=new WeakMap;function i(e){return e?.array===!0?void 0:a(e)}function a(t){if(t===void 0||t.type!==`string`)return;let n=r.get(t);if(n)return n;let i=t.autoGenerate;if(i===void 0||!e(i.kind)||i.implicit===!0)return;let a={format:i.kind,prefix:i.prefix,length:i.length};return r.set(t,a),a}const o={pg:/^(?:text|citext|varchar\(\d+\))$/,mysql:/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,sqlite:/^TEXT$/},s=/^(?:BINARY|VARBINARY)\((\d+)\)$/,c=e=>e===`uuid`||e===`uuidv7`,l={pg:`text, citext, varchar(n)`,mysql:`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`,sqlite:`TEXT`};function u(e,n){let r=t(e);return r===void 0?{representation:`text`,columnType:n===`pg`?`text`:`TEXT`}:n===`pg`?c(e)?{representation:`uuid`,columnType:`uuid`}:{representation:`bytes`,columnType:`bytea`}:{representation:`bytes`,columnType:n===`mysql`?`BINARY(${r})`:`BLOB`}}function d(e,n,r){let i=t(n);if(i!==void 0){if(r===`pg`)return e===`bytea`?`bytes`:e===`uuid`&&c(n)?`uuid`:void 0;if(e===`BLOB`)return`bytes`;if(r===`mysql`){let t=s.exec(e);if(t&&Number(t[1])===i)return`bytes`}}}function f(e,t,r){let i=n(t,r);if(i===void 0)return u(e.format,r);let a=i.type;if(o[r].test(a))return{representation:`text`,columnType:a};let s=d(a,e.format,r);return s===void 0?void 0:{representation:s,columnType:a}}function p(e,n){let r=t(e),i=l[n];return r===void 0?i:`${n===`pg`?c(e)?`uuid, bytea`:`bytea`:n===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}export{f as i,i as n,a as r,p as t};
|
|
2
|
+
//# sourceMappingURL=id-domain-Cg65TLZ-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"id-domain-Cg65TLZ-.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\nconst TEXT_FAMILY: Record<IdDialect, RegExp> = {\n pg: /^(?:text|citext|varchar\\(\\d+\\))$/,\n mysql: /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/,\n sqlite: /^TEXT$/,\n};\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\nconst isUuid = (format: IdFormat) => format === \"uuid\" || format === \"uuidv7\";\n\nconst TEXT_DESC: Record<IdDialect, string> = {\n pg: \"text, citext, varchar(n)\",\n mysql: \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\",\n sqlite: \"TEXT\",\n};\n\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n return {\n representation: \"text\",\n columnType: dialect === \"pg\" ? \"text\" : \"TEXT\",\n };\n }\n if (dialect === \"pg\") {\n return isUuid(format)\n ? { representation: \"uuid\", columnType: \"uuid\" }\n : { representation: \"bytes\", columnType: \"bytea\" };\n }\n return {\n representation: \"bytes\",\n columnType: dialect === \"mysql\" ? `BINARY(${width})` : \"BLOB\",\n };\n}\n\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return;\n if (dialect === \"pg\") {\n return type === \"bytea\"\n ? \"bytes\"\n : type === \"uuid\" && isUuid(format)\n ? \"uuid\"\n : undefined;\n }\n if (type === \"BLOB\") return \"bytes\";\n if (dialect === \"mysql\") {\n const sized = MYSQL_SIZED_BINARY.exec(type);\n if (sized && Number(sized[1]) === width) return \"bytes\";\n }\n return;\n}\n\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) return defaultIdStorage(domain.format, dialect);\n const type = nativeType.type;\n if (TEXT_FAMILY[dialect].test(type)) {\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text = TEXT_DESC[dialect];\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? isUuid(format)\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n"],"mappings":"gEAkCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,EACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,EAAsB,EAAM,CAIzE,SAAgB,EACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,E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O,CAC5B,EAAO,EAAU,GAUvB,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,EAAO,EAAO,CACZ,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./migrations-DIUltjr3.mjs";import{o as t}from"./sql-tegqTqGq.mjs";import{n,r}from"./model-Dtd37Sky.mjs";import{gt as i,yt as a}from"./native-types-1ewJXVks.mjs";import{i as o}from"./keys-DZdKAd4n.mjs";import{c as s}from"./time-step-DJaIhpAz.mjs";import{g as c,m as l,n as u}from"./validator-DMzH5Tz0.mjs";import{t as d}from"./identifiers-BxOf57qy.mjs";const f=`[0-9a-fA-F]`,p=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,m=`[0-9A-Za-z]`,h={uuid:{length:36,r7:`^${f}{8}-${f}{4}-${f}{4}-${f}{4}-${f}{12}$`,glob:`${f.repeat(8)}-${f.repeat(4)}-${f.repeat(4)}-${f.repeat(4)}-${f.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,r7:`^[0-7]${p}{25}$`,glob:`[0-7]${p.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,r7:`^${m}{27}$`,glob:m.repeat(27),fold:void 0,max:a}};function g(e){return e.format===`ulid`?h.ulid:e.format===`ksuid`?h.ksuid:h.uuid}const _=e=>t.raw(String(e));function v(e,n,i,a){let o=d(n===`mysql`?"`":`"`),s=n===`postgresql`&&i?`${o(i)}.`:``;return t.raw(`${s+o(r(e))} AS ${a}`)}function y(e,r,i,a){let o=d(i===`mysql`?"`":`"`);return t.raw(`${a}.${o(n(e,r))}`)}function b(e,n){let r=n.prefix;return r?t`substr(${e}, ${_(r.length+2)})`:e}function x(e,n){return n===`mysql`?t`CAST(${e} AS BINARY)`:e}function S(e,n){return n===`postgresql`?t`CAST(${e} AS text) COLLATE "C"`:x(e,n)}function C(e,n,r){let i=g(n),a=b(e,n),o=r===`postgresql`?t`${a} ~ ${i.r7}`:r===`mysql`?t`${a} REGEXP ${i.r7}`:t`${a} GLOB ${i.glob}`,s=t`${t.raw(r===`mysql`?`CHAR_LENGTH`:`length`)}(${a}) = ${_(i.length)} AND ${o}`,c=i.max===void 0?s:t`${s} AND ${S(a,r)} <= ${i.max}`,l=n.prefix;return l?t`${x(t`substr(${e}, 1, ${_(l.length+1)})`,r)} = ${`${l}-`} AND ${c}`:c}function w(e,n,r){let i=g(n).fold,a=b(e,n);return x(i===void 0?a:t`${t.raw(i)}(${a})`,r)}function T(e,n,r,i){return{kind:`trusted-read`,query:t`SELECT COUNT(${n}) = COUNT(DISTINCT ${w(n,r,i)}) AS ok FROM ${e}`,equals:!0}}function E(e,t){return o(e).sf.some(e=>e.length===1&&e[0]===t)}const D=(e,n)=>({kind:`trusted-read`,query:t`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${n}) AS ok`,equals:!0});function O(e,t){let n=[];for(let r of l(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.ee===e.field&&n.push({model:r.owner.source,field:t.tw});return n}function k(a){let{model:o,field:l,dialect:d,namespace:f}=a;s(a.schema);let p=u(a.schema),m=c(o,l,p);if(m===void 0||!i(m.format))throw new e(`'${r(o)}.${n(o,l)}' has no compact identifier domain (uuid/uuidv7/ulid/ksuid).`,`V4002`);let h=v(o,d,f,`p`),_=y(o,l,d,`p`),b=[D(h,t`${_} IS NOT NULL AND NOT (${C(_,m,d)})`)],x=g(m).fold!==void 0;x&&b.push(T(h,_,m,d));for(let e of O(a,p)){let n=v(e.model,d,f,`c`),r=y(e.model,e.field,d,`c`);b.push(D(n,t`${r} IS NOT NULL AND NOT (${C(r,m,d)})`)),x&&E(e.model,e.field)&&b.push(T(n,r,m,d)),b.push(D(n,t`${r} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${h} WHERE ${w(_,m,d)} = ${w(r,m,d)})`))}return b}const A=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,j=e=>`'${e.replaceAll(`'`,`''`)}'`;function M(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${j(h.uuid.r7)}; IF invalid > 0 THEN RAISE EXCEPTION ${j(`VibORM: % row(s) of ${n} are not canonical uuid text (prefixed IDs unsupported); convert manually or keep a text native type.`)}, invalid; END IF; END \$viborm\$`}function N(e,t){return t.toLowerCase()===`uuid`&&A.test(e.trim())}export{N as n,M as r,k as t};
|
|
2
|
+
//# sourceMappingURL=identifier-conversion-BTDxDwDB.mjs.map
|