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":"native-types-1ewJXVks.mjs","names":["integer","opt","wrapped","wrapped","optional","wrapped","optional"],"sources":["../src/validation/primitives/bigint.ts","../src/validation/primitives/geo-values.ts","../src/validation/primitives/binary-shapes.ts","../src/validation/primitives/id-formats.ts","../src/validation/primitives/id-codec.ts","../src/validation/json-schema/types.ts","../src/validation/json-schema/converters.ts","../src/validation/json-schema/factory.ts","../src/validation/parse-failure.ts","../src/validation/primitives/helpers.ts","../src/validation/primitives/decimal-value.ts","../src/validation/primitives/decimal-codec.ts","../src/validation/primitives/optional.ts","../src/validation/primitives/object.ts","../src/validation/primitives/datetime-values.ts","../src/validation/primitives/number.ts","../src/validation/primitives/geo-point-codec.ts","../src/schema/identifier.ts","../src/schema/scalars/native-types.ts"],"sourcesContent":["import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isBigInt } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// BigInt Schema\n// =============================================================================\n\nexport interface BaseBigIntSchema<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {}\n\nexport interface BigIntSchema<TInput = bigint, TOutput = bigint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"bigint\";\n}\n\n// Pre-computed error for fast path\nconst BIGINT_ERROR = /* @__PURE__ */ frozenFail(\n \"Expected bigint or an integer string\"\n);\n\n/**\n * The integer TEXT a bigint is also admitted as: what a JSON boundary carries,\n * since a JSON number past 2^53 has already lost digits. The JSON Schema\n * export states this same grammar as the bigint's `pattern`.\n */\nexport const BIGINT_TEXT_PATTERN = \"^[+-]?\\\\d+$\";\nconst BIGINT_TEXT = new RegExp(BIGINT_TEXT_PATTERN);\n\n/**\n * Validate that a value is a bigint, or an integer string read as one.\n */\nfunction validateBigInt(value: unknown) {\n if (isBigInt(value)) return ok(value);\n return typeof value === \"string\" && BIGINT_TEXT.test(value)\n ? ok(BigInt(value))\n : BIGINT_ERROR;\n}\n\n/**\n * Create a bigint schema.\n *\n * @example\n * const id = v.bigint();\n * const optionalId = v.bigint({ optional: true });\n */\nexport function bigint(): BigIntSchema<bigint, bigint>;\nexport function bigint<const Opts extends ScalarOptions<bigint, any>>(\n options: Opts\n): BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>>;\nexport function bigint<\n const Opts extends ScalarOptions<bigint, any> | undefined,\n>(\n options?: Opts\n): BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {\n return buildSchema(\"bigint\", validateBigInt, options) as BigIntSchema<\n ComputeInput<bigint, Opts>,\n ComputeOutput<bigint, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBigInt };\n","/**\n * The coordinate domain every geographic value shares: EPSG:4326 degrees,\n * longitude first. The codecs, the JSON Schema projection, and the SQLite\n * CHECK read these same constants.\n */\nexport const GEO_POINT_KEYS = [\"longitude\", \"latitude\"] as const;\nexport const GEO_LONGITUDE_MIN = -180;\nexport const GEO_LONGITUDE_MAX = 180;\nexport const GEO_LATITUDE_MIN = -90;\nexport const GEO_LATITUDE_MAX = 90;\nexport const GEO_BOUNDS_KEYS = [\"south\", \"west\", \"north\", \"east\"] as const;\nexport const GEO_POLYGON_MIN_RING_POINTS = 3;\n\n/** The sole public value represented by an `s.point()` field. */\nexport interface GeoPoint {\n longitude: number;\n latitude: number;\n}\n\n/** One inclusive latitude/longitude rectangle. */\nexport interface GeoBounds {\n south: number;\n west: number;\n north: number;\n east: number;\n}\n\n/** One simple geographic polygon with optional holes. */\nexport interface GeoPolygon {\n outer: readonly GeoPoint[];\n holes?: readonly (readonly GeoPoint[])[];\n}\n\n/** The two query-only geographic area forms. */\nexport type GeoArea =\n | { readonly bounds: GeoBounds }\n | { readonly polygon: GeoPolygon };\n","/**\n * The ONE normalization of every shape a driver spells binary bytes in.\n *\n * Nine drivers return the same column nine ways — a Node `Buffer`, a\n * `Uint8Array`, an `ArrayBuffer`, a plain array of byte numbers, PostgreSQL's\n * `\\x…` hex inside a JSON carrier, MySQL's `base64:typeNNN:…` inside one, and\n * the lowercase hex our own `blobToHex` cast emits — and every one of them\n * names the same bytes. Deciding which is which is a pure question about a\n * VALUE, not about a dialect or an operation, so it lives here as a leaf where\n * both readers of physical binary can share one answer: the blob scalar's\n * result parser and the identifier storage codec.\n *\n * It REPORTS rather than throws. The two callers are at different boundaries\n * and owe different messages — a blob column names the driver and the\n * operation, an identifier names the field and its declared format — so the\n * refusal's wording belongs to them and only the classification belongs here.\n */\n\nconst HEX_BYTES = /^(?:[0-9a-fA-F]{2})*$/;\nconst BASE64 =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64_PROVIDER = /^base64:type\\d+:(.*)$/;\n\n/**\n * The bytes a driver value names, or the REPRESENTATION that could not be read.\n *\n * `unsupported` is the phrase a message says after \"an unsupported\": the shape\n * that was recognized but malformed (`\"hex string\"`, `\"base64 string\"`,\n * `\"byte array\"`), or the `typeof` of a value that is no binary shape at all.\n */\nexport type BinaryShape =\n | { readonly bytes: Uint8Array; readonly unsupported?: undefined }\n | { readonly bytes?: undefined; readonly unsupported: string };\n\nfunction hexBytes(hex: string): BinaryShape {\n if (!HEX_BYTES.test(hex)) return { unsupported: \"hex string\" };\n const out = new Uint8Array(hex.length / 2);\n for (let index = 0; index < out.length; index++) {\n out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return { bytes: out };\n}\n\nfunction base64Bytes(base64: string): BinaryShape {\n if (!BASE64.test(base64)) return { unsupported: \"base64 string\" };\n return { bytes: Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)) };\n}\n\n/** Normalize any driver binary representation to plain bytes, or say why not. */\nexport function normalizeBinaryValue(value: unknown): BinaryShape {\n if (value instanceof ArrayBuffer) {\n return { bytes: new Uint8Array(value.slice(0)) };\n }\n if (value instanceof Uint8Array) {\n const out = new Uint8Array(value.byteLength);\n out.set(value);\n return { bytes: out };\n }\n if (ArrayBuffer.isView(value)) {\n const out = new Uint8Array(value.byteLength);\n out.set(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n return { bytes: out };\n }\n if (Array.isArray(value)) {\n for (const byte of value) {\n if (!Number.isInteger(byte) || byte < 0 || byte > 255) {\n return { unsupported: \"byte array\" };\n }\n }\n return { bytes: Uint8Array.from(value) };\n }\n if (typeof value === \"string\") {\n if (value.startsWith(\"\\\\x\")) return hexBytes(value.slice(2));\n if (value.startsWith(\"base64:type\")) {\n const match = BASE64_PROVIDER.exec(value);\n return match ? base64Bytes(match[1]!) : { unsupported: \"base64 string\" };\n }\n return hexBytes(value);\n }\n return { unsupported: typeof value };\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: a version nibble, a\n// variant pair and a base32 digit are DEFINED as bit fields; expressing them\n// arithmetically would restate the same masks less legibly.\n\n/**\n * The ONE reversible representation of every fixed-width identifier format.\n *\n * UUID, ULID and KSUID each name the same value twice: as the TEXT a caller\n * writes and reads, and as the BYTES that text stands for. This module owns\n * both spellings and the conversion between them, plus the byte layout each\n * format's generator assembles. Nothing above it re-derives a width, an\n * alphabet, a padding rule, or a version bit.\n *\n * It is a LEAF on purpose. It imports no scalar class, no schema state and no\n * dialect, so the storage codec that will encode and decode these values at the\n * database boundary can consume the same conversions the generators use. Two\n * implementations of \"what a ULID is\" is exactly what this file exists to\n * prevent.\n *\n * Two asymmetries are deliberate:\n *\n * 1. TEXT -> BYTES returns `undefined` for anything outside the format. Text is\n * what a caller types, so a spelling the format does not have is a value to\n * refuse, and the boundary that asked owns the message.\n * 2. BYTES -> TEXT REFUSES a wrong width. A byte array is never typed by a\n * caller; it is produced by a generator or read out of a column, so a width\n * that is not the format's names a broken physical value rather than a\n * spelling question, and no caller above can say anything truer about it.\n *\n * Randomness is drawn HERE and only here, from `crypto.getRandomValues`. There\n * is no `Math.random()` path: an identifier that is not unpredictable is not an\n * identifier, so a runtime without secure randomness gets a refusal instead of\n * a weaker value.\n */\n\nimport { ValidationError } from \"@errors\";\n\n// =============================================================================\n// WIDTHS AND DOMAINS\n// =============================================================================\n\n/** Bytes in a UUID (RFC 9562 §4). */\nexport const UUID_BYTE_LENGTH = 16;\n\n/** Bytes in a ULID and characters in its Crockford base32 text. */\nexport const ULID_BYTE_LENGTH = 16;\nexport const ULID_TEXT_LENGTH = 26;\n\n/** Bytes in a KSUID and characters in its base62 text. */\nexport const KSUID_BYTE_LENGTH = 20;\nexport const KSUID_TEXT_LENGTH = 27;\n\n/** Random bytes a ULID carries after its 48-bit timestamp. */\nexport const ULID_RANDOM_LENGTH = 10;\n\n/** Random bytes a UUIDv7 carries after its 48-bit timestamp. */\nexport const UUIDV7_RANDOM_LENGTH = 10;\n\n/** Payload bytes a KSUID carries after its 32-bit timestamp. */\nexport const KSUID_PAYLOAD_LENGTH = 16;\n\n/**\n * The widest instant a 48-bit millisecond timestamp names: 2^48-1 ms after the\n * Unix epoch, which is in the year 10889. Shared by ULID and UUIDv7.\n */\nexport const MAX_MILLISECOND_TIMESTAMP = 281_474_976_710_655;\n\n/** KSUID counts seconds from 2014-05-13T16:53:20Z, not from the Unix epoch. */\nexport const KSUID_EPOCH_SECONDS = 1_400_000_000;\n\n/** The widest second a 32-bit KSUID timestamp names, as a Unix second. */\nexport const MAX_KSUID_UNIX_SECONDS = KSUID_EPOCH_SECONDS + 4_294_967_295;\n\n/**\n * Crockford's base32 alphabet: no `I`, `L`, `O` or `U`. VibORM does NOT map the\n * excluded letters onto digits — a ULID with an `I` in it was not produced by\n * this format, and silently reading it as `1` would make two different texts\n * the same identifier.\n */\nexport const CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * The accepted spellings of one Crockford digit: canonical uppercase first,\n * its lowercase alias second, so `indexOf(char) % 32` is the digit's value and\n * anything else is not a digit at all.\n *\n * The lookup is by exact character rather than by case folding: `\"ſ\"`\n * upper-cases to `\"S\"`, and a ULID is an identity, not a piece of prose.\n */\nconst CROCKFORD_ALIASED = CROCKFORD + CROCKFORD.toLowerCase();\n\n/**\n * NanoID's URL-safe alphabet: 64 characters, so one random byte selects one\n * character through `byte & 63` with no bias and no rejection sampling.\n *\n * It lives HERE, beside the fixed-width alphabets, because a declared nanoid\n * field has to ADMIT the values it generates: the storage codec spells the\n * grammar from the same 64 characters the generator draws from, and two copies\n * of an alphabet is exactly how a generated value comes to be refused by its\n * own field.\n */\nexport const NANOID_ALPHABET =\n \"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\";\n\n/** The length `.nanoid()` takes when the declaration names none. */\nexport const NANOID_DEFAULT_LENGTH = 21;\n\n/**\n * The one spelling a CUID2 has: a lowercase letter then 23 lowercase\n * alphanumerics, which is what this port's generator emits at its fixed length\n * of 24 and what upstream's own validator accepts.\n */\nexport const CUID_TEXT = /^[a-z][0-9a-z]{23}$/;\n\n/**\n * KSUID's base62 alphabet, in ASCII order. The order is load-bearing: it makes\n * the text sort exactly as the bytes sort, which is what makes a KSUID\n * time-sortable as a string.\n */\nexport const BASE62 =\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/** The first value 20 bytes cannot hold; some 27-character base62 texts exceed it. */\nconst KSUID_EXCLUSIVE_MAX = 2n ** 160n;\n\nexport const UUID_TEXT =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\nconst HEX_RADIX = 16;\nconst BASE62_RADIX = 62n;\nconst BYTE_RADIX = 256n;\nconst BYTE_MASK = 255n;\n\n// =============================================================================\n// THE ONE REFUSAL\n// =============================================================================\n\n/**\n * The one refusal an identifier declaration or generation raises.\n *\n * Every failure here is a DECLARATION failure in the end — a length the format\n * has no value for, an instant it cannot name, a prefix that contradicts one\n * already declared, or a runtime that cannot produce the entropy the declared\n * format requires — so they all name the builder that was spelled and the part\n * of the declaration at fault.\n */\nexport function refuseId(\n builder: string,\n path: string,\n message: string\n): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n// =============================================================================\n// SECURE RANDOMNESS\n// =============================================================================\n\n/**\n * The most bytes one call to the entropy source will serve.\n *\n * `crypto.getRandomValues` refuses a request larger than this with a\n * `QuotaExceededError` (Web Cryptography API §10.1), so it is the ceiling on\n * every length a caller can choose. It is published because a DECLARATION that\n * asks for more has to be refused where it is spelled, not at row-create time\n * inside a closure.\n */\nexport const MAX_RANDOM_BYTES = 65_536;\n\n/**\n * `length` unpredictable bytes, or a refusal.\n *\n * The ONE entropy source in the identifier language. It is read at GENERATION\n * time, never at import or declaration time, so loading VibORM and describing a\n * schema draw nothing.\n *\n * `format` names the generator that asked, because the message a developer sees\n * has to say what stopped working. It cannot name the FIELD: a generator is a\n * closure held in scalar state, and field keys belong to the model that later\n * mounts that scalar, so no field name exists at this point in the program.\n */\nexport function randomBytes(length: number, format: string): Uint8Array {\n const source = globalThis.crypto;\n if (typeof source?.getRandomValues !== \"function\")\n refuseId(\n `s.string().${format}`,\n \"generate\",\n `Cannot generate ${format}: crypto.getRandomValues unavailable`\n );\n return source.getRandomValues(new Uint8Array(length));\n}\n\n// =============================================================================\n// PREFIX\n// =============================================================================\n\n/**\n * Whether a declaration carries a prefix. An empty string is NOT a prefix: it\n * is how a caller spells \"no prefix\", and `${\"\"}-${value}` would otherwise make\n * a bare hyphen part of every value.\n */\nexport function hasIdPrefix(prefix: string | undefined): boolean {\n return prefix !== undefined && prefix !== \"\";\n}\n\n/**\n * The public value of a generated identifier: `prefix-payload`, or the bare\n * payload when no prefix was declared. The hyphen is part of the contract, and\n * a prefix is matched whole at admission — nothing splits generically on `-`.\n */\nexport function applyIdPrefix(\n prefix: string | undefined,\n payload: string\n): string {\n return hasIdPrefix(prefix) ? `${prefix}-${payload}` : payload;\n}\n\n// =============================================================================\n// EXACT-WIDTH INTEGERS\n// =============================================================================\n\n/**\n * Write `value` big-endian across exactly `byteLength` bytes.\n *\n * Callers have already proved the value fits — each format refuses its own\n * out-of-range instant with a message naming that format — so this writes\n * rather than checks. Arithmetic, not shifts: a 48-bit timestamp is wider than\n * the 32 bits JavaScript's bitwise operators work in.\n */\nfunction writeUintBE(\n bytes: Uint8Array,\n byteLength: number,\n value: number\n): void {\n let remaining = value;\n for (let index = byteLength - 1; index >= 0; index--) {\n bytes[index] = remaining % 256;\n remaining = Math.floor(remaining / 256);\n }\n}\n\nfunction assembleTimestampedId(\n format: string,\n label: string,\n time: number,\n min: number,\n max: number,\n tsBytes: number,\n totalBytes: number,\n tail: Uint8Array\n): Uint8Array {\n if (!Number.isInteger(time) || time < min || time > max) {\n refuseId(\n `s.string().${format}`,\n \"generate\",\n `${label} timestamp must be integer in ${min}..${max}; got ${time}`\n );\n }\n const bytes = new Uint8Array(totalBytes);\n bytes.set(tail, tsBytes);\n writeUintBE(bytes, tsBytes, time - min);\n return bytes;\n}\n\nfunction timestampedBytes(\n format: string,\n timeMillis: number,\n random: Uint8Array\n): Uint8Array {\n return assembleTimestampedId(\n format,\n format,\n timeMillis,\n 0,\n MAX_MILLISECOND_TIMESTAMP,\n 6,\n UUID_BYTE_LENGTH,\n random\n );\n}\n\nfunction tagUuid(bytes: Uint8Array, version: number): Uint8Array {\n bytes[6] = (bytes[6]! & 0x0f) | version;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n return bytes;\n}\n\nexport function uuidV4Bytes(random: Uint8Array): Uint8Array {\n return tagUuid(random, 0x40);\n}\n\nexport function uuidV7Bytes(\n timeMillis: number,\n random: Uint8Array\n): Uint8Array {\n return tagUuid(timestampedBytes(\"uuidv7\", timeMillis, random), 0x70);\n}\n\nfunction assertByteLength(\n bytes: Uint8Array,\n expected: number,\n format: string,\n label: string\n): void {\n if (bytes.length !== expected) {\n refuseId(\n `s.string().${format}`,\n \"generate\",\n `${label} must be ${expected} bytes; got ${bytes.length}`\n );\n }\n}\n\n/** The canonical text of 16 UUID bytes: lowercase hex, hyphenated 8-4-4-4-12. */\nexport function bytesToUuid(bytes: Uint8Array): string {\n assertByteLength(bytes, UUID_BYTE_LENGTH, \"uuid\", \"UUID\");\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(HEX_RADIX).padStart(2, \"0\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * The 16 bytes a canonical UUID text names, or `undefined`.\n *\n * Uppercase is an accepted ALIAS (RFC 9562 §4 requires readers to accept it),\n * so `A1B2…` and `a1b2…` are the same identifier and produce the same bytes.\n * Braces, URNs and unhyphenated forms are not spellings this format has.\n */\nexport function uuidToBytes(text: string): Uint8Array | undefined {\n if (!UUID_TEXT.test(text)) return;\n const hex = text.replaceAll(\"-\", \"\");\n const bytes = new Uint8Array(UUID_BYTE_LENGTH);\n for (let index = 0; index < UUID_BYTE_LENGTH; index++) {\n bytes[index] = Number.parseInt(\n hex.slice(index * 2, index * 2 + 2),\n HEX_RADIX\n );\n }\n return bytes;\n}\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/**\n * Assemble a ULID: a 48-bit big-endian millisecond timestamp followed by 80\n * bits of randomness.\n */\nexport function ulidBytes(timeMillis: number, random: Uint8Array): Uint8Array {\n return timestampedBytes(\"ulid\", timeMillis, random);\n}\n\n/**\n * The canonical text of 16 ULID bytes: 26 uppercase Crockford characters.\n *\n * 26 characters hold 130 bits and a ULID is 128, so the text is the value\n * left-padded with two zero bits. That padding is why a canonical ULID's first\n * character is always `0` through `7`.\n */\nexport function bytesToUlid(bytes: Uint8Array): string {\n assertByteLength(bytes, ULID_BYTE_LENGTH, \"ulid\", \"ULID\");\n let text = \"\";\n let accumulator = 0;\n let bits = 2;\n for (const byte of bytes) {\n accumulator = (accumulator << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n text += CROCKFORD.charAt((accumulator >>> bits) & 31);\n }\n accumulator &= (1 << bits) - 1;\n }\n return text;\n}\n\n/**\n * The 16 bytes a canonical ULID text names, or `undefined`.\n *\n * Lowercase is an accepted alias and normalizes to the same bytes. A first\n * character above `7` sets one of the two padding bits, which names a value\n * wider than 128 bits: that text is not a ULID and is refused rather than\n * truncated.\n */\nexport function ulidToBytes(text: string): Uint8Array | undefined {\n if (text.length !== ULID_TEXT_LENGTH) return;\n const first = CROCKFORD_ALIASED.indexOf(text.charAt(0));\n if (first < 0) return;\n const leading = first % 32;\n if (leading > 7) return;\n const bytes = new Uint8Array(ULID_BYTE_LENGTH);\n let accumulator = leading;\n let bits = 3;\n let index = 0;\n for (const char of text.slice(1)) {\n const digit = CROCKFORD_ALIASED.indexOf(char);\n if (digit < 0) return;\n accumulator = (accumulator << 5) | (digit % 32);\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n bytes[index] = (accumulator >>> bits) & 255;\n index++;\n accumulator &= (1 << bits) - 1;\n }\n }\n return bytes;\n}\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\n/**\n * Assemble a KSUID: a 32-bit big-endian count of seconds since\n * 2014-05-13T16:53:20Z followed by a 128-bit payload.\n *\n * The timestamp is given as a UNIX second — the offset epoch is this format's\n * private business, and a caller that had to subtract it would be a second\n * owner of the same constant.\n */\nexport function ksuidBytes(\n unixSeconds: number,\n payload: Uint8Array\n): Uint8Array {\n return assembleTimestampedId(\n \"ksuid\",\n \"KSUID\",\n unixSeconds,\n KSUID_EPOCH_SECONDS,\n MAX_KSUID_UNIX_SECONDS,\n 4,\n KSUID_BYTE_LENGTH,\n payload\n );\n}\n\n/**\n * The canonical text of 20 KSUID bytes: exactly 27 base62 characters, padded\n * with leading `0`s. The width is fixed rather than minimal, because a KSUID\n * that shortened itself for a small timestamp would stop sorting.\n */\nexport function bytesToKsuid(bytes: Uint8Array): string {\n assertByteLength(bytes, KSUID_BYTE_LENGTH, \"ksuid\", \"KSUID\");\n let value = 0n;\n for (const byte of bytes) value = value * BYTE_RADIX + BigInt(byte);\n return ksuidText(value);\n}\n\n/** A number below 2^160 as its fixed-width, zero-padded base62 text. */\nfunction ksuidText(value: bigint): string {\n const digits: string[] = [];\n let rest = value;\n for (let index = 0; index < KSUID_TEXT_LENGTH; index++) {\n digits.push(BASE62.charAt(Number(rest % BASE62_RADIX)));\n rest /= BASE62_RADIX;\n }\n return digits.reverse().join(\"\");\n}\n\n/**\n * The canonical text of the largest value 20 bytes hold. Every KSUID text is\n * at most this, and a 27-character base62 text above it names no KSUID.\n *\n * Because {@link BASE62} is in ASCII order and the width is fixed, \"at most\" is\n * a plain BYTE-wise string comparison — which is how a caller that cannot run\n * {@link ksuidToBytes}, such as SQL over a legacy text column, asks it. Under a\n * collation that folds case it is not: `a` sorts before `V` there.\n */\nexport const KSUID_MAX_TEXT = \"aWgEPTl1tmebfsQzFP4bxwgy80V\";\n\n/**\n * The 20 bytes a canonical KSUID text names, or `undefined`.\n *\n * Base62 is case-SENSITIVE — `A` and `a` are different digits — so there is no\n * alias to normalize. 27 base62 characters can express more than 2^160 values;\n * one that does names no 20-byte identifier and is refused.\n */\nexport function ksuidToBytes(text: string): Uint8Array | undefined {\n if (text.length !== KSUID_TEXT_LENGTH) return;\n let value = 0n;\n for (const char of text) {\n const digit = BASE62.indexOf(char);\n if (digit < 0) return;\n value = value * BASE62_RADIX + BigInt(digit);\n }\n if (value >= KSUID_EXCLUSIVE_MAX) return;\n const bytes = new Uint8Array(KSUID_BYTE_LENGTH);\n for (let index = KSUID_BYTE_LENGTH - 1; index >= 0; index--) {\n bytes[index] = Number(value & BYTE_MASK);\n value >>= 8n;\n }\n return bytes;\n}\n","/**\n * The ONE codec of a declared identifier DOMAIN.\n *\n * A domain is `{ format, prefix?, length? }` — exactly the facts a generator\n * modifier already recorded on the scalar, never a second declaration. This\n * module answers the three questions every boundary asks about a value in one:\n *\n * 1. Is this string IN the domain, and what is its canonical spelling?\n * (`canonicalizeId`: the uppercase UUID and the lowercase ULID are aliases,\n * and an identity-sensitive consumer — a cache key, a captured row key, an\n * `fkEquals` — must see one spelling for one identifier.)\n * 2. What does the column physically hold for it? (`encodePhysicalId`)\n * 3. Which public value did a physical one come back as? (`decodePhysicalId`)\n *\n * It is PURE and dialect-blind on purpose. It takes an\n * {@link IdRepresentation}, never a provider: choosing the representation is a\n * storage question, owned one layer up in\n * {@link file://../../schema/scalars/string/id-domain.ts}, and a codec that\n * knew about `bytea` could not be read by the validation schemas that run\n * before any adapter exists.\n *\n * Two things it deliberately does NOT do. It never splits a value on `-`: a\n * prefix is matched WHOLE, because `usr-01H…` and a UUID both contain hyphens\n * and a generic split would silently reinterpret one as the other. And it\n * never widens a format: a text that is not a spelling of the declared format\n * is `undefined` here, so the boundary that asked owns the message.\n */\n\nimport { normalizeBinaryValue } from \"./binary-shapes\";\nimport {\n applyIdPrefix,\n BASE62,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n CROCKFORD,\n CUID_TEXT,\n KSUID_BYTE_LENGTH,\n KSUID_MAX_TEXT,\n ksuidToBytes,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n UUID_BYTE_LENGTH,\n UUID_TEXT,\n ulidToBytes,\n uuidToBytes,\n} from \"./id-formats\";\n\n// =============================================================================\n// THE DOMAIN\n// =============================================================================\n\n/** The six string generators that name an identifier domain. */\nexport type IdFormat = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\n\nconst ID_FORMATS: ReadonlySet<string> = new Set<IdFormat>(\n \"uuid uuidv7 ulid ksuid nanoid cuid\".split(\" \") as IdFormat[]\n);\n\n/** Whether a generator kind names an identifier domain. */\nexport function isIdFormat(kind: string | undefined): kind is IdFormat {\n return kind !== undefined && ID_FORMATS.has(kind);\n}\n\n/**\n * A declared or derived identifier domain.\n *\n * `prefix` is absent rather than empty when none was declared — `\"\"` is how a\n * caller spells \"no prefix\", and carrying it would make a bare `-` part of\n * every value. `length` belongs to `nanoid` alone; every other format's width\n * is the format's own.\n */\nexport interface IdDomain {\n readonly format: IdFormat;\n readonly prefix?: string | undefined;\n readonly length?: number | undefined;\n}\n\n/**\n * The four formats whose values are stored COMPACT — as bytes, or as a\n * PostgreSQL `uuid`.\n *\n * Compactness is what costs them `contains`/`startsWith`/`endsWith`/`mode`: a\n * substring of a 16-byte column is not a substring of the text a caller wrote.\n * `nanoid` and `cuid` stay text and keep every string operator.\n */\nexport function isCompactIdFormat(format: IdFormat): boolean {\n return idByteLength(format) !== undefined;\n}\n\n/** Whether two domains admit exactly the same values and store them alike. */\nexport function sameIdDomain(\n left: IdDomain | undefined,\n right: IdDomain | undefined\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return (\n left.format === right.format &&\n idPrefixOf(left) === idPrefixOf(right) &&\n nanoidLengthOf(left) === nanoidLengthOf(right)\n );\n}\n\n/** The declared prefix, with `\"\"` read as the absence it spells. */\nfunction idPrefixOf(domain: IdDomain): string | undefined {\n return domain.prefix || undefined;\n}\n\n/** The width a nanoid domain admits; every other format has a fixed one. */\nfunction nanoidLengthOf(domain: IdDomain): number | undefined {\n if (domain.format !== \"nanoid\") return undefined;\n return domain.length ?? NANOID_DEFAULT_LENGTH;\n}\n\n/** One phrase naming a domain, for a refusal that has to say what was expected. */\nexport function describeIdDomain(domain: IdDomain): string {\n const prefix = idPrefixOf(domain);\n const width =\n domain.format === \"nanoid\" ? ` of length ${nanoidLengthOf(domain)}` : \"\";\n return `a ${domain.format} value${width}${prefix === undefined ? \"\" : ` prefixed '${prefix}-'`}`;\n}\n\n/** The characters a pattern reads as syntax, escaped in a literal prefix. */\nconst PATTERN_SYNTAX = /[$()*+./?[\\\\\\]^{|}]/g;\n\n/**\n * The domain as one ECMAScript pattern, for a reader that cannot run\n * {@link canonicalizeId} — the JSON Schema export. A string matches it exactly\n * when `canonicalizeId` admits it: the declared prefix whole, then a payload\n * the format's own text conversion accepts, aliases included.\n */\nexport function idDomainPattern(domain: IdDomain): string {\n const prefix = idPrefixOf(domain);\n const marker =\n prefix === undefined ? \"\" : `${prefix.replace(PATTERN_SYNTAX, \"\\\\$&\")}-`;\n return `^${marker}${payloadPattern(domain)}$`;\n}\n\nfunction payloadPattern(domain: IdDomain): string {\n switch (domain.format) {\n case \"uuid\":\n case \"uuidv7\":\n return UUID_TEXT.source.slice(1, -1);\n case \"ulid\":\n // The first digit carries the top 3 of 128 bits, so it is at most 7.\n return `[0-7][${CROCKFORD}${CROCKFORD.toLowerCase()}]{25}`;\n case \"ksuid\":\n return base62NotAbove(KSUID_MAX_TEXT);\n case \"nanoid\":\n return `[${NANOID_ALPHABET.replace(\"-\", \"\\\\-\")}]{${nanoidLengthOf(domain)}}`;\n default:\n return CUID_TEXT.source.slice(1, -1);\n }\n}\n\n/**\n * A base62 text as wide as `max` and not above it. Base62's ASCII order is its\n * numeric order, so \"not above\" is: `max` itself, or a prefix of it followed by\n * a smaller digit and any digits after.\n */\nfunction base62NotAbove(max: string): string {\n const arms = [max];\n for (let index = 0; index < max.length; index++) {\n const below = base62Below(max[index]!);\n if (below !== \"\")\n arms.push(\n `${max.slice(0, index)}[${below}][0-9A-Za-z]{${max.length - index - 1}}`\n );\n }\n return `(?:${arms.join(\"|\")})`;\n}\n\nconst BASE62_RUN = /[0-9]{3,}|[A-Z]{3,}|[a-z]{3,}/g;\n\n/** The base62 digits below `digit`, runs of three or more as ranges. */\nfunction base62Below(digit: string): string {\n return BASE62.slice(0, BASE62.indexOf(digit)).replace(\n BASE62_RUN,\n (run) => `${run[0]}-${run.at(-1)}`\n );\n}\n\n// =============================================================================\n// ADMISSION\n// =============================================================================\n\n/**\n * The PAYLOAD of a public value: everything after an exactly-matched\n * `prefix-`, or the whole value when the domain declares no prefix.\n *\n * `undefined` means the prefix the domain declares is not the one this value\n * carries, which is a refusal and never a reason to try the bare payload.\n */\nfunction payloadOf(value: string, domain: IdDomain): string | undefined {\n const prefix = idPrefixOf(domain);\n if (prefix === undefined) return value;\n const marker = `${prefix}-`;\n return value.startsWith(marker) ? value.slice(marker.length) : undefined;\n}\n\n/** Whether every character of `text` is one this nanoid alphabet has. */\nfunction isNanoidPayload(text: string, length: number): boolean {\n if (text.length !== length) return false;\n for (const char of text) {\n if (!NANOID_ALPHABET.includes(char)) return false;\n }\n return true;\n}\n\n/**\n * The canonical spelling of one payload, or `undefined`.\n *\n * The compact formats normalize through their own byte conversion — the leaf\n * already owns which spellings are aliases and which are not values at all —\n * so a ULID whose first character exceeds `7` and a UUID with braces are\n * refused here for the same reason they are refused there. The text formats\n * are case-sensitive with no aliases, so their canonical form is themselves.\n */\nfunction canonicalizePayload(\n payload: string,\n domain: IdDomain\n): string | undefined {\n switch (domain.format) {\n case \"uuid\":\n case \"uuidv7\":\n return UUID_TEXT.test(payload) ? payload.toLowerCase() : undefined;\n case \"ulid\":\n return ulidToBytes(payload) ? payload.toUpperCase() : undefined;\n case \"ksuid\":\n return ksuidToBytes(payload) ? payload : undefined;\n case \"nanoid\":\n return isNanoidPayload(payload, nanoidLengthOf(domain)!)\n ? payload\n : undefined;\n default:\n return CUID_TEXT.test(payload) ? payload : undefined;\n }\n}\n\n/**\n * The canonical PUBLIC value this domain names, or `undefined` when the input\n * is not one of its values.\n *\n * This is the admission every boundary shares: create and update values, unique\n * selectors, `equals`/`not`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte` operands,\n * cursors, and every `connect`/`connectOrCreate`/`upsert` key. Normalizing HERE\n * — once, before anything identity-sensitive — is what keeps one identifier\n * from hashing to two cache keys.\n */\nexport function canonicalizeId(\n value: unknown,\n domain: IdDomain\n): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const payload = payloadOf(value, domain);\n if (payload === undefined) return undefined;\n const canonical = canonicalizePayload(payload, domain);\n return canonical === undefined\n ? undefined\n : applyIdPrefix(idPrefixOf(domain), canonical);\n}\n\n// =============================================================================\n// PHYSICAL REPRESENTATION\n// =============================================================================\n\n/**\n * What a column physically holds for one identifier.\n *\n * - `\"text\"` — the whole PUBLIC string, prefix included. Every `nanoid` and\n * `cuid` field, and any domain field whose native type override keeps a text\n * column.\n * - `\"uuid\"` — the payload as canonical UUID text, which is what a PostgreSQL\n * `uuid` column takes and returns on the wire.\n * - `\"bytes\"` — the payload's own bytes: 16 for a UUID or ULID, 20 for a KSUID.\n *\n * A declared PREFIX is never stored. It is a fact of the declaration, identical\n * in every row, and re-applied on read — which is also why `\"uuid\"` and\n * `\"bytes\"` are not identity paths for a prefixed field.\n */\nexport type IdRepresentation = \"text\" | \"uuid\" | \"bytes\";\n\nexport function idByteLength(format: IdFormat): number | undefined {\n return format === \"ksuid\"\n ? KSUID_BYTE_LENGTH\n : format === \"uuid\" || format === \"uuidv7\" || format === \"ulid\"\n ? UUID_BYTE_LENGTH\n : undefined;\n}\n\nexport function encodePhysicalId(\n value: string,\n domain: IdDomain,\n representation: IdRepresentation\n): string | Uint8Array | undefined {\n const canonical = canonicalizeId(value, domain);\n if (canonical === undefined || representation === \"text\") return canonical;\n const payload = payloadOf(canonical, domain)!;\n if (representation === \"uuid\") return payload;\n const { format } = domain;\n return format === \"ulid\"\n ? ulidToBytes(payload)\n : format === \"ksuid\"\n ? ksuidToBytes(payload)\n : format === \"uuid\" || format === \"uuidv7\"\n ? uuidToBytes(payload)\n : undefined;\n}\n\nexport function decodePhysicalId(\n physical: unknown,\n domain: IdDomain,\n representation: IdRepresentation\n): string | undefined {\n if (representation === \"text\") return canonicalizeId(physical, domain);\n const prefix = idPrefixOf(domain);\n if (representation === \"uuid\") {\n return typeof physical === \"string\" && UUID_TEXT.test(physical)\n ? applyIdPrefix(prefix, physical.toLowerCase())\n : undefined;\n }\n const { bytes } = normalizeBinaryValue(physical);\n if (bytes === undefined || bytes.length !== idByteLength(domain.format))\n return undefined;\n return applyIdPrefix(\n prefix,\n domain.format === \"ulid\"\n ? bytesToUlid(bytes)\n : domain.format === \"ksuid\"\n ? bytesToKsuid(bytes)\n : bytesToUuid(bytes)\n );\n}\n","/**\n * Standard JSON Schema types for VibORM.\n * Implements the StandardJSONSchemaV1 specification.\n * @see https://standardschema.dev/json-schema\n */\n\n// =============================================================================\n// JSON Schema Target Versions\n// =============================================================================\n\n/**\n * Supported JSON Schema target versions.\n * - draft-07: JSON Schema Draft 7 (widely used)\n * - draft-2020-12: JSON Schema Draft 2020-12 (latest)\n * - openapi-3.0: OpenAPI 3.0 compatible (superset of draft-04)\n */\nexport type JsonSchemaTarget =\n | \"draft-07\"\n | \"draft-2020-12\"\n | \"openapi-3.0\"\n | ({} & string); // Allows future targets\n\n/**\n * Supported targets for validation.\n */\nexport const SUPPORTED_TARGETS: JsonSchemaTarget[] = [\n \"draft-07\",\n \"draft-2020-12\",\n \"openapi-3.0\",\n];\n\n// =============================================================================\n// JSON Schema Options\n// =============================================================================\n\n/**\n * Options for JSON Schema conversion methods.\n */\nexport interface JsonSchemaOptions {\n /** Target JSON Schema version */\n readonly target: JsonSchemaTarget;\n /** Vendor-specific options */\n readonly libraryOptions?: Record<string, unknown> | undefined;\n}\n\n// =============================================================================\n// JSON Schema Types\n// =============================================================================\n\n/**\n * JSON Schema object type.\n * A flexible record that can hold any JSON Schema properties.\n */\nexport interface JsonSchema {\n $schema?: string;\n $defs?: Record<string, JsonSchema>;\n $ref?: string;\n type?: string | string[];\n const?: unknown;\n enum?: unknown[];\n properties?: Record<string, JsonSchema>;\n required?: string[];\n additionalProperties?: boolean | JsonSchema;\n items?: JsonSchema | JsonSchema[];\n prefixItems?: JsonSchema[];\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n allOf?: JsonSchema[];\n nullable?: boolean; // OpenAPI 3.0 specific\n format?: string;\n contentEncoding?: string;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n default?: unknown;\n description?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n// =============================================================================\n// JSON Schema Converter Interface\n// =============================================================================\n\n/**\n * JSON Schema converter interface.\n * Provides methods to convert to input/output JSON Schema.\n */\nexport interface JsonSchemaConverter {\n /**\n * Converts the input type to JSON Schema.\n * @throws If conversion is not supported for the given target.\n */\n readonly input: (options: JsonSchemaOptions) => Record<string, unknown>;\n\n /**\n * Converts the output type to JSON Schema.\n * @throws If conversion is not supported for the given target.\n */\n readonly output: (options: JsonSchemaOptions) => Record<string, unknown>;\n}\n\n// =============================================================================\n// Conversion Context\n// =============================================================================\n\n/**\n * One schema whose conversion is currently OPEN — i.e. sits somewhere on the\n * conversion call stack. Reaching the same schema again (through a `lazyRef`\n * or a thunk) means the schema graph is cyclic, and JSON Schema spells a cycle\n * with `$ref` rather than by inlining forever.\n *\n * `pointer` is allocated LAZILY, the first time something actually refers back\n * to the frame: a frame nobody points at emits its body inline, exactly as\n * before cycles were understood at all.\n */\nexport interface ConversionFrame {\n /** The schema this frame is converting (identity, not structure). */\n schema: unknown;\n /** The `$ref` value pointing at this frame, or null while unreferenced. */\n pointer: string | null;\n /** The `$defs` key holding the body — null when the frame is the root. */\n name: string | null;\n}\n\n/**\n * Context for JSON Schema conversion.\n * Used to track definitions and references for circular schemas.\n */\nexport interface ConversionContext {\n /** Accumulated definitions for $defs */\n definitions: Record<string, JsonSchema>;\n /** Map of schema objects to their reference IDs */\n referenceMap: Map<unknown, string>;\n /** Schemas whose conversion is currently open, keyed by identity */\n activeFrames: Map<unknown, ConversionFrame>;\n /**\n * The schema at the document root, if known. A cycle back to it is the whole\n * document, so it is spelled `#` and needs no definition of its own.\n */\n rootSchema?: unknown;\n /** Counter for generating unique reference IDs */\n refCount: number;\n /** The target version being generated */\n target: JsonSchemaTarget;\n /**\n * Which side of a transforming schema is being described. Omission keeps\n * the historical input projection for callers that build a context.\n */\n direction?: \"input\" | \"output\";\n}\n\n/**\n * Creates a new conversion context.\n *\n * @param target - The target JSON Schema version\n * @param rootSchema - The schema being converted at the document root, so a\n * cycle back to it can be spelled as the root pointer `#`\n * @param direction - The input or output side of transforming schemas\n */\nexport function createContext(\n target: JsonSchemaTarget,\n rootSchema?: unknown,\n direction: \"input\" | \"output\" = \"input\"\n): ConversionContext {\n return {\n definitions: {},\n referenceMap: new Map(),\n activeFrames: new Map(),\n rootSchema,\n refCount: 0,\n target,\n direction,\n };\n}\n","/**\n * Schema to JSON Schema converters.\n * Handles conversion of VibORM schemas to JSON Schema format.\n */\n\nimport { ValidationError } from \"@errors\";\nimport { BIGINT_TEXT_PATTERN } from \"../primitives/bigint\";\nimport type { DecimalSchema } from \"../primitives/decimal\";\nimport type { DecimalDescriptor } from \"../primitives/decimal-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n GEO_POINT_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n} from \"../primitives/geo-values\";\nimport { type IdDomain, idDomainPattern } from \"../primitives/id-codec\";\nimport type { ExactlyOneSchema } from \"../scalars/decimal\";\nimport type { VibSchema } from \"../types\";\nimport { isFunction, isRecord, isString } from \"../value-guards\";\nimport type {\n ConversionContext,\n ConversionFrame,\n JsonSchema,\n JsonSchemaTarget,\n} from \"./types\";\nimport { createContext, SUPPORTED_TARGETS } from \"./types\";\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Wrapper schema types that should be traversed to find inner schemas.\n */\nconst WRAPPER_TYPES = new Set([\n \"array\",\n \"nullable\",\n \"nonNullable\",\n \"optional\",\n \"lazyRef\",\n]);\nconst DECIMAL_INPUT_PATTERN = \"^[+-]?(?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)$\";\nconst DECIMAL_OUTPUT_PATTERN =\n \"^(?:0|-?(?:[1-9]\\\\d*(?:\\\\.\\\\d*[1-9])?|0\\\\.\\\\d*[1-9]))$\";\n\n/**\n * The input literal grammar restricted to a declared domain: at most\n * `precision - scale` significant integer digits and at most `scale`\n * significant fractional digits, any leading and trailing zeros aside.\n */\nfunction decimalDomainPattern({ precision, scale }: DecimalDescriptor): string {\n const integer = precision - scale;\n const whole = integer === 0 ? \"0+\" : `(?:0+|0*[1-9]\\\\d{0,${integer - 1}})`;\n const fraction = `\\\\d{0,${scale}}0*`;\n const bareFraction = scale === 0 ? \"0+\" : `\\\\d{1,${scale}}0*`;\n return `^[+-]?(?:${whole}(?:\\\\.${fraction})?|\\\\.${bareFraction})$`;\n}\n\nfunction closedObject(\n properties: Record<string, JsonSchema>,\n required: string[]\n): JsonSchema {\n return {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n };\n}\n\nfunction numRange(minimum: number, maximum: number): JsonSchema {\n return { type: \"number\", minimum, maximum };\n}\n\nfunction wrapNullable(body: JsonSchema, target: JsonSchemaTarget): JsonSchema {\n return target === \"openapi-3.0\"\n ? { ...body, nullable: true }\n : { anyOf: [body, { type: \"null\" }] };\n}\n\nfunction geoPointJsonSchema(): JsonSchema {\n return closedObject(\n {\n [GEO_POINT_KEYS[0]]: numRange(GEO_LONGITUDE_MIN, GEO_LONGITUDE_MAX),\n [GEO_POINT_KEYS[1]]: numRange(GEO_LATITUDE_MIN, GEO_LATITUDE_MAX),\n },\n [...GEO_POINT_KEYS]\n );\n}\n\ntype ConvertibleExactOneSchema = ExactlyOneSchema<\n Record<\n string,\n VibSchema<unknown, unknown> | (() => VibSchema<unknown, unknown>)\n >\n>;\n\ntype ConvertibleDecimalSchema = DecimalSchema<unknown, unknown> & {\n readonly options:\n | (NonNullable<DecimalSchema[\"options\"]> & {\n readonly array?: boolean | undefined;\n readonly nullable?: boolean | undefined;\n })\n | undefined;\n};\n\n/**\n * Traverse through wrapper schemas to find the innermost schema.\n * Wrappers include: array, nullable, optional\n */\nfunction getInnerSchema(schema: any): any {\n let current = schema;\n while (current && WRAPPER_TYPES.has(current.type)) {\n // array uses 'item', others use 'wrapped'\n current = current.item ?? current.wrapped;\n }\n return current;\n}\n\n/**\n * The `$ref` value for an open frame something has just referred back to,\n * allocating it on first use.\n *\n * A cycle back to the document ROOT is the whole document, so it is spelled\n * `#` and hoists nothing. Anything else gets a `$defs` entry: a schema that\n * declares a name keeps it, an anonymous one — every recursive scalar filter,\n * whose `not` arm points back at the filter object itself — gets a generated\n * one. The key is reserved immediately so a second, concurrently-open frame\n * cannot claim it; the placeholder is overwritten with the real body when the\n * frame completes.\n */\nfunction framePointer(\n frame: ConversionFrame,\n context: ConversionContext\n): string {\n if (frame.pointer !== null) return frame.pointer;\n if (frame.schema === context.rootSchema) return (frame.pointer = \"#\");\n const declared = (frame.schema as { options?: { name?: string } }).options\n ?.name;\n let name = declared || undefined;\n while (!name || name in context.definitions)\n name = `Recursive${++context.refCount}`;\n frame.name = name;\n context.definitions[name] = {};\n return (frame.pointer = `#/$defs/${name}`);\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Converts a VibORM schema to JSON Schema format.\n *\n * Cycle-aware: a schema graph may point back at itself (a scalar filter's\n * `not` arm is the filter itself, a model's `where` comes back round through\n * `AND`/`OR`/`NOT`). JSON Schema expresses that with `$ref`, so a schema\n * reached again while its own conversion is still open emits a reference —\n * `#` when it is the document root, otherwise a `$defs` entry holding its\n * body. A schema nothing points back at is unaffected: it is still inlined,\n * byte for byte as before.\n *\n * @param schema - The VibORM schema to convert\n * @param context - The conversion context for tracking references\n * @param skipRef - Whether to skip reference lookup (for inline conversion)\n * @returns The converted JSON Schema\n */\nexport function convertSchema(\n schema: VibSchema<unknown, unknown>,\n context: ConversionContext,\n skipRef = false\n): JsonSchema {\n if (!skipRef) {\n // Check for existing reference (circular schema support)\n const existingRef = context.referenceMap.get(schema);\n if (existingRef) {\n return { $ref: `#/$defs/${existingRef}` };\n }\n\n // Reached a schema that is still being converted further up the stack:\n // the graph is cyclic. Close it with a $ref rather than recursing forever.\n const openFrame = context.activeFrames.get(schema);\n if (openFrame) {\n return { $ref: framePointer(openFrame, context) };\n }\n }\n\n const shadowed = context.activeFrames.get(schema);\n const frame: ConversionFrame = { schema, pointer: null, name: null };\n context.activeFrames.set(schema, frame);\n\n let body: JsonSchema;\n try {\n body = convertSchemaBody(schema, context);\n if (\"options\" in schema && isRecord(schema.options)) {\n if (schema.options.array === true) body = { type: \"array\", items: body };\n if (schema.options.nullable === true)\n body = wrapNullable(body, context.target);\n }\n } finally {\n if (shadowed) {\n context.activeFrames.set(schema, shadowed);\n } else {\n context.activeFrames.delete(schema);\n }\n }\n\n if (frame.name === null) {\n // Either nothing pointed back at this schema, or it IS the document root\n // and the back-references already say `#`. Either way it stays inline.\n return body;\n }\n\n context.definitions[frame.name] = body;\n // Later occurrences of the same schema reuse the definition instead of\n // re-emitting the body.\n context.referenceMap.set(schema, frame.name);\n return { $ref: frame.pointer as string };\n}\n\nconst STATIC_SCHEMAS: Record<string, JsonSchema> = Object.assign(\n Object.create(null),\n {\n boolean: { type: \"boolean\" },\n bigint: { type: \"string\", pattern: BIGINT_TEXT_PATTERN },\n date: { type: \"string\", format: \"date-time\" },\n iso_timestamp: { type: \"string\", format: \"date-time\" },\n iso_date: { type: \"string\", format: \"date\" },\n iso_time: { type: \"string\", format: \"time\" },\n json: {},\n refused: { not: {} },\n blob: { type: \"string\", contentEncoding: \"base64\" },\n }\n);\n\nconst PASSTHROUGH_WRAPPERS = new Set(\n \"optional,transform,field_ref_or,comparison_operand,value_node_or,lazyRef,no_field_ref,written_depth,json_null_or,json_write\".split(\n \",\"\n )\n);\n\nconst SCHEMA_URIS: Record<string, string> = {\n \"draft-2020-12\": \"https://json-schema.org/draft/2020-12/schema\",\n \"draft-07\": \"http://json-schema.org/draft-07/schema#\",\n};\n\n/**\n * The per-type conversion itself. Never call this directly — {@link convertSchema}\n * wraps it with the cycle bookkeeping every recursive schema depends on.\n */\nfunction convertSchemaBody(\n schema: VibSchema<unknown, unknown>,\n context: ConversionContext\n): JsonSchema {\n const conv = (s: VibSchema<unknown, unknown>, skip?: boolean) =>\n convertSchema(s, context, skip);\n const schemaType = schema.type;\n\n if (schemaType === \"decimal\") {\n const domain = (schema as ConvertibleDecimalSchema).options?.decimal;\n return {\n ...(domain && {\n description: `Exact decimal (${domain.precision},${domain.scale})`,\n }),\n type: \"string\",\n pattern:\n context.direction === \"output\"\n ? DECIMAL_OUTPUT_PATTERN\n : domain\n ? decimalDomainPattern(domain)\n : DECIMAL_INPUT_PATTERN,\n };\n }\n\n if (schemaType === \"exact_one\") {\n const arms: JsonSchema[] = [];\n for (const [key, entry] of Object.entries(\n (schema as ConvertibleExactOneSchema).entries\n )) {\n const entrySchema = isFunction<() => VibSchema<unknown, unknown>>(entry)\n ? entry()\n : entry;\n if (entrySchema.type !== \"refused\")\n arms.push(closedObject({ [key]: conv(entrySchema) }, [key]));\n }\n return { oneOf: arms };\n }\n\n const staticSchema = STATIC_SCHEMAS[schemaType];\n if (staticSchema) return { ...staticSchema };\n if (PASSTHROUGH_WRAPPERS.has(schemaType))\n return conv((schema as any).wrapped as VibSchema<unknown, unknown>);\n\n switch (schemaType) {\n case \"string\": {\n const idDomain = (schema as { options?: { idDomain?: IdDomain } }).options\n ?.idDomain;\n return idDomain\n ? { type: \"string\", pattern: idDomainPattern(idDomain) }\n : { type: \"string\" };\n }\n\n case \"number\":\n case \"integer\": {\n const result: JsonSchema = { type: schemaType };\n if (\"minimum\" in schema && typeof schema.minimum === \"number\")\n result.minimum = schema.minimum;\n if (\"maximum\" in schema && typeof schema.maximum === \"number\")\n result.maximum = schema.maximum;\n return result;\n }\n\n case \"literal\": {\n const value = (schema as any).value;\n return context.target === \"openapi-3.0\"\n ? { enum: [value] }\n : { const: value };\n }\n\n case \"enum\":\n return { enum: (schema as any).values };\n\n case \"nullable\":\n return wrapNullable(conv((schema as any).wrapped), context.target);\n\n case \"nonNullable\": {\n const converted = conv((schema as any).wrapped);\n if (Array.isArray(converted.anyOf)) {\n const kept = converted.anyOf.filter(\n (branch: JsonSchema) => branch.type !== \"null\"\n );\n return kept.length === 1 ? kept[0]! : { ...converted, anyOf: kept };\n }\n if (converted.nullable === true) {\n const { nullable: _nullable, ...rest } = converted;\n return rest;\n }\n return converted;\n }\n\n case \"array\":\n return { type: \"array\", items: conv((schema as any).item) };\n\n case \"object\": {\n const entries = (schema as any).entries as Record<string, unknown>;\n const options = (schema as any).options as\n | { partial?: boolean; strict?: boolean; atLeast?: readonly string[] }\n | undefined;\n const partial = options?.partial ?? true;\n const strict = options?.strict ?? true;\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n for (const key in entries) {\n const entry = entries[key];\n const entrySchema = isFunction(entry)\n ? (entry as () => VibSchema<unknown, unknown>)()\n : (entry as VibSchema<unknown, unknown>);\n const inner = getInnerSchema(entrySchema);\n const name = inner?.options?.name;\n if (name && isString(name) && !context.referenceMap.has(inner)) {\n context.referenceMap.set(inner, name);\n context.definitions[name] = conv(inner, true);\n }\n properties[key] = conv(entrySchema);\n const acceptsUndefined =\n (entrySchema as any).type === \"optional\" ||\n (entrySchema as { acceptsUndefined?: boolean }).acceptsUndefined ===\n true;\n const entryOpts = (entrySchema as { options?: unknown }).options;\n const outputDefault =\n context.direction === \"output\" &&\n isRecord(entryOpts) &&\n entryOpts.default !== undefined;\n if (\n (!partial || options?.atLeast?.includes(key)) &&\n (outputDefault || !acceptsUndefined)\n )\n required.push(key);\n }\n return {\n type: \"object\",\n properties,\n required: required.length ? required : undefined,\n ...(strict && { additionalProperties: false }),\n };\n }\n\n case \"record\":\n return {\n type: \"object\",\n additionalProperties: conv((schema as any).value),\n };\n\n case \"union\":\n return {\n anyOf: ((schema as any).options as VibSchema<unknown, unknown>[]).map(\n (opt) => conv(opt)\n ),\n };\n\n case \"vector\": {\n const dimensions = (schema as any).dimensions as number | undefined;\n return {\n type: \"array\",\n items: { type: \"number\" },\n ...(dimensions !== undefined && {\n minItems: dimensions,\n maxItems: dimensions,\n }),\n };\n }\n\n case \"point\":\n return geoPointJsonSchema();\n\n case \"geo_area\": {\n const latitude = numRange(GEO_LATITUDE_MIN, GEO_LATITUDE_MAX);\n const longitude = numRange(GEO_LONGITUDE_MIN, GEO_LONGITUDE_MAX);\n const bounds = closedObject(\n {\n [GEO_BOUNDS_KEYS[0]]: latitude,\n [GEO_BOUNDS_KEYS[1]]: longitude,\n [GEO_BOUNDS_KEYS[2]]: latitude,\n [GEO_BOUNDS_KEYS[3]]: longitude,\n },\n [...GEO_BOUNDS_KEYS]\n );\n const ring: JsonSchema = {\n type: \"array\",\n items: geoPointJsonSchema(),\n minItems: GEO_POLYGON_MIN_RING_POINTS,\n };\n return {\n oneOf: [\n closedObject({ bounds }, [\"bounds\"]),\n closedObject(\n {\n polygon: closedObject(\n { outer: ring, holes: { type: \"array\", items: ring } },\n [\"outer\"]\n ),\n },\n [\"polygon\"]\n ),\n ],\n };\n }\n\n case \"polymorphic_only\": {\n const { wrapped } = schema as VibSchema<unknown, unknown> & {\n wrapped: VibSchema<unknown, unknown>;\n };\n return { ...conv(wrapped), uniqueItems: true };\n }\n\n case \"pipe\":\n return conv((schema as any).schema as VibSchema<unknown, unknown>);\n\n default:\n throw new ValidationError({ kind: \"json-schema\", schemaType }, [\n { path: \"type\", message: `Unsupported type \"${schemaType}\"` },\n ]);\n }\n}\n\nexport function toJsonSchema(\n schema: VibSchema<unknown, unknown>,\n target: JsonSchemaTarget = \"draft-07\"\n): JsonSchema {\n return toJsonSchemaForDirection(schema, target, \"input\");\n}\n\nexport function toJsonSchemaForDirection(\n schema: VibSchema<unknown, unknown>,\n target: JsonSchemaTarget,\n direction: \"input\" | \"output\"\n): JsonSchema {\n if (!SUPPORTED_TARGETS.includes(target))\n throw new ValidationError({ kind: \"json-schema\", target }, [\n { path: \"target\", message: `Unsupported target: ${target}` },\n ]);\n const context = createContext(target, schema, direction);\n const jsonSchema = convertSchema(schema as any, context);\n const schemaUri = SCHEMA_URIS[target];\n if (schemaUri) jsonSchema.$schema = schemaUri;\n if (Object.keys(context.definitions).length > 0)\n jsonSchema.$defs = context.definitions;\n return jsonSchema;\n}\n","/**\n * Factory for creating JSON Schema converters.\n * Each schema gets its own jsonSchema property with input/output methods.\n */\n\nimport type { VibSchema } from \"../types\";\nimport { toJsonSchemaForDirection } from \"./converters\";\nimport type { JsonSchemaConverter, JsonSchemaOptions } from \"./types\";\n\n/**\n * Creates a JSON Schema converter for a VibORM schema.\n * The converter provides `input` and `output` methods that generate\n * JSON Schema representations of the schema's input and output types.\n *\n * @param schema - The VibORM schema to create a converter for\n * @returns A JsonSchemaConverter with input and output methods\n */\nexport function createJsonSchemaConverter(\n schema: VibSchema<unknown, unknown>\n): JsonSchemaConverter {\n return {\n input(options: JsonSchemaOptions): Record<string, unknown> {\n return toJsonSchemaForDirection(schema, options.target, \"input\");\n },\n\n output(options: JsonSchemaOptions): Record<string, unknown> {\n return toJsonSchemaForDirection(schema, options.target, \"output\");\n },\n };\n}\n","import { errorCause, isError } from \"../errors/diagnostic-safety\";\nimport { sanitizeErrorCause } from \"../errors/diagnostics\";\nimport type { ValidationFailure } from \"./types\";\n\nconst PARSE_FAILURE_CAUSE = Symbol(\"viborm.validation.parseFailureCause\");\n\n/** A refused async validator must not leak a later process-level rejection. */\nexport function discardAsyncValidationResult(result: unknown): void {\n Promise.resolve(result).catch(() => undefined);\n}\n\n/** Contain a thrown validator value while retaining sanitized cause evidence. */\nexport function validationFailureFromThrown(cause: unknown): ValidationFailure {\n const error = errorCause(cause);\n const failure: ValidationFailure = {\n issues: [{ message: \"Schema validation failed unexpectedly\" }],\n };\n Object.defineProperty(failure, PARSE_FAILURE_CAUSE, {\n value: sanitizeErrorCause(error),\n });\n return failure;\n}\n\n/**\n * Read the sanitized cause retained by the public parse boundary, if any.\n *\n * The argument is a parse result, and every one of them is built by\n * `parse` itself — the failure literals in `validation/index.ts` and the\n * failure this module defines the symbol on. Reading a symbol off an object\n * the library constructed cannot throw and cannot be handed a non-object, so\n * the type states the invariant and no guard restates it.\n */\nexport function readValidationFailureCause(value: object): Error | undefined {\n const cause = Reflect.get(value, PARSE_FAILURE_CAUSE);\n return isError(cause) ? cause : undefined;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createJsonSchemaConverter } from \"../json-schema/factory\";\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationFailure,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction } from \"../value-guards\";\nimport { canonicalizeId, describeIdDomain, type IdDomain } from \"./id-codec\";\nimport type { ObjectOptions, ObjectSchema } from \"./object\";\n\n// =============================================================================\n// Core Validation Primitives\n// =============================================================================\n\nexport function withWrapped<S extends object>(\n schema: S,\n wrapped: VibSchema<any, any>,\n extra?: object\n): S {\n return Object.assign(schema, {\n wrapped,\n acceptsUndefined:\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true,\n ...extra,\n });\n}\n\n/**\n * Create a failure result with a single issue.\n */\nexport function fail(\n message: string,\n path?: PropertyKey[]\n): ValidationResult<never> {\n const issue: ValidationIssue =\n path && path.length > 0 ? { message, path } : { message };\n return { issues: [issue] };\n}\n\n/** Pre-computed frozen failure for hot-path primitive checks. */\nexport function frozenFail(message: string): ValidationFailure {\n return Object.freeze({\n issues: Object.freeze([Object.freeze({ message })]),\n });\n}\n\n/** Replace `~standard.validate` in place via `wrap(previous)`. */\nexport function patchValidate<S extends VibSchema<any, any>>(\n schema: S,\n wrap: (inner: (value: unknown) => any) => (value: unknown) => any\n): S {\n const std = schema[\"~standard\"];\n Object.defineProperty(std, \"validate\", { value: wrap(std.validate) });\n return schema;\n}\n\n/** Wrap an object schema with a custom validator while preserving its metadata and lazy getters. */\nexport function wrapObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined,\n>(\n schema: ObjectSchema<TEntries, TOpts>,\n validate: ObjectSchema<TEntries, TOpts>[\"~standard\"][\"validate\"]\n): ObjectSchema<TEntries, TOpts> {\n const standard = schema[\"~standard\"];\n return {\n ...schema,\n parse: validate,\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate,\n get types() {\n return standard.types;\n },\n get jsonSchema() {\n return standard.jsonSchema;\n },\n },\n };\n}\n\n/**\n * Whether the parse in progress reports EVERY issue instead of the first. Set\n * by {@link reportingAllIssues} for one synchronous parse and restored in its\n * `finally`, like `parseProviding`'s context. Read only on a failure path, so\n * a parse that succeeds never pays for the mode.\n */\nlet allIssues = false;\n\n/** Does the parse in progress collect every issue? */\nexport const collectingAllIssues = (): boolean => allIssues;\n\n/** Run `parse` with the all-issues mode set to `collect`, then restore it. */\nexport function reportingAllIssues<T>(collect: boolean, parse: () => T): T {\n const outer = allIssues;\n allIssues = collect;\n try {\n return parse();\n } finally {\n allIssues = outer;\n }\n}\n\n/** A member's issues, re-rooted under `key`: only the first unless collecting. */\nexport function issuesUnder(\n key: PropertyKey,\n issues: readonly ValidationIssue[]\n): ValidationIssue[] {\n const reported = allIssues ? issues : issues.slice(0, 1);\n return reported.map((issue) => ({\n message: issue.message,\n path: issue.path ? [key, ...issue.path] : [key],\n }));\n}\n\n/**\n * Create a success result.\n */\nexport function ok<T>(value: T): ValidationResult<T> {\n return { value };\n}\n\n/** Copy Standard Schema issues into VibORM's property-key path representation. */\nexport function standardSchemaFailure(\n issues: readonly StandardSchemaV1.Issue[]\n): ValidationFailure {\n return {\n issues: issues.map((issue) => {\n if (issue.path === undefined) return { message: issue.message };\n return {\n message: issue.message,\n path: issue.path.map((segment) =>\n typeof segment === \"object\" ? segment.key : segment\n ),\n };\n }),\n };\n}\n\n// =============================================================================\n// Set Theory Optimized Validators\n// =============================================================================\n\n// Pre-allocated error objects (avoid allocation in hot path)\nconst ARRAY_TYPE_ERROR = /* @__PURE__ */ frozenFail(\"Expected array\");\nconst ASYNC_ERROR = /* @__PURE__ */ frozenFail(\n \"Async schemas are not supported\"\n);\n\nfunction rejectAsync(pending: PromiseLike<unknown>): ValidationFailure {\n discardAsyncValidationResult(pending);\n return ASYNC_ERROR;\n}\n\n// Pre-allocated null/undefined results for fast paths\nexport const OK_NULL = Object.freeze({ value: null });\nexport const OK_UNDEFINED = Object.freeze({ value: undefined });\n\n/**\n * Validate array items with the provided validator.\n * Shared by the array() wrapper, options.array and every other list walk.\n */\nexport function validateArray<T>(\n value: unknown,\n validate: (v: unknown) => StandardSchemaV1.Result<T>\n): ValidationResult<T[]> {\n try {\n if (!Array.isArray(value)) {\n return ARRAY_TYPE_ERROR;\n }\n } catch {\n return fail(\"Could not inspect array\");\n }\n\n let len: number;\n try {\n len = value.length;\n } catch {\n return fail(\"Could not read array length\");\n }\n if (!Number.isInteger(len) || len < 0) {\n return ARRAY_TYPE_ERROR;\n }\n if (len === 0) return ok([]);\n\n const results = new Array<T>(len);\n let issues: ValidationIssue[] | undefined;\n for (let i = 0; i < len; i++) {\n let member: unknown;\n try {\n member = value[i];\n } catch {\n return fail(\"Could not read array member\", [i]);\n }\n const r = validate(member);\n if (r.issues) {\n const rooted = issuesUnder(i, r.issues as readonly ValidationIssue[]);\n if (!allIssues) return { issues: rooted };\n (issues ??= []).push(...rooted);\n continue;\n }\n results[i] = (r as { value: T }).value;\n }\n return issues ? { issues } : ok(results);\n}\n\ntype ValidatorFn<T> = (value: unknown) => ValidationResult<T>;\n\n// =============================================================================\n// Factories with Default (for optional + default cases)\n// =============================================================================\n\n/**\n * Resolve a default when undefined, contain a throwing factory, and pass the\n * resolved value through the already-composed field validator.\n */\nfunction createOptionalWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => unknown\n): ValidatorFn<T> {\n return (val) => {\n if (val !== undefined) return validate(val);\n let resolved: unknown;\n try {\n resolved = getDefault();\n } catch (error) {\n return fail(`Default failed: ${describeDefaultFailure(error)}`);\n }\n return validate(resolved);\n };\n}\n\n/** Render hostile thrown values without letting their coercion escape. */\nfunction describeDefaultFailure(error: unknown): string {\n try {\n return String(error instanceof Error ? error.message : error);\n } catch {\n return \"unrenderable thrown value\";\n }\n}\n\n// =============================================================================\n// Optimized Validator Builder (Set Theory + Composition)\n// =============================================================================\n\n/** `next` on the value `prev` admitted; `prev`'s issues otherwise. */\nfunction thenValidate(\n prev: ValidatorFn<unknown>,\n next: ValidatorFn<unknown>\n): ValidatorFn<unknown> {\n return (value) => {\n const result = prev(value);\n return result.issues ? result : next(result.value);\n };\n}\n\n/** The canonical member of `domain`, or its \"Expected <domain>\" refusal. */\nfunction idDomainAdmission(domain: IdDomain): ValidatorFn<string> {\n const expected = `Expected ${describeIdDomain(domain)}`;\n return (value) => {\n const canonical = canonicalizeId(value, domain);\n return canonical === undefined ? fail(expected) : ok(canonical);\n };\n}\n\n/**\n * Build an optimized validator at schema creation time.\n * Uses set theory approach for nullable/optional/array/default combinations.\n *\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param typeName - The scalar representation that must survive transforms\n */\nexport function buildValidator<T, TOut, TSchemaOut = T>(\n baseValidate: ValidatorFn<T>,\n options: ScalarOptions<T, TOut, TSchemaOut> | undefined,\n typeName: string\n): ValidatorFn<TOut> {\n // Fast path: no options at all\n if (!options) {\n return baseValidate as unknown as ValidatorFn<TOut>;\n }\n\n const {\n nullable,\n optional,\n array,\n default: defaultVal,\n transform,\n schema,\n disallowZero,\n idDomain,\n } = options;\n\n // Check what we have\n const hasDefault = defaultVal !== undefined;\n const hasTransform = transform !== undefined;\n\n // Build the core validator (base + schema + transform chain)\n let validate: ValidatorFn<any> = baseValidate;\n\n if (disallowZero) validate = thenValidate(validate, refuseZero);\n\n // The identifier domain is the first AND the last word on the value.\n // First, before the custom schema and the transform: a `.schema()` a caller\n // attached to a `.uuid()` field reads the canonical spelling. Last, after\n // that schema: its output is the caller's code — a Standard Schema may\n // return any string — so it crosses the domain again, where an alias it\n // returns folds and a value outside the domain is refused with the same\n // \"Expected <domain>\" an input gets, at admission rather than at the\n // binding. Every identity-sensitive consumer downstream — cache key,\n // captured row key, `fkEquals` — reads the one spelling that leaves, and\n // `canonicalizeId` is the only place an alias is folded. A transform never\n // meets a domain: `scalars/string.ts` is the one caller that passes\n // `idDomain`, and a field state carries no transform.\n const admitIdDomain =\n idDomain === undefined ? undefined : idDomainAdmission(idDomain);\n if (admitIdDomain) validate = thenValidate(validate, admitIdDomain);\n\n // Chain custom schema validation (if any)\n\n if (schema !== undefined) {\n const schemaValidate = schema[\"~standard\"].validate;\n validate = thenValidate(validate, (value) =>\n runValidate(schemaValidate, value)\n );\n if (admitIdDomain) validate = thenValidate(validate, admitIdDomain);\n }\n\n // Chain transform (if any)\n if (hasTransform) validate = withTransform(validate, transform!);\n // A custom JSON schema may transform its input, but the persisted result\n // must still be JSON. Validate the new representation before any write.\n if (typeName === \"json\" && (hasTransform || schema !== undefined))\n validate = thenValidate(validate, baseValidate);\n\n // Compose the complete field validator before the default trigger. A\n // resolved literal or factory value is an ordinary untrusted field value:\n // it crosses scalar/custom/transform, member-array, and nullability rules in\n // exactly the same order as an explicit input.\n\n validate = wrapped(validate, array, nullable);\n\n if (hasDefault) {\n // Compute default getter once\n const getDefault = isFunction(defaultVal)\n ? (defaultVal as () => any)\n : () => defaultVal;\n\n return createOptionalWithDefault(validate, getDefault) as ValidatorFn<TOut>;\n }\n\n // Nullability is already part of the composed validator. Only optionality\n // remains when no default consumes undefined.\n return wrapped(validate, false, false, optional) as ValidatorFn<TOut>;\n}\n\n/**\n * The wrappers every schema shares, innermost first: a list of the value,\n * `null`, `undefined`. Apart from {@link buildValidator}, so a schema that\n * needs these alone (an object) does not carry what a scalar field may\n * declare: an identifier domain and its codec.\n */\nexport function wrapped(\n inner: ValidatorFn<any>,\n array?: boolean,\n nullable?: boolean,\n optional?: boolean\n): ValidatorFn<any> {\n let validate = inner;\n if (array) {\n const itemValidator = validate;\n validate = (val) => validateArray(val, itemValidator);\n }\n if (nullable) {\n const nonNullValidate = validate;\n validate = (val) => (val === null ? OK_NULL : nonNullValidate(val));\n }\n if (optional) {\n const requiredValidate = validate;\n validate = (val) =>\n val === undefined ? OK_UNDEFINED : requiredValidate(val);\n }\n return validate;\n}\n\n// The rarely declared field options, each composed by its own function so a\n// field without them never compiles their setup.\n\nconst refuseZero: ValidatorFn<unknown> = (value) =>\n value === 0 || value === 0n\n ? fail(\"0 disallowed on auto-increment\")\n : ok(value);\n\nexport function transformFail(error: unknown): ValidationResult<never> {\n return fail(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`\n );\n}\n\nexport function withTransform(\n prev: ValidatorFn<any>,\n fn: (value: any) => any\n): ValidatorFn<any> {\n return thenValidate(prev, (value) => {\n try {\n return ok(fn(value));\n } catch (error) {\n return transformFail(error);\n }\n });\n}\n\n// =============================================================================\n// Schema Builder (Returns complete schema object)\n// =============================================================================\n\n/**\n * Build a complete schema object with optimized validator.\n * This is the main entry point for creating scalar schemas.\n *\n * @param type - Schema type name\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param extras - Additional properties to add to the schema (e.g., `value` for literal)\n */\nexport function buildSchema<\n T,\n const Opts extends ScalarOptions<T, any> | undefined,\n TExtras extends Record<string, unknown> = Record<never, never>,\n>(\n type: string,\n baseValidate: ValidatorFn<T>,\n options: Opts,\n extras?: TExtras\n): VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { type: string; options: Opts; acceptsUndefined: boolean } {\n // Pre-compute whether this schema accepts undefined\n // True if: optional, or has a default value\n const acceptsUndefined =\n options?.optional === true || options?.default !== undefined;\n\n // `createSchema` owns the Standard Schema carrier and its lazy JSON Schema\n // converter; a scalar adds only its options and wrapper metadata.\n return Object.assign(\n createSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>>(\n type,\n buildValidator(baseValidate, options, type)\n ),\n { options, acceptsUndefined, ...extras }\n ) as VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { options: Opts; type: string; acceptsUndefined: boolean };\n}\n\n/**\n * Create a StandardSchema-compatible schema object.\n */\nexport function createSchema<TInput, TOutput>(\n type: string,\n validate: (value: unknown) => ValidationResult<TOutput>\n): VibSchema<TInput, TOutput> {\n const schema = {\n type,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n };\n\n // Add the inferred property for type branding\n Object.defineProperty(schema, \" vibInferred\", {\n value: undefined,\n enumerable: false,\n });\n\n return schema as VibSchema<TInput, TOutput>;\n}\n\nexport function runValidate<T>(\n validate: (\n value: unknown\n ) => StandardSchemaV1.Result<T> | PromiseLike<StandardSchemaV1.Result<T>>,\n value: unknown\n): ValidationResult<T> {\n const result = validate(value);\n if (\"then\" in result) return rejectAsync(result);\n if (result.issues) return standardSchemaFailure(result.issues);\n return ok(result.value);\n}\n\n/**\n * Validate a value against a StandardSchema.\n */\nexport function validateSchema<const S extends StandardSchemaV1>(\n schema: S,\n value: unknown\n): ValidationResult<StandardSchemaV1.InferOutput<S>> {\n return runValidate(schema[\"~standard\"].validate, value);\n}\n","/**\n * The exact decimal VALUE type, its accepted spelling, and the text-level\n * arithmetic the field codec needs.\n *\n * A `Decimal` is an immutable signed `BigInt` coefficient and a non-negative\n * scale, `coefficient x 10^-scale`: no NaN, no infinity, no exponent, no\n * statics and no configuration. The constructor and every result strip\n * insignificant fraction zeros and zero is `(0n, 0)`, so `toString()` IS the\n * canonical private text every identity owner keys on.\n *\n * `admitDecimal` is the one admission rule (a string through the grammar,\n * anything else through the brand). The brand is the `#c` private field only\n * the constructor installs, so `canonicalDecimalText` answers `undefined` for\n * `Object.create(Decimal.prototype)`, a look-alike object or a `Proxy`, and no\n * boundary above has to snapshot a foreign representation.\n *\n * The published TYPE is an interface and the published VALUE a const holding\n * the class: result types map every leaf through `Prettify`, a mapped type\n * drops private fields, and a class type would stop being assignable to\n * `Decimal`. The const's declared type keeps the two in step.\n */\n\n/**\n * The accepted literal grammar: optional sign, decimal digits, at most one dot,\n * at least one digit overall. Deliberately NO exponent — `1e3` is a float\n * spelling, and admitting it would mean admitting `1e400` and the rounding\n * question that comes with it. Deliberately no whitespace, no `NaN`, no\n * `Infinity`: none of them name an exact decimal.\n */\nconst DECIMAL_LITERAL_REGEX = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\nconst LEADING_ZEROS_REGEX = /^0+/;\nconst TRAILING_ZEROS_REGEX = /0+$/;\nconst LEADING_SIGN_REGEX = /^[+-]/;\n\n/**\n * Reduce a valid decimal literal to its ONE canonical spelling: no leading `+`,\n * no insignificant leading or trailing zeros, no bare `-0`, no dangling dot.\n *\n * Canonicalization is not cosmetic. It is the private logical representation\n * every identity owner keys on — cursors, row keys, cache keys, race pins, link\n * folds — so two Decimal instances naming the same number are the same key, and\n * `\"1.10\"` and `\"1.1\"` are the same value on every dialect.\n */\nfunction canonicalizeLiteral(literal: string): string {\n const [rawInteger = \"\", rawFraction = \"\"] = literal\n .replace(LEADING_SIGN_REGEX, \"\")\n .split(\".\");\n const whole = rawInteger.replace(LEADING_ZEROS_REGEX, \"\") || \"0\";\n const fraction = rawFraction.replace(TRAILING_ZEROS_REGEX, \"\");\n if (whole === \"0\" && fraction === \"\") return \"0\";\n return `${literal.startsWith(\"-\") ? \"-\" : \"\"}${whole}${fraction === \"\" ? \"\" : `.${fraction}`}`;\n}\n\n/**\n * The canonical text of a `Decimal | string`, or `undefined` when the value\n * names no exact decimal: THE admission rule.\n *\n * The constructor reads a string through it, and the field (`v.decimal()`),\n * the engine binders and the cache encoder read every value through it, so\n * what `s.decimal()` accepts and what `new Decimal()` accepts cannot drift\n * apart. A `Decimal` answers through the brand, never through its shape.\n */\nexport function admitDecimal(value: unknown): string | undefined {\n if (typeof value !== \"string\") return canonicalDecimalText(value);\n return DECIMAL_LITERAL_REGEX.test(value)\n ? canonicalizeLiteral(value)\n : undefined;\n}\n\n/**\n * The two PRIMITIVE forms of an exact decimal a caller may hand the value type:\n * a spelling, or a whole coefficient. Both name an exact decimal; a JavaScript\n * number names a double, so it is not one of them.\n */\nexport type DecimalPrimitive = string | bigint;\n\n/**\n * How a quotient resolves a value exactly between two representable ones.\n *\n * Two modes, each with a caller: `\"half-up\"` is what an application reading a\n * money column expects and what every VibORM release so far has produced;\n * `\"half-even\"` is what the SQL engines do, so a caller reconciling against a\n * server-side division can ask for the server's answer. There is no third mode\n * because there is no third caller.\n */\nexport type DecimalRounding = \"half-up\" | \"half-even\";\n\nconst TEN = 10n;\n\n/** `10^power`, the scale shift both alignment and rounding are spelled with. */\nfunction shift(power: number): bigint {\n return TEN ** BigInt(power);\n}\n\n/**\n * Round `numerator / denominator` to an integer, both taken as non-negative.\n *\n * `\"half-up\"` sends a tie away from zero, which is the sign the caller's\n * coefficient carries separately; `\"half-even\"` sends it to the even neighbour.\n */\nfunction roundQuotient(\n numerator: bigint,\n denominator: bigint,\n rounding: DecimalRounding\n): bigint {\n const quotient = numerator / denominator;\n const doubled = (numerator % denominator) * 2n;\n if (doubled > denominator) return quotient + 1n;\n if (doubled < denominator) return quotient;\n return rounding === \"half-up\" || quotient % 2n !== 0n\n ? quotient + 1n\n : quotient;\n}\n\n/** The accepted spelling, named once for both refusal sentences below. */\nconst DECIMAL_SPELLING = \"decimal string (no exponent/number)\";\n\n/**\n * The FIELD boundary's refusal: `v.decimal()` returns it as its issue message\n * wherever `admitDecimal` answers `undefined`.\n */\nexport const DECIMAL_INPUT_REFUSAL = `Expected Decimal or ${DECIMAL_SPELLING}`;\n\n/**\n * The constructor's refusal. It names one more member than the field's,\n * because the value type also takes a whole `bigint` coefficient, and it shares\n * the grammar and the spelling clause with it.\n */\nexport const DECIMAL_CONSTRUCTOR_REFUSAL = `Expected Decimal, bigint, or ${DECIMAL_SPELLING}`;\n\n/**\n * Write one normalized coefficient and scale as canonical text: the integer\n * digits, a point only when there are fraction digits, and a sign only on a\n * value below zero. The one canonical rendering — `toString` and the seam the\n * codec reads both come here, so no caller can be shown a second spelling;\n * `toFixed` shares its point placement.\n */\nfunction renderParts(coefficient: bigint, scale: number): string {\n const negative = coefficient < 0n;\n return placePoint(\n negative,\n (negative ? -coefficient : coefficient).toString(),\n scale\n );\n}\n\n/** Unsigned digits with the point `fractionDigits` from the right, and a sign. */\nfunction placePoint(\n negative: boolean,\n digits: string,\n fractionDigits: number\n): string {\n const sign = negative ? \"-\" : \"\";\n if (fractionDigits === 0) return `${sign}${digits}`;\n const padded = digits.padStart(fractionDigits + 1, \"0\");\n const point = padded.length - fractionDigits;\n return `${sign}${padded.slice(0, point)}.${padded.slice(point)}`;\n}\n\n/**\n * Write a coefficient and scale with exactly `fractionDigits` fraction digits,\n * rounding half away from zero: `toFixed`.\n */\nfunction renderFixed(\n coefficient: bigint,\n scale: number,\n fractionDigits: number\n): string {\n const negative = coefficient < 0n;\n const rounded = roundQuotient(\n (negative ? -coefficient : coefficient) * shift(fractionDigits),\n shift(scale),\n \"half-up\"\n ).toString();\n // A negative value keeps its sign even when every digit it rounded to is a\n // zero: `-0.004` to two places is `-0.00`, which says the value was below\n // zero and too small to show. Zero itself is never negative, so there is no\n // second rule to apply.\n return placePoint(negative, rounded, fractionDigits);\n}\n\n/**\n * Read already-canonical text straight into a coefficient and a scale.\n *\n * Canonical text carries no `+`, no insignificant zero and no bare `-0`, so\n * what comes out needs no normalization — which is what lets the codec hand\n * over a spelling it has already validated without paying for the grammar a\n * second time.\n */\nfunction partsOfCanonical(canonical: string): [bigint, number] {\n const point = canonical.indexOf(\".\");\n if (point === -1) return [BigInt(canonical), 0];\n const scale = canonical.length - point - 1;\n return [\n BigInt(canonical.slice(0, point) + canonical.slice(point + 1)),\n scale,\n ];\n}\n\n/**\n * The exact decimal VALUE.\n *\n * Immutable: every operation returns a new instance and none of them mutates\n * the receiver. Every binary operation accepts the same\n * `Decimal | DecimalPrimitive` the constructor does, so there is one admission\n * grammar for the whole type.\n *\n * This is an INTERFACE, and {@link Decimal} below is the const that holds the\n * class implementing it. They carry the same name on purpose — a caller writes\n * `Decimal` for both — and the const's declared type is what keeps them in\n * step: a method added to one side and not the other stops compiling.\n *\n * @example\n * new Decimal(\"19.99\").times(\"3\").toString(); // \"59.97\"\n * new Decimal(\"1\").div(\"3\", 5).toString(); // \"0.33333\"\n */\nexport interface Decimal {\n /** Immutable canonical text retained by deep equality and structured cloning. */\n readonly value: string;\n /** This value plus `other`, exactly. */\n plus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value minus `other`, exactly. */\n minus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value times `other`, exactly: coefficients multiply, scales add. */\n times(other: Decimal | DecimalPrimitive): Decimal;\n /**\n * This value divided by `other`, to `fractionDigits` fraction digits.\n *\n * A quotient is the one operation with no exact answer, so it is the one that\n * asks: how many digits, and what happens to a tie.\n *\n * @throws {RangeError} when `other` is zero.\n */\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits?: number,\n rounding?: DecimalRounding\n ): Decimal;\n /** `-1`, `0` or `1` as this value is below, equal to, or above `other`. */\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1;\n /** Whether this value and `other` are the same number. */\n eq(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other`. */\n lt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other` or the same number. */\n lte(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other`. */\n gt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other` or the same number. */\n gte(other: Decimal | DecimalPrimitive): boolean;\n /** This value without its sign. */\n abs(): Decimal;\n /** This value with its sign flipped. Zero has no sign to flip. */\n neg(): Decimal;\n /**\n * The canonical text of this value: no exponent, ever, and no insignificant\n * zero, so two instances naming the same number spell it the same way.\n */\n toString(): string;\n /**\n * This value with exactly `fractionDigits` fraction digits, rounding half\n * away from zero. With no argument it is {@link Decimal.toString}: the whole\n * value, in normal notation, rounded nowhere.\n */\n toFixed(fractionDigits?: number): string;\n /**\n * This value as a JavaScript number, which is a double: the conversion is\n * exact only for values a double can hold, and is the caller's decision.\n */\n toNumber(): number;\n /** The canonical text, so `` `${value}` `` and `+value` read the number. */\n valueOf(): string;\n /** The canonical text, so `JSON.stringify` writes the number, not `{}`. */\n toJSON(): string;\n}\n\n/**\n * The two module-private readers of a Decimal's private fields, captured from\n * inside the class body.\n *\n * Captured rather than declared `static` so the published constructor carries\n * no static property at all: `Object.getOwnPropertyNames(Decimal)` is\n * `length`, `name`, `prototype` and nothing else, which is the \"no\n * configuration, in either direction\" promise made literal.\n */\nlet owns: (value: unknown) => value is ExactDecimal;\nlet textOf: (value: ExactDecimal) => string;\n\n/**\n * The class, and the only place a `#c` is installed.\n *\n * Named for what it is rather than `Decimal`, which the interface above already\n * takes: it is not a wrapper AROUND a decimal, it IS the exact decimal, and a\n * class named `DecimalValue`/`DecimalWrapper` beside a `Decimal` is exactly the\n * second-owner shape the language census refuses.\n *\n * Module-private: what the package exports is {@link Decimal} below, whose\n * declared type carries ONE construct signature — the public grammar. The\n * two-argument form here is the internal seam a coefficient at a non-zero\n * scale arrives through; TypeScript outside this module cannot spell it, but\n * untyped JavaScript reaches it (`new Decimal(123n, 2)` is 1.23) and the\n * scale is not checked there.\n */\nclass ExactDecimal implements Decimal {\n readonly #c: bigint;\n readonly #scale: number;\n readonly value: string;\n\n constructor(value: Decimal | DecimalPrimitive, scale?: number) {\n // A `bigint` is a coefficient: a public one is a whole number (scale 0),\n // and the internal seam passes its scale. Normalized here so every result\n // in this file is normalized in one place.\n let text: string;\n if (typeof value === \"bigint\") {\n let coefficient = value;\n let places = scale ?? 0;\n while (places > 0 && coefficient % TEN === 0n) {\n coefficient /= TEN;\n places--;\n }\n this.#c = coefficient;\n this.#scale = coefficient === 0n ? 0 : places;\n text = renderParts(this.#c, this.#scale);\n } else if (owns(value)) {\n // The BRAND, not `instanceof`: a prototype is forgeable and a private field\n // is not, so a value that only wears the prototype falls through to the\n // refusal below instead of failing on a field it does not have.\n this.#c = value.#c;\n this.#scale = value.#scale;\n text = value.value;\n } else {\n const canonical = admitDecimal(value);\n if (canonical === undefined) {\n throw new TypeError(DECIMAL_CONSTRUCTOR_REFUSAL);\n }\n const [coefficient, places] = partsOfCanonical(canonical);\n this.#c = coefficient;\n this.#scale = places;\n text = canonical;\n }\n this.value = text;\n Object.defineProperty(this, \"value\", {\n writable: false,\n configurable: false,\n });\n }\n\n static {\n owns = (value: unknown): value is ExactDecimal =>\n typeof value === \"object\" && value !== null && #c in value;\n textOf = (value) => value.value;\n }\n\n /** The coefficient this value would carry at `scale`, which is never less. */\n #at(scale: number): bigint {\n return this.#c * shift(scale - this.#scale);\n }\n\n #align(other: Decimal | DecimalPrimitive): [bigint, bigint, number] {\n const rhs = new ExactDecimal(other);\n const scale = Math.max(this.#scale, rhs.#scale);\n return [this.#at(scale), rhs.#at(scale), scale];\n }\n\n plus(other: Decimal | DecimalPrimitive): Decimal {\n const [left, right, scale] = this.#align(other);\n return new ExactDecimal(left + right, scale);\n }\n\n minus(other: Decimal | DecimalPrimitive): Decimal {\n const [left, right, scale] = this.#align(other);\n return new ExactDecimal(left - right, scale);\n }\n\n times(other: Decimal | DecimalPrimitive): Decimal {\n const factor = new ExactDecimal(other);\n return new ExactDecimal(this.#c * factor.#c, this.#scale + factor.#scale);\n }\n\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits = 20,\n rounding: DecimalRounding = \"half-up\"\n ): Decimal {\n const divisor = new ExactDecimal(other);\n if (divisor.#c === 0n) throw new RangeError(\"Division by zero\");\n const numerator = this.#c * shift(divisor.#scale + fractionDigits);\n const denominator = divisor.#c * shift(this.#scale);\n const negative = numerator < 0n !== denominator < 0n;\n const magnitude = roundQuotient(\n numerator < 0n ? -numerator : numerator,\n denominator < 0n ? -denominator : denominator,\n rounding\n );\n return new ExactDecimal(negative ? -magnitude : magnitude, fractionDigits);\n }\n\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1 {\n const [left, right] = this.#align(other);\n return left < right ? -1 : left > right ? 1 : 0;\n }\n\n eq(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 0;\n }\n\n lt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === -1;\n }\n\n lte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== 1;\n }\n\n gt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 1;\n }\n\n gte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== -1;\n }\n\n abs(): Decimal {\n return new ExactDecimal(this.#c < 0n ? -this.#c : this.#c, this.#scale);\n }\n\n neg(): Decimal {\n return new ExactDecimal(-this.#c, this.#scale);\n }\n\n toString(): string {\n return renderParts(this.#c, this.#scale);\n }\n\n toFixed(fractionDigits?: number): string {\n return fractionDigits === undefined\n ? this.toString()\n : renderFixed(this.#c, this.#scale, fractionDigits);\n }\n\n toNumber(): number {\n return Number(this.toString());\n }\n\n valueOf(): string {\n return this.toString();\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `Decimal(\"${this.value}\")`;\n }\n}\n\n/**\n * The public constructor, carrying the one grammar a caller may spell.\n *\n * The same object as the class, so `instanceof` and `Object.create(\n * Decimal.prototype)` behave exactly as they would for a plain class\n * declaration — only the internal two-argument construction is hidden, and the\n * instance TYPE stays free of private fields so a mapped result type keeps it.\n */\nexport const Decimal: {\n /**\n * @param value a `Decimal` to copy, an exact decimal string, or a whole\n * `bigint`.\n * @throws {TypeError} for every other value, including every JavaScript\n * number, a string outside the accepted grammar, and a value of any other\n * type.\n */\n new (value: Decimal | DecimalPrimitive): Decimal;\n readonly prototype: Decimal;\n} = ExactDecimal;\n\n/**\n * Construct one Decimal from text this module's own grammar already admitted.\n *\n * The decode half of every result, cache and default boundary. The codec has\n * established the spelling before calling, so re-testing it here would make the\n * grammar two owners deep; a caller that has NOT established it uses the\n * ordinary constructor, which is the only other way in.\n */\nexport function fromCanonical(canonical: string): Decimal {\n const [coefficient, scale] = partsOfCanonical(canonical);\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The canonical text of a value that IS one of ours, or `undefined`.\n *\n * The whole value boundary, in one function: the private field is installed by\n * the constructor and by nothing else, so answering at all is a witness of\n * CONSTRUCTION rather than a reading of a shape — `undefined` for\n * `Object.create(Decimal.prototype)`, for a plain object carrying the same\n * keys, for a `Proxy` around a real one, and for every other value there is.\n *\n * The text is read from the fields, deliberately NOT through `value.toString()`:\n * the prototype is an object an application can write to, and a codec that\n * rendered through it would be rendering whatever the application put there.\n * The fields are reachable from inside the class body and from nowhere else, so\n * this is the only rendering no caller can move — and it shares `renderParts`\n * with the prototype method, so there is still one spelling.\n */\nexport function canonicalDecimalText(value: unknown): string | undefined {\n return owns(value) ? textOf(value) : undefined;\n}\n\n/**\n * The Decimal `coefficient x 10^-scale`: the decode seam for an unscaled\n * integer a provider stored, normalized by the constructor like every result.\n */\nexport function fromCoefficient(coefficient: bigint, scale: number): Decimal {\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The unscaled integer coefficient of canonical text at `scale`, which is never\n * less than the text's own: `logical x 10^scale`, exact because it is the\n * value's own `BigInt` shifted, never a JavaScript multiplication.\n */\nexport function toCoefficient(canonical: string, scale: number): string {\n const [coefficient, own] = partsOfCanonical(canonical);\n return (coefficient * shift(scale - own)).toString();\n}\n\n/**\n * Why canonical text is outside the domain `{ precision, scale }`, or\n * `undefined` when it fits: the one owner of both refusal sentences.\n *\n * Fitting is a DOMAIN question, not a spelling one: `\"1.2\"` at scale 5 fits and\n * stays `\"1.2\"`. Only digits past `scale`, or an unscaled coefficient wider\n * than `precision`, are outside, and both are refused rather than rounded.\n *\n * Read from the TEXT, in one pass and with no allocation: a declared scale may\n * be as large as `Number.MAX_SAFE_INTEGER` before a provider bounds it, and a\n * field refuses an over-long literal before any `BigInt` is built.\n */\nexport function domainRefusal(\n canonical: string,\n precision: number,\n scale: number\n): string | undefined {\n const point = canonical.indexOf(\".\");\n const fractionDigits = point === -1 ? 0 : canonical.length - point - 1;\n if (fractionDigits > scale) {\n return `'${canonical}' exceeds scale ${scale} (${fractionDigits} fractional digits)`;\n }\n const start = canonical.startsWith(\"-\") ? 1 : 0;\n let digits: number;\n if (canonical[start] !== \"0\") {\n // Canonical text has no leading zero, so every integer digit counts.\n digits = (point === -1 ? canonical.length : point) - start + scale;\n } else {\n // A zero integer part: the coefficient starts at the first non-zero\n // fraction digit, and zero itself has none.\n let first = point + 1;\n while (canonical[first] === \"0\") first++;\n digits = point === -1 ? 0 : scale - (first - point - 1);\n }\n if (digits > precision) {\n return `'${canonical}' exceeds precision ${precision} (${digits} digits)`;\n }\n return undefined;\n}\n","/**\n * The field-aware decimal codec: the descriptor type, the two physical\n * vocabularies a column crosses through, the provider decode grammars and\n * their domain limits, the two DDL renderings, the widened-sum decode and the\n * JSON list container. The value and its arithmetic are `decimal-value.ts`'s;\n * a value whose `canonicalDecimalText` answers was built by its constructor,\n * so there is nothing here to snapshot or defend against.\n */\n\nimport { isString } from \"../value-guards\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n type Decimal,\n domainRefusal,\n fromCanonical,\n fromCoefficient,\n toCoefficient,\n} from \"./decimal-value\";\n\n// =============================================================================\n// THE DOMAIN\n// =============================================================================\n\n/**\n * The fixed-decimal domain: multiples of `10^-scale` whose unscaled coefficient\n * has at most `precision` digits. Frozen once by `s.decimal` and carried by\n * reference through every modifier.\n */\nexport interface DecimalDescriptor {\n readonly precision: number;\n readonly scale: number;\n}\n\n/** Whether two optional descriptor references declare the same value domain. */\nexport function sameDecimalDescriptor(\n left: DecimalDescriptor | undefined,\n right: DecimalDescriptor | undefined\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return left.precision === right.precision && left.scale === right.scale;\n}\n\n/**\n * The two exact physical vocabularies a decimal field can cross through.\n *\n * The active adapter selects one; this codec alone interprets it. The value\n * cannot select its own vocabulary because `\"120\"` is logical 120 as native\n * decimal text and logical 1.2 as a scale-2 coefficient.\n */\nexport type DecimalPhysicalRepresentation = \"text\" | \"coefficient\";\n\n/**\n * The codec's names for four value-module seams: the admission rule\n * (`admitDecimal`), the brand reader (`canonicalDecimalText`), the\n * grammar-skipping decode seam (`fromCanonical`) and the coefficient at a\n * scale (`toCoefficient`). Each is the same function, not a wrapper around it.\n * They are the names every other module reaches: the language census lets only\n * this codec and the root entry import a construction seam from the value\n * module at runtime, so `primitives/decimal.ts`, the engine's binders, result\n * parser and cache, and the migration readers build and admit through here.\n */\nexport const canonicalizeDecimal = admitDecimal;\nexport const canonicalizeMaterializedDecimal = canonicalDecimalText;\nexport const toDecimal = fromCanonical;\nexport const logicalToCoefficient = toCoefficient;\n\n// =============================================================================\n// THE COEFFICIENT VOCABULARY\n// =============================================================================\n\n/**\n * The one physical coefficient spelling: `0`, or an optional minus and digits\n * with no leading zero. `BigInt` alone would also read `\" 1 \"`, `\"0x10\"` and\n * `\"\"`, so a provider value crosses this before it becomes a number.\n */\nconst COEFFICIENT_REGEX = /^(?:0|-?[1-9]\\d*)$/;\n\n/**\n * Decode one untrusted unscaled coefficient at `scale`, or `undefined` when it\n * is outside the vocabulary or wider than `precision` digits. The length is\n * bounded before the `BigInt` is built.\n */\nfunction decodeCoefficient(\n value: unknown,\n scale: number,\n precision?: number\n): Decimal | undefined {\n if (!(isString(value) && COEFFICIENT_REGEX.test(value))) return undefined;\n const digits = value.startsWith(\"-\") ? value.length - 1 : value.length;\n if (precision !== undefined && digits > precision) return undefined;\n return fromCoefficient(BigInt(value), scale);\n}\n\n/** The canonical text of a decoded coefficient, or `undefined`. */\nfunction decodeCoefficientText(\n value: unknown,\n scale: number,\n precision?: number\n): string | undefined {\n const decoded = decodeCoefficient(value, scale, precision);\n return decoded === undefined ? undefined : canonicalDecimalText(decoded);\n}\n\n// =============================================================================\n// PROVIDER TEXT DECODE\n// =============================================================================\n\n/** Physical decimal text emitted by PostgreSQL/MySQL: optional minus, no leading zero, optional fraction. */\nconst PROVIDER_TEXT_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/;\n\nfunction decodeProviderText(\n value: unknown,\n scale: number,\n precision = Number.POSITIVE_INFINITY\n): string | undefined {\n if (!(isString(value) && PROVIDER_TEXT_REGEX.test(value))) return undefined;\n const canonical = admitDecimal(value)!;\n return domainRefusal(canonical, precision, scale) === undefined\n ? canonical\n : undefined;\n}\n\n/**\n * Decode one scalar field value read back as native decimal text, or\n * `undefined` when the provider returned something outside the field's declared\n * domain or outside the physical vocabulary the adapter promised.\n *\n * The PostgreSQL/MySQL scalar-read half of the codec: a column declared\n * `NUMERIC(p,s)` cannot answer with more than `s` fractional digits or more\n * than `p` coefficient digits, so a value that does is a column the schema no\n * longer describes rather than a number to widen the field for.\n */\nexport function decodeFieldScalar(\n text: unknown,\n descriptor: DecimalDescriptor\n): string | undefined {\n return decodeProviderText(text, descriptor.scale, descriptor.precision);\n}\n\n/**\n * Decode an aggregate SUM, which keeps the field's SCALE but is deliberately\n * NOT held to its precision: adding a million `precision: 10` rows produces a\n * legitimate answer wider than any single column. `undefined` means the\n * provider returned something that is not an exact decimal at this scale.\n */\nexport function decodeWidenedSum(\n value: unknown,\n scale: number\n): string | undefined {\n return decodeProviderText(value, scale);\n}\n\n// =============================================================================\n// PROVIDER PHYSICAL REPRESENTATION\n// =============================================================================\n\nfunction encodePhysicalDecimalAtScale(\n canonical: string,\n scale: number,\n representation: DecimalPhysicalRepresentation\n): string {\n return representation === \"coefficient\"\n ? toCoefficient(canonical, scale)\n : canonical;\n}\n\n/**\n * Encode one trusted canonical logical value in the vocabulary selected by the\n * active adapter. SQL construction remains with that adapter.\n */\nexport function encodePhysicalDecimal(\n canonical: string,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string {\n return encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n}\n\nfunction decodePhysical(\n value: unknown,\n scale: number,\n representation: DecimalPhysicalRepresentation,\n precision?: number\n): string | undefined {\n return representation === \"text\"\n ? decodeProviderText(value, scale, precision)\n : decodeCoefficientText(value, scale, precision);\n}\n\nfunction materializePhysical(\n value: unknown,\n scale: number,\n representation: DecimalPhysicalRepresentation,\n precision?: number\n): Decimal | undefined {\n if (representation === \"coefficient\") {\n return decodeCoefficient(value, scale, precision);\n }\n const canonical = decodeProviderText(value, scale, precision);\n return canonical === undefined ? undefined : fromCanonical(canonical);\n}\n\n/**\n * Decode one untrusted provider scalar into canonical private logical text.\n */\nexport function decodePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return decodePhysical(\n value,\n descriptor.scale,\n representation,\n descriptor.precision\n );\n}\n\n/**\n * Decode one ordinary scalar directly into its one fresh public Decimal.\n */\nexport function materializePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return materializePhysical(\n value,\n descriptor.scale,\n representation,\n descriptor.precision\n );\n}\n\n/**\n * Encode the ordered input members that the adapter will place in its native\n * array or JSON-backed coefficient container. Canonicalization stays inside\n * the codec so the caller does not need a second list pass or conversion owner.\n */\nexport function encodePhysicalDecimalListMembers(\n values: readonly unknown[],\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n const members = new Array<string>(values.length);\n for (const [index, value] of values.entries()) {\n const canonical = admitDecimal(value);\n if (canonical === undefined) return undefined;\n members[index] = encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n }\n return members;\n}\n\n/**\n * Decode one provider list into canonical private logical members. Text means\n * a native array of exact decimal strings; coefficient means one JSON text\n * container of coefficient strings.\n */\nexport function decodePhysicalDecimalList(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n if (representation === \"coefficient\") {\n return decodeDecimalListContainer(\n value,\n descriptor.scale,\n descriptor.precision\n );\n }\n try {\n if (!Array.isArray(value)) return undefined;\n const length = value.length;\n if (!Number.isSafeInteger(length) || length < 0) return undefined;\n const members = new Array<string>(length);\n for (let index = 0; index < length; index++) {\n if (!Object.hasOwn(value, index)) return undefined;\n const canonical = decodeFieldScalar(value[index], descriptor);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n return members;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decode an exact SUM while retaining only the declared scale. The field\n * precision is deliberately not applied because sums widen.\n */\nexport function decodePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return decodePhysical(value, descriptor.scale, representation);\n}\n\n/** Decode one widened SUM directly into its one fresh public Decimal. */\nexport function materializePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return materializePhysical(value, descriptor.scale, representation);\n}\n\n// =============================================================================\n// THE TWO DDL RENDERINGS\n// =============================================================================\n\n/** The dialects that spell a fixed decimal, in `NativeType[\"db\"]` vocabulary. */\nexport type DecimalDialect = \"pg\" | \"mysql\" | \"sqlite\";\n\n// =============================================================================\n// PROVIDER PHYSICAL LIMITS\n// =============================================================================\n\n/**\n * What each provider can physically store, as one table (plan 3.1).\n *\n * PostgreSQL's `NUMERIC(p,s)` tops out at 1000 digits. MySQL's `DECIMAL(p,s)`\n * tops out at 65 digits with at most 30 after the point, and exact coefficient\n * arithmetic additionally needs `precision + scale <= 65`. SQLite's bound is not\n * a storage limit at all — it stores the unscaled coefficient in an int64 — but\n * the requirement of the one-statement multiply/divide: `precision + scale <=\n * 18` is what makes every in-range rounded result computable without\n * overflowing the intermediate, and 18 digits is also the widest literal\n * SQLite's own parser reads as an integer rather than as a REAL, which is what\n * the descriptor's range CHECK is written in.\n *\n * A descriptor is syntactically valid at model construction regardless: a\n * schema valid for PostgreSQL stays a valid model graph, and only BINDING it to\n * a provider that cannot store it fails.\n */\nconst PROVIDER_LIMITS: Record<\n DecimalDialect,\n { readonly precision: number; readonly scale: number; readonly sum?: number }\n> = {\n pg: { precision: 1000, scale: 1000 },\n mysql: { precision: 65, scale: 30, sum: 65 },\n sqlite: { precision: 18, scale: 18, sum: 18 },\n};\n\n/**\n * Why this provider cannot store this descriptor, or `undefined` when it can:\n * one sentence per failing bound, naming the descriptor, the provider and the\n * limit — the caller adds the field. Read by the schema bind boundary\n * (`provider-limits.ts`) before any provider I/O, and by the migration layer.\n */\nexport function describeProviderLimitRefusal(\n dialect: DecimalDialect,\n descriptor: DecimalDescriptor\n): string | undefined {\n const limit = PROVIDER_LIMITS[dialect];\n const { precision, scale } = descriptor;\n const named = describeDecimalDomain(descriptor);\n return precision > limit.precision\n ? `${named} exceeds max precision ${limit.precision}`\n : scale > limit.scale\n ? `${named} exceeds max scale ${limit.scale}`\n : limit.sum !== undefined && precision + scale > limit.sum\n ? `${named} requires precision + scale <= ${limit.sum}`\n : undefined;\n}\n\n/**\n * The physical column type for this descriptor.\n *\n * SQLite has no exact decimal type — `DECIMAL(10,5)` is only a NUMERIC-affinity\n * spelling whose numbers it ignores — so it stores the signed integer\n * coefficient and the migration driver adds the range check that makes the\n * declared precision real.\n *\n * No space after the comma, on every dialect: the emitted text is compared by\n * the differ, so one descriptor has one spelling.\n */\nexport function decimalColumnType(\n dialect: DecimalDialect,\n { precision, scale }: DecimalDescriptor\n): string {\n return dialect === \"sqlite\"\n ? \"INTEGER\"\n : `${dialect === \"pg\" ? \"NUMERIC\" : \"DECIMAL\"}(${precision},${scale})`;\n}\n\n/**\n * The DDL literal for a default. PostgreSQL and MySQL take the value padded to\n * `scale` fraction digits, because that is what MySQL reads back from\n * `information_schema`: canonical `1.2` on a scale-5 column would read back as\n * `1.20000` and the differ would see a change on every push. SQLite takes the\n * coefficient, the same integer the column stores.\n *\n * The text is padded, never rounded: PostgreSQL introspection hands back\n * catalog text the column's scale never touched (`DEFAULT 1.005` on\n * `NUMERIC(10,2)` stays `1.005`), and the differ compares what the DDL\n * declared. A scale-0 column keeps the integer part.\n */\nexport function decimalDefaultText(\n dialect: DecimalDialect,\n canonical: string,\n descriptor: DecimalDescriptor\n): string {\n const { scale } = descriptor;\n if (dialect === \"sqlite\") return toCoefficient(canonical, scale);\n const point = canonical.indexOf(\".\");\n if (scale === 0) return point === -1 ? canonical : canonical.slice(0, point);\n if (point === -1) return `${canonical}.${\"0\".repeat(scale)}`;\n return canonical.padEnd(point + 1 + scale, \"0\");\n}\n\n/**\n * The physical value of one trusted literal decimal-list default.\n *\n * PostgreSQL owns a native numeric array, so every logical member is padded to\n * the declared scale just like a scalar DDL default. MySQL and the SQLite\n * family own coefficient-string JSON containers, exactly like their runtime\n * list writes. This codec renders the VALUE only; migration drivers still own\n * string quoting and provider expression syntax.\n */\nexport function decimalListDefaultText(\n dialect: DecimalDialect,\n canonicals: readonly string[],\n descriptor: DecimalDescriptor\n): string {\n if (dialect !== \"pg\") {\n return encodeDecimalListContainer(canonicals, descriptor.scale);\n }\n return `{${canonicals.map((c) => decimalDefaultText(\"pg\", c, descriptor)).join(\",\")}}`;\n}\n\n// =============================================================================\n// THE JSON LIST CONTAINER\n// =============================================================================\n\nexport function encodeDecimalListContainer(\n canonicals: readonly string[],\n scale: number\n): string {\n return JSON.stringify(canonicals.map((c) => toCoefficient(c, scale)));\n}\n\n/**\n * The canonical logical members of a physical list container, or `undefined`\n * when the container is not one this codec wrote: malformed JSON, a non-array\n * top level, a numeric token, `null`, or a member outside the coefficient\n * grammar. Order and multiplicity are preserved exactly.\n */\nexport function decodeDecimalListContainer(\n container: unknown,\n scale: number,\n precision?: number\n): string[] | undefined {\n if (!isString(container)) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(container);\n } catch {\n return undefined;\n }\n if (!Array.isArray(parsed)) return undefined;\n const members = new Array<string>(parsed.length);\n for (const [index, member] of parsed.entries()) {\n const canonical = decodeCoefficientText(member, scale, precision);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n return members;\n}\n\n/** Domain diagnostics and catalog admission share the value descriptor owner. */\nexport function describeDecimalDomain(descriptor: DecimalDescriptor): string {\n return `precision ${descriptor.precision}, scale ${descriptor.scale}`;\n}\n\nconst STORED_DECIMAL_INTEGER = /^-?\\d+$/;\nexport function readStoredDecimalDescriptor(\n precisionValue: unknown,\n scaleValue: unknown,\n dialect: DecimalDialect\n): DecimalDescriptor | undefined {\n const precision = readStoredDecimalInteger(precisionValue);\n const scale = readStoredDecimalInteger(scaleValue);\n if (\n precision === undefined ||\n scale === undefined ||\n precision <= 0 ||\n scale < 0 ||\n scale > precision\n )\n return undefined;\n const descriptor = { precision, scale };\n return describeProviderLimitRefusal(dialect, descriptor) === undefined\n ? descriptor\n : undefined;\n}\n\nfunction readStoredDecimalInteger(value: unknown): number | undefined {\n const parsed =\n typeof value === \"number\"\n ? value\n : isString(value) && STORED_DECIMAL_INTEGER.test(value)\n ? Number(value)\n : Number.NaN;\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n","import type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction } from \"../value-guards\";\nimport { createSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Optional Schema\n// =============================================================================\n\n/**\n * Schema or thunk that can be wrapped with optional.\n */\nexport type WrappableSchema =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Unwrap a schema or thunk to get the underlying schema type.\n */\ntype UnwrapSchema<T> =\n T extends VibSchema<any, any>\n ? T\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\nexport interface OptionalSchema<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n TInput = InferInput<UnwrapSchema<TWrapped>> | undefined,\n TOutput = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"optional\";\n readonly wrapped: TWrapped;\n readonly default: TDefault;\n readonly acceptsUndefined: true;\n}\n\n// Compute output type based on default\ntype OptionalOutput<\n TWrapped extends WrappableSchema,\n TDefault,\n> = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>;\n\n/** The validators of the optional schemas built without a default. */\nconst withoutDefault = new WeakSet<VibSchema[\"~standard\"][\"validate\"]>();\n\n/**\n * Is `validate` the validator of a `v.optional` without a default, which\n * answers `undefined` with `{ value: undefined }` and reads nothing else?\n */\nexport const answersAbsentWithUndefined = (\n validate: VibSchema[\"~standard\"][\"validate\"]\n): boolean => withoutDefault.has(validate);\n\n/**\n * Create an optional schema that allows undefined values.\n * Supports both direct schemas and thunks (for circular references).\n * Optionally provide a default value for when undefined is received.\n *\n * @example\n * const optionalName = v.optional(v.string());\n * const nameWithDefault = v.optional(v.string(), \"Unknown\");\n *\n * // With thunks (circular references)\n * const node = v.object({ child: v.optional(() => node) });\n */\nexport function optional<\n TWrapped extends WrappableSchema,\n TDefault extends\n | InferOutput<UnwrapSchema<TWrapped>>\n | (() => InferOutput<UnwrapSchema<TWrapped>>)\n | undefined = undefined,\n>(\n wrapped: TWrapped,\n defaultValue?: TDefault\n): OptionalSchema<TWrapped, TDefault> {\n // Check if wrapped is a thunk (function) or direct schema\n const isThunk = isFunction(wrapped) && !(\"~standard\" in wrapped);\n\n // Lazy resolution for thunks\n let cachedValidate: ((value: unknown) => any) | null = isThunk\n ? null\n : (wrapped as VibSchema<any, any>)[\"~standard\"].validate;\n\n const getValidate = () => {\n if (cachedValidate) return cachedValidate;\n\n const resolvedSchema = (wrapped as () => VibSchema<any, any>)();\n cachedValidate = resolvedSchema[\"~standard\"].validate;\n\n return cachedValidate;\n };\n\n const schema = createSchema(\n \"optional\",\n (value): ValidationResult<OptionalOutput<TWrapped, TDefault>> => {\n // Handle undefined - fast path\n if (value === undefined) {\n if (defaultValue !== undefined) {\n const resolved = isFunction(defaultValue)\n ? (defaultValue as () => InferOutput<UnwrapSchema<TWrapped>>)()\n : defaultValue;\n return ok(resolved) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n return ok(undefined) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n\n // Delegate to wrapped schema (resolve thunk if needed)\n const validate = getValidate();\n return validate(value) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n ) as OptionalSchema<TWrapped, TDefault>;\n\n if (defaultValue === undefined)\n withoutDefault.add(schema[\"~standard\"].validate);\n // Add references\n (schema as any).wrapped = wrapped;\n (schema as any).default = defaultValue;\n // Optional schema always accepts undefined\n (schema as any).acceptsUndefined = true;\n\n return schema;\n}\n","import type {\n InferInputShape,\n InferOutputShape,\n ThunkCast,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport {\n collectingAllIssues,\n createSchema,\n issuesUnder,\n ok,\n withTransform,\n wrapped,\n} from \"./helpers\";\nimport { answersAbsentWithUndefined } from \"./optional\";\n\n// =============================================================================\n// Object Schema Types\n// =============================================================================\n\n/**\n * Object entries - a record of field names to schemas or thunks.\n */\nexport type ObjectEntries = Record<\n string,\n VibSchema<any, any> | ThunkCast<any, any>\n>;\n\n/**\n * Options for object schemas.\n */\nexport interface ObjectOptions<T = unknown, TKeys extends string = string> {\n /** Make all fields optional (default: true) */\n partial?: boolean;\n /** Reject unknown keys (default: true) */\n strict?: boolean;\n /** Make the object itself optional (undefined allowed) */\n optional?: boolean;\n /** Make the object itself nullable (null allowed) */\n nullable?: boolean;\n /** Validate as array of objects */\n array?: boolean;\n /** Default value when undefined/null */\n default?: T | (() => T);\n /** Transform output */\n transform?: (value: T) => T;\n /** Object name for circular references in json schema*/\n name?: string;\n /** Object description for json schema*/\n description?: string;\n /** Require at least these specific keys (works with partial: true) */\n atLeast?: TKeys[];\n /** Require at least one key from each group to be present */\n requiresOneOf?: readonly (readonly TKeys[])[];\n /** Require one key set from each group; all keys in the chosen set must be present */\n requiresOneOfKeySets?: readonly (readonly (readonly TKeys[])[])[];\n /** Omit these keys entirely from the type and validation */\n omit?: TKeys[];\n /** Require at least one key to be present (object cannot be empty) */\n nonEmpty?: boolean;\n /**\n * The WHOLE-OBJECT refusal this object owns, with its own sentence.\n *\n * `atLeast`, `requiresOneOf` and `nonEmpty` each answer one shape of \"which\n * keys must be here\", and each answers it with the primitive's own generic\n * message. A completeness rule that reads more than key presence — \"this\n * filter states no OPERATION\" (`path`/`mode` are modifiers, not operations),\n * \"this `mode` governs nothing here\", \"this `by` names the same column\n * twice\" — has no key-level spelling, and the ones that do still have a\n * REGISTERED sentence the generic message cannot spell.\n *\n * So one hook: it runs after every member validated, over the validated\n * output (a key spelled `undefined` is already absent there, which is the\n * `{ f: undefined }` ≡ `{}` rule the whole surface follows), and returns the\n * refusal sentence, an issue carrying the path of the key that is wrong, or\n * `undefined`. It is deliberately NOT part of the\n * inferred input type: these are runtime completeness facts about a\n * recursive filter surface, and distributing them into the type would turn\n * every filter object into a union of one variant per operator.\n */\n refuse?: (\n value: Record<string, unknown>\n ) => string | ValidationIssue | undefined;\n /**\n * The name this object's fields are provided under: inside\n * {@link parseProviding}, a required field the caller's context provides\n * under it may be absent (the required-field check and the\n * `requiresOneOfKeySets` check count it as given), and a key it adds is\n * admitted with its validator; outside, it changes nothing. It shapes no\n * input type.\n */\n provides?: string | undefined;\n}\n\n/**\n * What the caller's context says of one key of the object a `provides` name\n * names: `true` when it writes that required field itself, a validator when\n * it adds that key to the ones the object declares.\n */\ntype ProvidedFields = (\n name: string,\n field: string\n) => boolean | ((value: unknown) => ValidationResult<unknown>) | undefined;\n\n/**\n * The provided fields of the parse in progress. Set by\n * {@link parseProviding} for one synchronous parse and restored, to the\n * enclosing parse's value or to `undefined`, in its `finally`: no field is\n * provided outside it, after it throws, or to another call.\n */\nlet provided: ProvidedFields | undefined;\n\n/** Does the parse in progress provide `field` of the object named `name`? */\nconst isProvided = (name: string | undefined, field: string): boolean =>\n name !== undefined && provided?.(name, field) === true;\n\n/** The validator of a key the parse in progress adds to the object named `name`. */\nconst added = (name: string | undefined, key: string) => {\n const answer = name === undefined ? undefined : provided?.(name, key);\n return typeof answer === \"function\" ? answer : undefined;\n};\n\n/**\n * Run `parse` where `fields` are provided by the caller's context: an object\n * whose `provides` name they list takes such a required field as absent, not\n * missing, so the caller may leave it out (someone else writes it after the\n * parse). `parse` must be synchronous: the context lives until it returns or\n * throws and is then restored, so a nested call sees its own fields and its\n * caller's come back after it.\n */\nexport function parseProviding<T>(fields: ProvidedFields, parse: () => T): T {\n const outer = provided;\n // An enclosing parse's fields stay provided: a stamped create may also\n // name a projection key.\n provided = outer\n ? (name, field) => fields(name, field) || outer(name, field)\n : fields;\n try {\n return parse();\n } finally {\n provided = outer;\n }\n}\n\n/**\n * Omit specific keys from a type entirely.\n * Preserves optionality of remaining keys.\n */\ntype VOmit<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]: T[P];\n};\n\ntype OmittedKeyUnion<TKeys> = TKeys extends readonly PropertyKey[]\n ? Extract<TKeys[number], string>\n : never;\n\ntype KeepRequirementGroup<\n Group,\n OmittedKeys extends string,\n> = Group extends readonly string[]\n ? [Extract<Group[number], OmittedKeys>] extends [never]\n ? Group\n : never\n : never;\n\ntype KeepRequirementKeySetGroup<\n Group,\n OmittedKeys extends string,\n> = Group extends readonly (readonly string[])[]\n ? [Extract<Group[number][number], OmittedKeys>] extends [never]\n ? Group\n : never\n : never;\n\ntype ActiveRequirementGroups<\n Groups,\n OmittedKeys extends string,\n> = Groups extends readonly [\n infer Group extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n]\n ? KeepRequirementGroup<Group, OmittedKeys> extends never\n ? ActiveRequirementGroups<Rest, OmittedKeys>\n : readonly [\n KeepRequirementGroup<Group, OmittedKeys>,\n ...ActiveRequirementGroups<Rest, OmittedKeys>,\n ]\n : Groups extends readonly (infer Group extends readonly string[])[]\n ? readonly Exclude<KeepRequirementGroup<Group, OmittedKeys>, never>[]\n : readonly [];\n\ntype ActiveRequirementKeySetGroups<\n Groups,\n OmittedKeys extends string,\n> = Groups extends readonly [\n infer Group extends readonly (readonly string[])[],\n ...infer Rest extends readonly (readonly (readonly string[])[])[],\n]\n ? KeepRequirementKeySetGroup<Group, OmittedKeys> extends never\n ? ActiveRequirementKeySetGroups<Rest, OmittedKeys>\n : readonly [\n KeepRequirementKeySetGroup<Group, OmittedKeys>,\n ...ActiveRequirementKeySetGroups<Rest, OmittedKeys>,\n ]\n : Groups extends readonly (infer Group extends\n readonly (readonly string[])[])[]\n ? readonly Exclude<KeepRequirementKeySetGroup<Group, OmittedKeys>, never>[]\n : readonly [];\n\ntype ActiveOmitRequirements<TOpts, OmittedKeys extends string> = Omit<\n TOpts,\n \"requiresOneOf\" | \"requiresOneOfKeySets\"\n> &\n (TOpts extends {\n requiresOneOf: infer Groups extends readonly (readonly string[])[];\n }\n ? {\n requiresOneOf: ActiveRequirementGroups<Groups, OmittedKeys>;\n }\n : unknown) &\n (TOpts extends {\n requiresOneOfKeySets: infer Groups extends\n readonly (readonly (readonly string[])[])[];\n }\n ? {\n requiresOneOfKeySets: ActiveRequirementKeySetGroups<\n Groups,\n OmittedKeys\n >;\n }\n : unknown);\n\n/**\n * Compute input type based on partial option.\n * Default is partial: true, so only non-partial when explicitly { partial: false }\n * If atLeast is specified, those keys are required even when partial: true\n * If omit is specified, those keys are removed from the type entirely\n */\ntype ComputeObjectInput<TEntries, TOpts> = TOpts extends {\n omit: infer OmitKeys extends readonly string[];\n}\n ? TOpts extends { partial: false }\n ? ApplyRequiresOneOf<\n VOmit<InferInputShape<TEntries>, OmitKeys[number]>,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : TOpts extends { atLeast: infer Keys extends readonly string[] }\n ? ApplyRequiresOneOf<\n VOmit<\n RequireKeys<Partial<InferInputShape<TEntries>>, Keys[number]>,\n OmitKeys[number]\n >,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : ApplyRequiresOneOf<\n VOmit<Partial<InferInputShape<TEntries>>, OmitKeys[number]>,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : TOpts extends { partial: false }\n ? ApplyRequiresOneOf<InferInputShape<TEntries>, TOpts>\n : TOpts extends { atLeast: infer Keys extends readonly string[] }\n ? ApplyRequiresOneOf<\n RequireKeys<Partial<InferInputShape<TEntries>>, Keys[number]>,\n TOpts\n >\n : ApplyRequiresOneOf<Partial<InferInputShape<TEntries>>, TOpts>;\n\n/**\n * Compute output type based on entries.\n * Unlike input, output doesn't use Partial - each field's schema determines\n * whether its output includes undefined (based on whether it has a default).\n */\ntype ComputeObjectOutput<TEntries, _TOpts> = InferOutputShape<TEntries>;\n\n/**\n * Make specific keys required in an otherwise partial object.\n * Uses a mapped type instead of Omit & Required<Pick> to reduce type depth.\n */\ntype RequireKeys<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]?: T[P];\n} & {\n [P in keyof T as P extends K ? P : never]-?: T[P];\n};\n\ntype RequireOneKey<T, K extends PropertyKey> = T extends unknown\n ? K extends keyof T\n ? RequireKeys<T, Extract<K, string>>\n : never\n : never;\n\ntype ApplyRequiresOneOf<T, TOpts> = TOpts extends {\n requiresOneOf: infer Groups extends readonly (readonly string[])[];\n}\n ? ApplyRequiresOneOfKeySets<ApplyRequiresOneOfGroups<T, Groups>, TOpts>\n : ApplyRequiresOneOfKeySets<T, TOpts>;\n\ntype ApplyRequiresOneOfGroups<T, Groups> = Groups extends readonly [\n infer Group extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n]\n ? ApplyRequiresOneOfGroups<RequireOneKey<T, Group[number]>, Rest>\n : Groups extends readonly (infer Group extends readonly string[])[]\n ? [Group[number]] extends [never]\n ? T\n : RequireOneKey<T, Group[number]>\n : T;\n\ntype ApplyRequiresOneOfKeySets<TCurrent, TOpts> = TOpts extends {\n requiresOneOfKeySets: infer Groups extends\n readonly (readonly (readonly string[])[])[];\n}\n ? ApplyRequiresOneOfKeySetGroups<TCurrent, Groups>\n : TCurrent;\n\ntype RequireKeySet<T, K extends PropertyKey> = T extends unknown\n ? RequireKeys<T, Extract<K, string>>\n : never;\n\ntype RequireOneKeySet<T, Alternatives> = [Alternatives] extends [never]\n ? T\n : Alternatives extends readonly []\n ? never\n : Alternatives extends readonly [\n infer KeySet extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n ]\n ? RequireKeySet<T, KeySet[number]> | RequireOneKeySet<T, Rest>\n : Alternatives extends readonly (infer KeySet extends readonly string[])[]\n ? [KeySet[number]] extends [never]\n ? T\n : RequireKeySet<T, KeySet[number]>\n : T;\n\ntype UnionToIntersection<T> = (\n T extends unknown\n ? (value: T) => void\n : never\n) extends (value: infer I) => void\n ? I\n : never;\n\ntype RequireEveryKeySetGroup<T, Group> =\n UnionToIntersection<\n Group extends unknown ? { value: RequireOneKeySet<T, Group> } : never\n > extends { value: infer I }\n ? I & T\n : T;\n\ntype ApplyRequiresOneOfKeySetGroups<T, Groups> = Groups extends readonly [\n infer Group extends readonly (readonly string[])[],\n ...infer Rest extends readonly (readonly (readonly string[])[])[],\n]\n ? ApplyRequiresOneOfKeySetGroups<RequireOneKeySet<T, Group>, Rest>\n : Groups extends readonly (infer Group extends\n readonly (readonly string[])[])[]\n ? [Group] extends [never]\n ? T\n : RequireEveryKeySetGroup<T, Group>\n : T;\n\n/**\n * Apply wrapper options (optional, nullable, array) to input type.\n * Input accepts undefined when optional (even with default).\n */\ntype ApplyObjectOptionsInput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Apply wrapper options (optional, nullable, array) to output type.\n * When a default is provided, undefined is not included in output\n * (the default will always be applied).\n */\ntype ApplyObjectOptionsOutput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase | null\n : TBase\n : TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Object schema interface.\n */\nexport interface ObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n TInput = ApplyObjectOptionsInput<ComputeObjectInput<TEntries, TOpts>, TOpts>,\n TOutput = ApplyObjectOptionsOutput<\n ComputeObjectOutput<TEntries, TOpts>,\n TOpts\n >,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"object\";\n readonly entries: TEntries;\n readonly options: TOpts;\n readonly parse: VibSchema<TInput, TOutput>[\"~standard\"][\"validate\"];\n /** Extend this schema with additional entries */\n extend<\n TNewEntries extends ObjectEntries,\n TNewTOpts extends ObjectOptions | undefined = undefined,\n >(\n newEntries: TNewEntries,\n options?: TNewTOpts\n ): ObjectSchema<TEntries & TNewEntries, TOpts & TNewTOpts>;\n}\n\n/** An object schema whose parser omits keys from both its input and output. */\nexport type OmittedObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined,\n TKeys extends readonly PropertyKey[] | undefined,\n> = ObjectSchema<\n TEntries,\n TOpts,\n ApplyObjectOptionsInput<ComputeObjectInput<TEntries, TOpts>, TOpts>,\n ApplyObjectOptionsOutput<\n VOmit<InferOutputShape<TEntries>, OmittedKeyUnion<TKeys>>,\n TOpts\n >\n>;\n\n// =============================================================================\n// Object Schema Implementation\n// =============================================================================\n\n// Pre-computed error for fast path (frozen — shared across all callers)\nconst OBJECT_TYPE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected object\" })]),\n});\n\nconst EMPTY: readonly never[] = Object.freeze([]);\nconst EMPTY_MAP: ReadonlyMap<string, number> = Object.freeze(new Map());\nconst UNREAD = Symbol(\"unread\");\n\nfunction createObjectValidator(\n entries: ObjectEntries,\n options: ObjectOptions = {}\n): (value: unknown) => ValidationResult<Record<string, unknown>> {\n const {\n partial = true,\n strict = true,\n atLeast,\n requiresOneOf,\n requiresOneOfKeySets,\n omit,\n nonEmpty,\n refuse,\n provides,\n } = options;\n let keys: readonly string[] = EMPTY;\n let keyIndex = EMPTY_MAP;\n let validates: readonly ((value: unknown) => any)[] = EMPTY;\n let activeOneOf: ObjectOptions[\"requiresOneOf\"];\n let activeKeySets: ObjectOptions[\"requiresOneOfKeySets\"];\n let runOnMissingIdx: readonly number[] = EMPTY;\n let acceptsUndefined: readonly boolean[] = EMPTY;\n let requiredByAtLeast: readonly boolean[] | null = null;\n let scratchTemplate: readonly unknown[] | undefined;\n let scratchIdx: ReadonlyMap<string, number> | undefined;\n\n let resolve: (() => void) | undefined = () => {\n resolve = undefined;\n const omitSet = omit ? new Set(omit) : null;\n const ks = Object.keys(entries).filter((k) => !omitSet?.has(k));\n const atLeastSet = atLeast ? new Set(atLeast) : null;\n const ki = new Map<string, number>();\n const vs: ((value: unknown) => any)[] = new Array(ks.length);\n const fullPartial = partial && !atLeastSet;\n const oneOf = requiresOneOf?.filter((g) => !g.some((k) => omitSet?.has(k)));\n const keySets = requiresOneOfKeySets?.filter(\n (g) => !g.some((s) => s.some((k) => omitSet?.has(k)))\n );\n const missingIdx: number[] | undefined = fullPartial ? [] : undefined;\n const accUndef: boolean[] | undefined = fullPartial\n ? undefined\n : new Array(ks.length);\n\n keys = ks;\n keyIndex = ki;\n validates = vs;\n activeOneOf = oneOf;\n activeKeySets = keySets;\n runOnMissingIdx = missingIdx ?? EMPTY;\n acceptsUndefined = accUndef ?? EMPTY;\n requiredByAtLeast =\n !fullPartial && partial && atLeastSet\n ? ks.map((k) => atLeastSet.has(k))\n : null;\n\n for (let i = 0; i < ks.length; i++) {\n const k = ks[i]!;\n ki.set(k, i);\n const entry = entries[k]!;\n const schema = isFunction(entry)\n ? (entry as () => VibSchema<any, any>)()\n : entry;\n vs[i] = schema[\"~standard\"].validate;\n const au =\n (schema as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n if (missingIdx) {\n if (au && !absentStaysAbsent(schema)) missingIdx.push(i);\n } else {\n accUndef![i] = au;\n }\n }\n\n const si = new Map<string, number>();\n const reg = (k: string) => {\n if (!si.has(k)) si.set(k, si.size);\n };\n for (const g of oneOf ?? EMPTY) for (const k of g) reg(k);\n for (const g of keySets ?? EMPTY)\n for (const s of g) for (const k of s) reg(k);\n for (const i of runOnMissingIdx) reg(ks[i]!);\n if (si.size > 0) {\n scratchTemplate = new Array(si.size).fill(UNREAD);\n scratchIdx = si;\n }\n };\n\n type Result = ValidationResult<Record<string, unknown>>;\n\n const readInput = (\n input: Record<string, unknown>,\n key: string,\n scratch: unknown[] | undefined\n ): unknown => {\n const i = scratch ? scratchIdx!.get(key) : undefined;\n if (i === undefined) return input[key];\n const s = scratch![i];\n return s !== UNREAD ? s : (scratch![i] = input[key]);\n };\n\n const checkRequirements =\n nonEmpty === true || requiresOneOf || requiresOneOfKeySets\n ? (\n input: Record<string, unknown>,\n scratch: unknown[] | undefined\n ): ValidationIssue[] | undefined => {\n if (nonEmpty === true) {\n let any = false;\n for (const _ in input) {\n any = true;\n break;\n }\n if (!any) return [{ message: \"Object cannot be empty\" }];\n }\n for (const g of activeOneOf ?? EMPTY) {\n if (!g.some((k) => readInput(input, k, scratch) !== undefined))\n return [\n { message: `Missing required field: one of ${g.join(\", \")}` },\n ];\n }\n for (const g of activeKeySets ?? EMPTY) {\n if (\n !g.some((ks) =>\n ks.every(\n (k) =>\n readInput(input, k, scratch) !== undefined ||\n isProvided(provides, k)\n )\n )\n )\n return [\n {\n message: `Missing required fields: one of ${g.map((ks) => ks.join(\", \")).join(\" or \")}`,\n },\n ];\n }\n return undefined;\n }\n : undefined;\n\n const precheck = (\n input: Record<string, unknown>,\n scratch: unknown[] | undefined\n ): ValidationIssue[] | undefined => {\n const issues = strict\n ? unknownKeyIssues(input, keyIndex, provides)\n : undefined;\n if (issues && !collectingAllIssues()) return issues;\n const unmet = checkRequirements?.(input, scratch);\n return unmet ? gathered(issues, unmet) : issues;\n };\n\n const settle = (\n issues: ValidationIssue[] | undefined,\n output: Record<string, unknown>\n ): Result => {\n if (issues) return { issues };\n const r = refuse?.(output);\n return r\n ? { issues: [typeof r === \"string\" ? { message: r } : r] }\n : { value: output };\n };\n\n const failFirst = (\n input: Record<string, unknown>,\n found: ValidationIssue[]\n ): Result => ({\n issues:\n (strict ? unknownKeyIssues(input, keyIndex, provides) : undefined) ??\n found,\n });\n\n if (partial && !atLeast) {\n return (value: unknown): Result => {\n if (!isRecord(value)) return OBJECT_TYPE_ERROR as Result;\n const input = value as Record<string, unknown>;\n resolve?.();\n const scratch = scratchTemplate?.slice();\n const collectAll = collectingAllIssues();\n let issues = collectAll\n ? precheck(input, scratch)\n : checkRequirements?.(input, scratch);\n if (issues && !collectAll) return failFirst(input, issues);\n const output: Record<string, unknown> = {};\n for (const key in input) {\n const i = keyIndex.get(key);\n const validate = i === undefined ? added(provides, key) : validates[i];\n if (validate === undefined) {\n if (strict && !collectAll) return { issues: [unknownKey(key)] };\n continue;\n }\n const inputValue = readInput(input, key, scratch);\n if (inputValue === undefined) continue;\n const result = validate(inputValue);\n if (result.issues) {\n const sub = issuesUnder(key, result.issues);\n if (!collectAll) return failFirst(input, sub);\n issues = gathered(issues, sub);\n continue;\n }\n if (result.value !== undefined) output[key] = result.value;\n }\n for (const i of runOnMissingIdx) {\n const key = keys[i]!;\n if (readInput(input, key, scratch) !== undefined) continue;\n const result = validates[i]!(undefined);\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectAll) return { issues };\n continue;\n }\n if (result.value !== undefined) output[key] = result.value;\n }\n return settle(issues, output);\n };\n }\n\n return (value: unknown): Result => {\n if (!isRecord(value)) return OBJECT_TYPE_ERROR as Result;\n const input = value as Record<string, unknown>;\n resolve?.();\n const scratch = scratchTemplate?.slice();\n const collectAll = collectingAllIssues();\n let issues = precheck(input, scratch);\n if (issues && !collectAll) return { issues };\n const output: Record<string, unknown> = {};\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n const inputValue = readInput(input, key, scratch);\n if (inputValue === undefined) {\n if (isProvided(provides, key)) {\n output[key] = undefined;\n continue;\n }\n if (\n (!partial || requiredByAtLeast?.[i] === true) &&\n !acceptsUndefined[i]\n ) {\n issues = gathered(issues, [\n { message: `Missing required field: ${key}`, path: [key] },\n ]);\n if (!collectAll) return { issues };\n continue;\n }\n if (!acceptsUndefined[i]) {\n output[key] = undefined;\n continue;\n }\n }\n const result = validates[i]!(inputValue);\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectAll) return { issues };\n continue;\n }\n output[key] = result.value;\n }\n return settle(issues, output);\n };\n}\n\n/**\n * Does `schema` answer an absent value with `undefined` and nothing else? The\n * validator of a `v.optional` without a default does (`optional.ts`; a schema\n * that replaced it is asked as before), and a fully partial object leaves out\n * a member whose value is `undefined`, so such a member need not run when its\n * key is absent. Every relation node declares one (`recurse`), and a `where`\n * one per field: running them was 15 % of a three-level include's validation\n * and 30 % of a one-field `where`'s (2026-11-16).\n */\nfunction absentStaysAbsent(schema: VibSchema<any, any>): boolean {\n return answersAbsentWithUndefined(schema[\"~standard\"].validate);\n}\n\n/** `found` after the issues a parse has already gathered, if any. */\nfunction gathered(\n issues: ValidationIssue[] | undefined,\n found: ValidationIssue[]\n): ValidationIssue[] {\n if (!issues) return found;\n issues.push(...found);\n return issues;\n}\n\nconst unknownKey = (key: string): ValidationIssue => ({\n message: `Unknown key: ${key}`,\n path: [key],\n});\n\n/** The unknown keys of a strict object: the first, or every one when collecting. */\nfunction unknownKeyIssues(\n input: Record<string, unknown>,\n keyIndex: ReadonlyMap<string, number>,\n provides: string | undefined\n): ValidationIssue[] | undefined {\n let issues: ValidationIssue[] | undefined;\n for (const key in input) {\n if (keyIndex.has(key) || added(provides, key)) continue;\n (issues ??= []).push(unknownKey(key));\n if (!collectingAllIssues()) break;\n }\n return issues;\n}\n\n/**\n * Create an object schema.\n *\n * IMPORTANT: No constraint on TEntries to allow circular reference resolution.\n * The identity conditional (R extends infer _ ? _ : never) defers type evaluation.\n *\n * @param entries - Object schema entries\n * @param options - Schema options\n * - `strict` (default: true) - Reject unknown keys\n * - `partial` (default: true) - Make all fields optional\n * - `optional` - Allow undefined\n * - `nullable` - Allow null\n * - `array` - Validate as array of objects\n * - `default` - Default value\n * - `transform` - Transform output\n *\n * @example\n * // Basic object (strict by default)\n * const user = v.object({\n * name: v.string(),\n * age: v.number(),\n * });\n *\n * // Circular references\n * const node = v.object({\n * value: v.string(),\n * child: () => node, // Thunk\n * });\n */\nexport function object<TEntries>(\n entries: TEntries\n): ObjectSchema<TEntries, undefined>;\nexport function object<TEntries, const TOpts extends ObjectOptions | undefined>(\n entries: TEntries,\n options?: TOpts\n): ObjectSchema<TEntries, TOpts>;\nexport function object<\n TEntries, // NO constraint - critical for circular references\n const TOpts extends ObjectOptions | undefined,\n R = ObjectSchema<TEntries, TOpts>,\n>(entries: TEntries, options?: TOpts): R extends infer _ ? _ : never {\n const {\n default: fallback,\n optional,\n nullable,\n array,\n transform,\n } = options ?? {};\n const parsed = createObjectValidator(entries as ObjectEntries, options);\n let validate = wrapped(\n transform ? withTransform(parsed, transform) : parsed,\n array,\n nullable,\n optional\n );\n // An object's default answers an absent optional value as it stands: it\n // does not cross the parser, and without `optional` it is never read.\n if (optional === true && fallback !== undefined) {\n const present = validate;\n const getDefault = isFunction(fallback) ? fallback : () => fallback;\n validate = (value) =>\n value === undefined ? ok(getDefault()) : present(value);\n }\n\n return Object.assign(createSchema(\"object\", validate), {\n entries,\n options,\n acceptsUndefined: optional === true || fallback !== undefined,\n extend: (newEntries: ObjectEntries) =>\n object({ ...entries, ...newEntries } as any, options),\n }) as R extends infer _ ? _ : never;\n}\n","/**\n * The one logical instant domain of a VibORM DateTime value.\n *\n * Four-digit ISO years are not only an input spelling. They bound every\n * public DateTime instant, including a `Date` input and a provider value read\n * back through a numeric physical representation.\n */\n\nexport const MIN_DATETIME_EPOCH_MILLISECONDS = -62_167_219_200_000;\nexport const MAX_DATETIME_EPOCH_MILLISECONDS = 253_402_300_799_999;\n\n/** Whether one number names a whole millisecond in the public DateTime domain. */\nexport function isDateTimeInstant(epochMilliseconds: number): boolean {\n return (\n Number.isInteger(epochMilliseconds) &&\n epochMilliseconds >= MIN_DATETIME_EPOCH_MILLISECONDS &&\n epochMilliseconds <= MAX_DATETIME_EPOCH_MILLISECONDS\n );\n}\n\n/** Whether three numeric components name one real proleptic-Gregorian date. */\nexport function isGregorianCalendarDate(\n year: number,\n month: number,\n day: number\n): boolean {\n const hasIntegerComponents =\n Number.isInteger(year) && Number.isInteger(month) && Number.isInteger(day);\n if (!hasIntegerComponents || month < 1 || month > 12 || day < 1) {\n return false;\n }\n let daysInMonth = 31;\n if (month === 2) {\n daysInMonth = isLeapYear(year) ? 29 : 28;\n } else if (month === 4 || month === 6 || month === 9 || month === 11) {\n daysInMonth = 30;\n }\n return day <= daysInMonth;\n}\n\n/** Whether three numeric components name one clock time without leap seconds. */\nexport function isDateTimeClock(\n hour: number,\n minute: number,\n second: number\n): boolean {\n return (\n Number.isInteger(hour) &&\n Number.isInteger(minute) &&\n Number.isInteger(second) &&\n hour >= 0 &&\n hour <= 23 &&\n minute >= 0 &&\n minute <= 59 &&\n second >= 0 &&\n second <= 59\n );\n}\n\nfunction isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isNumber } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// Number Schema\n// =============================================================================\n\nexport interface BaseNumberSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface NumberSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"number\";\n}\n\n// Pre-computed error for fast path\nconst NUMBER_ERROR = /* @__PURE__ */ frozenFail(\"Expected finite number\");\n\n/**\n * Validate that a value is a finite number (rejects NaN and Infinity).\n */\nfunction validateNumber(value: unknown) {\n return isNumber(value) && Number.isFinite(value) ? ok(value) : NUMBER_ERROR;\n}\n\n/**\n * Create a number schema.\n *\n * @example\n * const age = v.number();\n * const optionalAge = v.number({ optional: true });\n * const scores = v.number({ array: true });\n */\nexport function number(): NumberSchema<number, number>;\nexport function number<const Opts extends ScalarOptions<number, any>>(\n options: Opts\n): NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\nexport function number<\n const Opts extends ScalarOptions<number, any> | undefined,\n>(\n options?: Opts\n): NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"number\", validateNumber, options) as NumberSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// =============================================================================\n// Integer Schema (number with integer constraint)\n// =============================================================================\n\nexport interface BaseIntegerSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface IntegerSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"integer\";\n}\n\n// Pre-computed error for fast path\nconst INTEGER_ERROR = /* @__PURE__ */ frozenFail(\"Expected integer\");\nconst UNSAFE_INTEGER_ERROR = /* @__PURE__ */ frozenFail(\n \"Expected safe integer\"\n);\n\n/**\n * Validate that a value is an integer.\n */\nfunction validateInteger(value: unknown) {\n if (!(isNumber(value) && Number.isInteger(value))) return INTEGER_ERROR;\n return Number.isSafeInteger(value) ? ok(value) : UNSAFE_INTEGER_ERROR;\n}\n\n/**\n * Create an integer schema.\n *\n * @example\n * const count = v.integer();\n */\nexport function integer(): IntegerSchema<number, number>;\nexport function integer<const Opts extends ScalarOptions<number, any>>(\n options: Opts\n): IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\nexport function integer<\n const Opts extends ScalarOptions<number, any> | undefined,\n>(\n options?: Opts\n): IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"integer\", validateInteger, options) as IntegerSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// Export validate functions for reuse\nexport { validateNumber, validateInteger };\n","import type { ValidationResult } from \"../types\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n GEO_POINT_KEYS,\n type GeoPoint,\n} from \"./geo-values\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { validateNumber } from \"./number\";\nimport { object } from \"./object\";\n\nexport type { GeoPoint } from \"./geo-values\";\n\n/**\n * One finite coordinate inside its inclusive range, with -0 read as 0: the\n * type VibORM returns has no -0, and points decode provider rows and cache\n * snapshots through this same schema.\n */\nfunction geoCoordinate(label: string, low: number, high: number) {\n return createSchema<number, number>(\"number\", (value) => {\n const coordinate = validateNumber(value);\n if (coordinate.issues) return coordinate;\n if (coordinate.value < low || coordinate.value > high) {\n return fail(`${label} must be between ${low} and ${high}`);\n }\n return ok(Object.is(coordinate.value, -0) ? 0 : coordinate.value);\n });\n}\n\nexport const geoLongitude = geoCoordinate(\n \"Longitude\",\n GEO_LONGITUDE_MIN,\n GEO_LONGITUDE_MAX\n);\nexport const geoLatitude = geoCoordinate(\n \"Latitude\",\n GEO_LATITUDE_MIN,\n GEO_LATITUDE_MAX\n);\n\nconst pointRecord = object(\n { [GEO_POINT_KEYS[0]]: geoLongitude, [GEO_POINT_KEYS[1]]: geoLatitude },\n { partial: false }\n);\n\n/** Validate the one public GeoPoint representation into a fresh record. */\nexport function validateGeoPoint(value: unknown): ValidationResult<GeoPoint> {\n const point = validateSchema(pointRecord, value);\n if (point.issues) return point;\n const { longitude, latitude } = point.value;\n // -180 and +180 are one meridian. The SQLite CHECK\n // (adapters/databases/sqlite/storage/geo-point.ts) refuses -180, and the coordinate\n // predicates in adapters/shared/geo-point.ts assume the +180 spelling.\n return ok({\n longitude: longitude === GEO_LONGITUDE_MIN ? GEO_LONGITUDE_MAX : longitude,\n latitude,\n });\n}\n","import { ClientInitializationError } from \"@errors\";\n\nconst VALID_SCHEMA_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nconst OBJECT_PROTOTYPE_PROPERTY_NAMES = new Set(\n Object.getOwnPropertyNames(Object.prototype)\n);\nexport const MAX_SCHEMA_IDENTIFIER_BYTES = 63;\n\nexport function isValidSchemaIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length <= MAX_SCHEMA_IDENTIFIER_BYTES &&\n VALID_SCHEMA_IDENTIFIER.test(value) &&\n !OBJECT_PROTOTYPE_PROPERTY_NAMES.has(value)\n );\n}\n\n// =============================================================================\n// DATABASE NAMESPACE — the public `namespace` option's one validation boundary\n// =============================================================================\n//\n// A namespace is the SQL qualification value for one driver's persistent\n// objects: a PostgreSQL schema, or the MySQL database position (which Vitess\n// reads as a keyspace qualifier). The grammar above is shared with model and\n// field names, so a namespace is deliberately narrower than every identifier\n// either server can represent; the renderer quotes it, so keywords are legal.\n\n/** The two dialect families that qualify persistent objects. */\nexport type NamespaceDialect = \"postgresql\" | \"mysql\";\n\n/**\n * PostgreSQL stores a schema name in `NAMEDATALEN - 1` = 63 bytes; MySQL admits\n * 64 characters for a database name. Under the ASCII grammar above, one\n * character is one byte, so both limits are measured in code units here.\n */\nconst NAMESPACE_LENGTH_LIMIT: Record<NamespaceDialect, number> = {\n postgresql: MAX_SCHEMA_IDENTIFIER_BYTES,\n mysql: 64,\n};\n\nconst NAMESPACE_DIALECT_LABEL: Record<NamespaceDialect, string> = {\n postgresql: \"PostgreSQL\",\n mysql: \"MySQL\",\n};\n\n/** Server-owned databases. MySQL database-name case folding varies by platform. */\nconst MYSQL_SYSTEM_DATABASES = new Set([\n \"information_schema\",\n \"mysql\",\n \"performance_schema\",\n \"sys\",\n \"ndbinfo\",\n]);\n\nfunction refuseNamespace(dialect: NamespaceDialect, reason: string): never {\n throw new ClientInitializationError(\n `The \"namespace\" option ${reason} (${NAMESPACE_DIALECT_LABEL[dialect]}).`\n );\n}\n\n/**\n * Normalize one caller-supplied namespace, or refuse it before any provider\n * work. Case is preserved: PostgreSQL quotes make `PG_CATALOG` a different\n * schema from `pg_catalog`, and MySQL keeps the supplied spelling.\n */\nexport function normalizeNamespace(\n value: unknown,\n dialect: NamespaceDialect\n): string {\n if (typeof value !== \"string\")\n refuseNamespace(dialect, `must be a string (got \"${typeof value}\")`);\n const limit = NAMESPACE_LENGTH_LIMIT[dialect];\n if (value.length > limit)\n refuseNamespace(dialect, `exceeds ${limit} chars (${value.length})`);\n if (!VALID_SCHEMA_IDENTIFIER.test(value))\n refuseNamespace(dialect, `invalid identifier ${JSON.stringify(value)}`);\n if (OBJECT_PROTOTYPE_PROPERTY_NAMES.has(value))\n refuseNamespace(\n dialect,\n `cannot be Object.prototype key ${JSON.stringify(value)}`\n );\n if (dialect === \"postgresql\") {\n if (value === \"information_schema\" || value.startsWith(\"pg_\"))\n refuseNamespace(\n dialect,\n `cannot be system schema ${JSON.stringify(value)}`\n );\n return value;\n }\n if (MYSQL_SYSTEM_DATABASES.has(value.toLowerCase()))\n refuseNamespace(\n dialect,\n `cannot be system database ${JSON.stringify(value)}`\n );\n return value;\n}\n","// Native Database Type Overrides\n// Provides typed constants for database-specific column types\n\n// =============================================================================\n// NATIVE TYPE INTERFACE\n// =============================================================================\n\nexport interface NativeType {\n readonly db: \"pg\" | \"mysql\" | \"sqlite\";\n readonly type: string;\n}\n\n/** The three dialects a native type can name. */\nexport type NativeDialect = NativeType[\"db\"];\n\n/**\n * A native type of ONE dialect — what every `PG` / `MYSQL` / `SQLITE` constant\n * is, parameterized ones included, so `PG.STRING.VARCHAR(80)` can fill a `pg`\n * entry of a {@link NativeTypeMap} and cannot fill a `mysql` one.\n */\nexport interface DialectNativeType<Dialect extends NativeDialect>\n extends NativeType {\n readonly db: Dialect;\n}\n\n/**\n * One scalar's native type on each dialect it names:\n * `s.string({ pg: PG.STRING.CITEXT, mysql: MYSQL.STRING.LONGTEXT })`.\n *\n * A dialect the map leaves out keeps that scalar's automatic column, exactly\n * as a tagged {@link NativeType} leaves every OTHER dialect's column alone.\n */\nexport interface NativeTypeMap {\n readonly pg?: DialectNativeType<\"pg\">;\n readonly mysql?: DialectNativeType<\"mysql\">;\n readonly sqlite?: DialectNativeType<\"sqlite\">;\n}\n\n/**\n * What a scalar factory's native-type argument declares: the tagged shorthand\n * (one dialect) or a {@link NativeTypeMap} (several). Scalars store the\n * declaration in the form it was written, so a schema document restates it\n * faithfully; every PHYSICAL reader asks {@link nativeTypeFor} instead of\n * inspecting the form.\n */\nexport type NativeTypeDeclaration = NativeType | NativeTypeMap;\n\n/** Every dialect, in the order a per-dialect question visits them. */\nexport const NATIVE_DIALECTS: readonly NativeDialect[] = [\n \"pg\",\n \"mysql\",\n \"sqlite\",\n];\n\n/** Whether a declaration is the tagged shorthand rather than a map. */\nexport const isTaggedNativeType = (\n declaration: NativeTypeDeclaration\n): declaration is NativeType => \"db\" in declaration;\n\n/**\n * The native type a declaration selects on one dialect, or `undefined` for the\n * dialect's automatic column.\n *\n * The ONE bound-dialect resolver. A migration driver, an adapter and the\n * identifier storage owner each know which dialect they speak and ask this;\n * none of them reads the declaration's form. A tagged shorthand for another\n * dialect is that dialect's automatic column, as it always was.\n */\nexport function nativeTypeFor(\n declaration: NativeTypeDeclaration | undefined,\n dialect: NativeDialect\n): NativeType | undefined {\n if (declaration === undefined) return undefined;\n if (isTaggedNativeType(declaration)) {\n return declaration.db === dialect ? declaration : undefined;\n }\n return declaration[dialect];\n}\n\n/**\n * A scalar factory's native-type argument: the tagged shorthand of dialect\n * `Db`, or the map `Given`, which the factory bounds by\n * {@link ExactNativeTypeMap}.\n *\n * The tagged shorthand keeps its historical shape: a `NativeType`, a union of\n * them, a generic `T extends NativeType`, a custom `type`, or one with unrelated\n * extra keys held in a variable all still compile, a fresh literal with an extra\n * key is still an excess-property error, and a value missing `db` or `type` is\n * still refused — except that a dialect key BESIDE its `db` is refused, since\n * that object would be two declarations at once.\n *\n * `Db` is inferred from a tagged value's `db` only so that TypeScript counts the\n * value as matched by this first member and keeps it out of `Given`: an\n * argument reaches `Given` only when it is not tagged, and `Given` is naked so\n * a union-typed argument (`NativeType | NativeTypeMap`) reaches it whole.\n */\nexport type NativeTypeArgument<Db extends NativeDialect, Given> =\n | (DialectNativeType<Db> & Partial<Record<NativeDialect, never>>)\n | Given;\n\n/**\n * The bound of a factory's `Given`: every key a dialect, each entry a native\n * type of its own key's dialect, and at least one dialect key. `{ type: \"text\" }`,\n * `{ postgres: … }`, `{}` and a `Date` are refused; an unknown key is refused\n * beside a real one, fresh and held in a variable. An argument that fails the\n * bound is refused against the bound itself, which is TypeScript's fallback.\n *\n * The exactness is a homomorphic mapped type, so it judges each member of a\n * union-typed map on its own. Measured traps (TS 7.0.2) that shaped it: a\n * generic CONSTRAINED to the weak `NativeTypeMap` falls back to that weak type\n * and admitted `{ foo: 1 }` and a `Date`; a parameter spelled `Given & NoInfer<…>`\n * makes TypeScript infer one member of a union argument; and a bound that is a\n * conditional type distributing over `Given` is a circular constraint (TS2313).\n * The at-least-one test is therefore not distributive: a union of maps with no\n * dialect key in COMMON is refused — annotate such a variable `NativeTypeMap`.\n */\nexport type ExactNativeTypeMap<Given> = {\n [Key in keyof Given]: Key extends NativeDialect\n ? DialectNativeType<Key>\n : never;\n} & ([keyof Given & NativeDialect] extends [never] ? never : unknown);\n\n// =============================================================================\n// CONSTANT BUILDERS\n// =============================================================================\n\n/** A fixed native type: its `db` and `type` keep their literal types. */\nconst fixed =\n <const Db extends NativeDialect>(db: Db) =>\n <const Type extends string>(type: Type) =>\n ({ db, type }) as const;\n\n/** A type that takes one required size: `varchar(80)`. */\nconst sized =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (n: number): DialectNativeType<Db> => ({ db, type: `${name}(${n})` });\n\n/** A type whose precision is optional: `timestamp` or `timestamp(3)`. */\nconst opt =\n <Db extends NativeDialect>(db: Db, name: string) =>\n (precision?: number): DialectNativeType<Db> => ({\n db,\n type: precision !== undefined ? `${name}(${precision})` : name,\n });\n\n// =============================================================================\n// POSTGRESQL NATIVE TYPES\n// =============================================================================\n\nconst makePg = () => {\n const p = fixed(\"pg\");\n const sz = (n: string) => sized(\"pg\", n);\n const op = (n: string) => opt(\"pg\", n);\n return {\n STRING: {\n TEXT: p(\"text\"),\n VARCHAR: sz(\"varchar\"),\n CHAR: sz(\"char\"),\n CITEXT: p(\"citext\"),\n UUID: p(\"uuid\"),\n BIT: sz(\"bit\"),\n VARBIT: (n?: number): DialectNativeType<\"pg\"> => ({\n db: \"pg\",\n type: n ? `varbit(${n})` : \"varbit\",\n }),\n XML: p(\"xml\"),\n INET: p(\"inet\"),\n CIDR: p(\"cidr\"),\n MACADDR: p(\"macaddr\"),\n MACADDR8: p(\"macaddr8\"),\n TSVECTOR: p(\"tsvector\"),\n TSQUERY: p(\"tsquery\"),\n },\n INT: { SMALLINT: p(\"smallint\"), INTEGER: p(\"integer\"), OID: p(\"oid\") },\n BIGINT: { BIGINT: p(\"bigint\") },\n FLOAT: { REAL: p(\"real\"), DOUBLE_PRECISION: p(\"double precision\") },\n BOOLEAN: { BOOLEAN: p(\"boolean\") },\n DATETIME: {\n TIMESTAMP: op(\"timestamp\"),\n TIMESTAMPTZ: op(\"timestamptz\"),\n DATE: p(\"date\"),\n TIME: op(\"time\"),\n TIMETZ: op(\"timetz\"),\n },\n JSON: { JSON: p(\"json\"), JSONB: p(\"jsonb\") },\n BLOB: { BYTEA: p(\"bytea\") },\n } as const;\n};\n\nexport const PG = /*#__PURE__*/ makePg();\n\n// =============================================================================\n// MYSQL NATIVE TYPES\n// =============================================================================\n\nconst makeMysql = () => {\n const m = fixed(\"mysql\");\n const sz = (n: string) => sized(\"mysql\", n);\n const op = (n: string) => opt(\"mysql\", n);\n return {\n STRING: {\n VARCHAR: sz(\"VARCHAR\"),\n CHAR: sz(\"CHAR\"),\n TEXT: m(\"TEXT\"),\n TINYTEXT: m(\"TINYTEXT\"),\n MEDIUMTEXT: m(\"MEDIUMTEXT\"),\n LONGTEXT: m(\"LONGTEXT\"),\n BIT: sz(\"BIT\"),\n },\n INT: {\n TINYINT: m(\"TINYINT\"),\n TINYINT_UNSIGNED: m(\"TINYINT UNSIGNED\"),\n SMALLINT: m(\"SMALLINT\"),\n SMALLINT_UNSIGNED: m(\"SMALLINT UNSIGNED\"),\n MEDIUMINT: m(\"MEDIUMINT\"),\n MEDIUMINT_UNSIGNED: m(\"MEDIUMINT UNSIGNED\"),\n INT: m(\"INT\"),\n INT_UNSIGNED: m(\"INT UNSIGNED\"),\n YEAR: m(\"YEAR\"),\n },\n BIGINT: { BIGINT: m(\"BIGINT\"), BIGINT_UNSIGNED: m(\"BIGINT UNSIGNED\") },\n FLOAT: { FLOAT: m(\"FLOAT\"), DOUBLE: m(\"DOUBLE\") },\n BOOLEAN: { TINYINT: m(\"TINYINT(1)\") },\n DATETIME: {\n DATETIME: op(\"DATETIME\"),\n TIMESTAMP: op(\"TIMESTAMP\"),\n DATE: m(\"DATE\"),\n TIME: op(\"TIME\"),\n },\n JSON: { JSON: m(\"JSON\") },\n BLOB: {\n BLOB: m(\"BLOB\"),\n TINYBLOB: m(\"TINYBLOB\"),\n MEDIUMBLOB: m(\"MEDIUMBLOB\"),\n LONGBLOB: m(\"LONGBLOB\"),\n BINARY: sz(\"BINARY\"),\n VARBINARY: sz(\"VARBINARY\"),\n },\n } as const;\n};\n\nexport const MYSQL = /*#__PURE__*/ makeMysql();\n\n// =============================================================================\n// SQLITE NATIVE TYPES\n// =============================================================================\n\nconst makeSqlite = () => {\n const sq = fixed(\"sqlite\");\n return {\n STRING: { TEXT: sq(\"TEXT\") },\n INT: { INTEGER: sq(\"INTEGER\") },\n BIGINT: { INTEGER: sq(\"INTEGER\") },\n FLOAT: { REAL: sq(\"REAL\") },\n BOOLEAN: { INTEGER: sq(\"INTEGER\") },\n DATETIME: { TEXT: sq(\"TEXT\"), REAL: sq(\"REAL\"), INTEGER: sq(\"INTEGER\") },\n JSON: { TEXT: sq(\"TEXT\") },\n BLOB: { BLOB: sq(\"BLOB\") },\n } as const;\n};\n\nexport const SQLITE = /*#__PURE__*/ makeSqlite();\n"],"mappings":"6KAuBA,MAAM,EAA+B,EACnC,uCACD,CAOY,EAAsB,cAC7B,EAAc,IAAI,OAAO,EAAoB,CAKnD,SAAS,EAAe,EAAgB,CAEtC,OADI,EAAS,EAAM,CAAS,EAAG,EAAM,CAC9B,OAAO,GAAU,UAAY,EAAY,KAAK,EAAM,CACvD,EAAG,OAAO,EAAM,CAAC,CACjB,EAcN,SAAgB,EAGd,EACuE,CACvE,OAAO,EAAY,SAAU,EAAgB,EAAQ,CCxDvD,MAAa,EAAiB,CAAC,YAAa,WAAW,CAC1C,EAAoB,KACpB,EAAoB,IACpB,EAAmB,IACnB,EAAmB,GACnB,EAAkB,CAAC,QAAS,OAAQ,QAAS,OAAO,CACpD,EAA8B,ECOrC,GAAY,wBACZ,EACJ,mEACI,EAAkB,wBAaxB,SAAS,EAAS,EAA0B,CAC1C,GAAI,CAAC,GAAU,KAAK,EAAI,CAAE,MAAO,CAAE,YAAa,aAAc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CAAE,QAAS,EAAG,UAAU,CAAE,CACnC,SAAU,CAAE,KAAM,EAAG,OAAO,CAAE,KAAM,EAAG,OAAO,CAAE,QAAS,EAAG,UAAU,CAAE,CACxE,KAAM,CAAE,KAAM,EAAG,OAAO,CAAE,CAC1B,KAAM,CAAE,KAAM,EAAG,OAAO,CAAE,CAC3B,IAG6C"}
|
package/dist/neon-http.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $a as QueryExecutionContext, Di as LinkedClientConfig, Gr as Schema, Ja as TransactionOptionSupport, Ka as BatchTransactionOptions, Xa as BatchQuery, Za as CommittedBatchNotification, eo as QueryResult, h as Driver, pt as VibORMClient, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys } from "./database-adapter-BMjJiBFm.mjs";
|
|
2
2
|
import { NeonQueryFunction } from "@neondatabase/serverless";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/neon-http/index.d.ts
|
package/dist/neon-http.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{h as e}from"./error-mapping-B9rSvgG9.mjs";import{p as t,r as n}from"./validation-ATmgN5RE.mjs";import{i as r}from"./normalized-result-D7nVkF36.mjs";import{n as i}from"./client-D7sWgUt2.mjs";import{f as a,h as o,r as s,u as c,v as l}from"./driver-lShUkDmf.mjs";import{t as u}from"./postgres-result-133boRW-.mjs";import{t as d}from"./postgres-adapter-BpLizOaK.mjs";const f={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function p(e,n){let r=e.operation??`execute`;return new t(`Driver "neon-http" malformed result for "${r}": ${n}.`,{meta:{driver:`neon-http`,...e,operation:r}})}function m(e,t){if(!(r(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(r)||e.rowAsArray!==!1)throw p(t,`expected fullResults with object rows and rowCount`)}var h=class extends s{static get name(){return`NeonHTTPDriver`}maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;eg;kd;constructor(e={}){super(`postgresql`,`neon-http`);let t=l(e);this.eg=e,d(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.eg.databaseUrl)throw new n(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let r=e=>e;return this.kd={getTypeParser:((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?r:t.getTypeParser(e,n))},e(this.eg.databaseUrl,{fetchOptions:this.eg.options?.fetchOptions,authToken:this.eg.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.pw(e,t,n,r,`execute`)}async pw(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.kd});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.pw(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP batch has no interactive body`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP batch has no connection wait`}}transaction(t,n){return Promise.reject(e(this.driverName))}async executeBatch(e,t,n,r,i){let o=n??{operation:`executeBatch`},s=await e.transaction(t.map(t=>{let n=t.context??o;try{return e.query(t.sql,t.params??[],{types:this.kd})}catch(e){throw a(this,e,t.sql,c(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(s)||s.length!==t.length){let e=Array.isArray(s)?s.length:0;throw p(o,`expected ${t.length} statement results but received ${e}`)}return s.map((e,n)=>this.parseResult(e,t[n]?.context??o))}parseResult(e,t){let n=t.operation??`execute`;return m(e,t),{rows:e.rows,rowCount:u(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function g(e){o(e,`neon-http`,f);let{databaseUrl:t,options:n,pgvector:r,postgis:a}=e,s=l(e);return i(e,new h({databaseUrl:t,options:n,pgvector:r,postgis:a,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:s}))}export{h as NeonHTTPDriver,g as createClient};
|
|
2
2
|
//# sourceMappingURL=neon-http.mjs.map
|