viborm 1.14.2 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
- package/dist/adapters.d.mts +15 -3
- package/dist/adapters.mjs +1 -1
- package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
- package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
- package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
- package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-CVCC-D1j.mjs +2 -0
- package/dist/client-CVCC-D1j.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
- package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
- package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
- package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
- package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
- package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
- package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
- package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
- package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
- package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
- package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
- package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
- package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +1 -1
- package/dist/error-mapping-DIRlrmDK.mjs +2 -0
- package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
- package/dist/every-BHEmfLOW.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
- package/dist/execution-context-VMQm-9CH.mjs +2 -0
- package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
- package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
- package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
- package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
- package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
- package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
- package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
- package/dist/identifiers-BTCfD5ic.mjs +2 -0
- package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
- package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
- package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
- package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
- package/dist/judge-words-DpwxOfre.mjs +2 -0
- package/dist/judge-words-DpwxOfre.mjs.map +1 -0
- package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
- package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
- package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
- package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
- package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
- package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
- package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
- package/dist/methods-part-DoTrY6b9.mjs +2 -0
- package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
- package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
- package/dist/named-statements-CMj1QEyw.mjs +2 -0
- package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
- package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
- package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
- package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
- package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
- package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
- package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +1 -1
- package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +27 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
- package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
- package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
- package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
- package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
- package/dist/postgres-result-CiS5OWp1.mjs +2 -0
- package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
- package/dist/postgres.d.mts +17 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
- package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
- package/dist/query-Cdy8E2jM.mjs +2 -0
- package/dist/query-Cdy8E2jM.mjs.map +1 -0
- package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
- package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
- package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
- package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
- package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
- package/dist/scalar-B9WizsvR.mjs +4 -0
- package/dist/scalar-B9WizsvR.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
- package/dist/schema-MB-pPNTO.mjs.map +1 -0
- package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
- package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
- package/dist/schema-introspection-wMVZowIF.mjs +6 -0
- package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-SuVxJjps.mjs +2 -0
- package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
- package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
- package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
- package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
- package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
- package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +1 -1
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
- package/dist/sql-BGjAsoBE.mjs +2 -0
- package/dist/sql-BGjAsoBE.mjs.map +1 -0
- package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
- package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
- package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
- package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
- package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
- package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
- package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
- package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
- package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
- package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
- package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
- package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
- package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
- package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
- package/dist/validation-D0LG854o.mjs +2 -0
- package/dist/validation-D0LG854o.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
- package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
- package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
- package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
- package/dist/version-B_ZLWzLW.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
- package/package.json +35 -35
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/version-CXGIA82S.mjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scalar-B9WizsvR.mjs","names":["parsed","values","model","state","result","value","admit","model","describe","v","refused","v","string","record","values","#state","#internal","state","map","#state","#internal","state","#withForeignKeyAction","#localFields","state","state","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames","model","state","#internal","map","catalogs","next","next","v","state"],"sources":["../src/validation/primitives/array.ts","../src/validation/primitives/blob.ts","../src/validation/primitives/boolean.ts","../src/validation/primitives/date.ts","../src/validation/primitives/decimal.ts","../src/validation/primitives/enum.ts","../src/validation/primitives/from-object.ts","../src/validation/primitives/iso.ts","../src/schema/field-ref.ts","../src/validation/primitives/json.ts","../src/schema/json-null.ts","../src/validation/primitives/json-null.ts","../src/validation/primitives/lazy.ts","../src/validation/primitives/literal.ts","../src/validation/primitives/nullable.ts","../src/validation/primitives/omit.ts","../src/validation/primitives/filter-depth.ts","../src/validation/primitives/parameter.ts","../src/validation/primitives/operand.ts","../src/validation/primitives/pipe.ts","../src/validation/primitives/point.ts","../src/validation/primitives/record.ts","../src/validation/primitives/refused.ts","../src/validation/primitives/transform.ts","../src/validation/primitives/shorthand.ts","../src/validation/primitives/union.ts","../src/validation/primitives/single-or-array.ts","../src/validation/primitives/string.ts","../src/validation/primitives/vector.ts","../src/validation/primitives/v.ts","../src/schema/record.ts","../src/schema/relation/terminal.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts","../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, validateArray } from \"./helpers\";\n\n// =============================================================================\n// Array Schema\n// =============================================================================\n\nexport interface ArraySchema<\n TItem extends VibSchema<any, any>,\n TInput = InferInput<TItem>[],\n TOutput = InferOutput<TItem>[],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"array\";\n readonly item: TItem;\n}\n\n/**\n * Create an array schema that validates each item.\n *\n * @example\n * const tags = v.array(v.string());\n * const scores = v.array(v.number());\n */\nexport function array<TItem extends VibSchema<any, any>>(\n item: TItem\n): ArraySchema<TItem> {\n // Cache the validate function directly\n const validate = item[\"~standard\"].validate;\n\n const schema = createSchema<InferInput<TItem>[], InferOutput<TItem>[]>(\n \"array\",\n (value) => validateArray(value, validate)\n ) as ArraySchema<TItem>;\n\n (schema as any).item = item;\n\n return schema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isUint8Array } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Blob Schema (Uint8Array, including Node Buffer subclasses)\n// =============================================================================\n\nexport interface BaseBlobSchema<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n > {}\n\nexport interface BlobSchema<TInput = Uint8Array, TOutput = Uint8Array>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"blob\";\n}\n\n// Pre-computed error for fast path\nconst BLOB_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Uint8Array\" })]),\n});\n\n// %TypedArray%.prototype owns the metadata accessors. Start lookup there so a\n// genuine foreign view cannot redirect normalization through hostile own\n// properties.\nconst typedArrayPrototype: object = Object.getPrototypeOf(Uint8Array.prototype);\n\nfunction localBufferPrototype(): object | undefined {\n try {\n const bufferConstructor: unknown = Reflect.get(globalThis, \"Buffer\");\n if (typeof bufferConstructor !== \"function\") return;\n const prototype: unknown = Reflect.get(bufferConstructor, \"prototype\");\n if (\n prototype !== null &&\n typeof prototype === \"object\" &&\n Object.getPrototypeOf(prototype) === Uint8Array.prototype\n ) {\n return prototype;\n }\n } catch {\n return;\n }\n}\n\nconst trustedBufferPrototype = localBufferPrototype();\n\nfunction hasOwnViewMetadata(value: Uint8Array): boolean {\n return (\n Object.getOwnPropertyDescriptor(value, \"buffer\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteOffset\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteLength\") !== undefined\n );\n}\n\nfunction hasTrustedLocalPrototype(value: Uint8Array): boolean {\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Uint8Array.prototype ||\n prototype === trustedBufferPrototype) &&\n !hasOwnViewMetadata(value)\n );\n}\n\n/**\n * Validate binary data without requiring a Node Buffer global. Node Buffers\n * inherit from Uint8Array and therefore pass this same runtime check.\n */\nexport function validateBlob(value: unknown) {\n try {\n if (!isUint8Array(value)) return BLOB_ERROR;\n\n // Read the internal view through %TypedArray%.prototype. This proves the\n // slots without `instanceof` or caller-visible metadata and bypasses\n // hostile own properties on a genuine local or foreign Uint8Array.\n const buffer: ArrayBufferLike = Reflect.get(\n typedArrayPrototype,\n \"buffer\",\n value\n );\n const byteOffset: number = Reflect.get(\n typedArrayPrototype,\n \"byteOffset\",\n value\n );\n const byteLength: number = Reflect.get(\n typedArrayPrototype,\n \"byteLength\",\n value\n );\n // Only the two exact local prototype paths may retain identity. An\n // intermediate/custom prototype can be a stateful Proxy that agrees with\n // one metadata read and lies to the driver later, so it is never treated as\n // proof. Construct after classification so a detached backing buffer is a\n // refusal rather than a successful detached value.\n const keepsIdentity = hasTrustedLocalPrototype(value);\n const normalized = new Uint8Array(buffer, byteOffset, byteLength);\n // Keep the established plain-local/Node-Buffer identity contract only on\n // the exact trusted path. Every other admitted view normalizes locally.\n if (keepsIdentity) {\n return ok(value);\n }\n return ok(normalized);\n } catch {\n return BLOB_ERROR;\n }\n}\n\n/**\n * Create a blob schema for binary data.\n *\n * @example\n * const avatar = v.blob();\n * const optionalBlob = v.blob({ optional: true });\n * const nullableBlob = v.blob({ nullable: true });\n */\nexport function blob<\n const Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n>(\n options?: Opts\n): BlobSchema<ComputeInput<Uint8Array, Opts>, ComputeOutput<Uint8Array, Opts>> {\n return buildSchema(\"blob\", validateBlob, options) as BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isBoolean } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Boolean Schema\n// =============================================================================\n\nexport interface BaseBooleanSchema<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n > {}\n\nexport interface BooleanSchema<TInput = boolean, TOutput = boolean>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"boolean\";\n}\n\n// Pre-computed error for fast path\nconst BOOLEAN_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected boolean\" })]),\n});\n\n/**\n * Validate that a value is a boolean.\n */\nfunction validateBoolean(value: unknown) {\n return isBoolean(value) ? ok(value) : BOOLEAN_ERROR;\n}\n\n/**\n * Create a boolean schema.\n *\n * @example\n * const active = v.boolean();\n * const optionalFlag = v.boolean({ optional: true });\n */\nexport function boolean(): BooleanSchema<boolean, boolean>;\nexport function boolean<const Opts extends ScalarOptions<boolean, any>>(\n options: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\nexport function boolean<\n const Opts extends ScalarOptions<boolean, any> | undefined,\n>(\n options?: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>> {\n return buildSchema(\"boolean\", validateBoolean, options) as BooleanSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBoolean };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Date Schema (JavaScript Date objects)\n// =============================================================================\n\nexport interface DateSchema<TInput = Date, TOutput = Date>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"date\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Date\" })]),\n});\nconst INVALID_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected valid Date\" })]),\n});\n\n/**\n * Validate that a value is a JavaScript Date object.\n */\nfunction validateDate(value: unknown) {\n if (!isDate(value)) return NOT_DATE_ERROR;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) return INVALID_DATE_ERROR;\n if (value instanceof Date) return ok(value);\n // A Date from another realm names this exact instant but fails every local\n // `instanceof` downstream; a local Date at the same instant does not.\n return ok(new Date(time));\n}\n\n/**\n * Create a date schema for JavaScript Date objects.\n *\n * @example\n * const createdAt = v.date();\n * const optionalDate = v.date({ optional: true });\n */\nexport function date<\n const Opts extends ScalarOptions<Date, any> | undefined = undefined,\n>(\n options?: Opts\n): DateSchema<ComputeInput<Date, Opts>, ComputeOutput<Date, Opts>> {\n return buildSchema(\"date\", validateDate, options) as DateSchema<\n ComputeInput<Date, Opts>,\n ComputeOutput<Date, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateDate };\n","import { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationFailure,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { type DecimalDescriptor, toDecimal } from \"./decimal-codec\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n DECIMAL_INPUT_REFUSAL,\n type Decimal,\n domainRefusal,\n} from \"./decimal-value\";\nimport { buildSchema, fail, ok, standardSchemaFailure } from \"./helpers\";\n\n// =============================================================================\n// Decimal Schema\n// =============================================================================\n\n/**\n * What a decimal accepts on the way IN: the public value type, or its lossless\n * spelling. A JavaScript number is a double and is refused.\n */\nexport type DecimalInput = Decimal | string;\n\n/**\n * What a VALIDATED decimal is inside the engine: the canonical private string.\n *\n * This is not a public result mode. It is the one logical representation SQL\n * binding, cursors, row keys, cache keys, race pins, and link folds all key on,\n * because two distinct `Decimal` instances naming the same number must be the\n * same identity. The public `Decimal` is constructed once per selected value at\n * the typed result boundary, never here.\n */\nexport type DecimalOutput = string;\n\n/**\n * Decimal schema options: the ordinary scalar options plus the field's declared\n * fixed-decimal domain. The domain is optional at this level because the\n * primitive is also the unconstrained value grammar the codec is built on; the\n * PUBLIC surface, `s.decimal({ precision, scale })`, always declares one.\n */\nexport interface DecimalOptions<TSchemaOut = Decimal>\n extends ScalarOptions<Decimal, DecimalOutput, TSchemaOut> {\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * A custom `.schema()` REFINES the Decimal the base already built; it does not\n * redefine what the field accepts or what the pipeline emits. So neither\n * computed side may take its types from the schema the way every other scalar's\n * does: input stays `Decimal | string`, output stays canonical text.\n */\ntype DecimalValueOptions<Opts> =\n Opts extends ScalarOptions<any, any, any>\n ? Omit<Opts, \"schema\"> & { schema?: undefined }\n : undefined;\n\ntype ReadonlyDecimalList<T> = T extends DecimalInput[]\n ? readonly DecimalInput[]\n : T;\n\nexport type DecimalComputeInput<Opts> = ReadonlyDecimalList<\n ComputeInput<DecimalInput, DecimalValueOptions<Opts>>\n>;\n\nexport type DecimalComputeOutput<Opts> = ComputeOutput<\n DecimalOutput,\n DecimalValueOptions<Opts>\n>;\n\nexport interface DecimalSchema<TInput = DecimalInput, TOutput = DecimalOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"decimal\";\n readonly acceptsUndefined: boolean;\n readonly options:\n | { readonly decimal?: DecimalDescriptor | undefined }\n | undefined;\n}\n\n/** The FIELD boundary's refusal, in the value module's own words. */\nconst DECIMAL_ERROR: ValidationFailure = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: DECIMAL_INPUT_REFUSAL })]),\n});\n\nconst DECIMAL_VALUE_ERROR =\n \"Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type\";\n\n/**\n * Validate a decimal and NORMALIZE it to its canonical string in one step, so\n * everything downstream — binding, SQL comparison, identity, storage — sees one\n * spelling.\n */\nfunction validateDecimal(value: unknown): ValidationResult<string> {\n const canonical = admitDecimal(value);\n return canonical === undefined ? DECIMAL_ERROR : ok(canonical);\n}\n\n/**\n * The decimal's own validator chain, built HERE rather than composed by\n * `buildValidator`'s option handling, because the ORDER is the contract:\n *\n * base (exact grammar, canonical text)\n * -> the custom schema, which observes a real `Decimal` (plan 2.3)\n * -> the DESCRIPTOR, last, on whatever that schema returned\n *\n * `buildValidator` runs a custom schema after the base and has no hook after\n * it, and validation Rule 4 forbids patching one on afterwards: every decimal\n * filter and update schema is a union, and a union captures each member's\n * `~standard.validate` at construction. So the whole value chain exists before\n * the schema object does, and `buildValidator` is handed only the\n * nullable/optional/array/default wrapping it uniquely owns.\n */\nfunction buildDecimalValueValidator(\n options: DecimalOptions<any> | undefined\n): (value: unknown) => ValidationResult<string> {\n const custom = options?.schema;\n const descriptor = options?.decimal;\n let validate = validateDecimal;\n\n if (custom !== undefined) {\n const refine = custom[\"~standard\"].validate;\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refined = refine(toDecimal(parsed.value));\n if (\"then\" in refined) {\n discardAsyncValidationResult(refined);\n return fail(\"Async schemas are not supported\");\n }\n if (refined.issues) {\n return standardSchemaFailure(refined.issues);\n }\n // The return position admits only a Decimal: a string, a number or a\n // decimal-shaped object the constructor never built is a different\n // value family, so the brand reader alone answers here.\n const canonical = canonicalDecimalText(refined.value);\n return canonical === undefined\n ? fail(DECIMAL_VALUE_ERROR)\n : ok(canonical);\n };\n }\n\n if (descriptor !== undefined) {\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refusal = domainRefusal(\n parsed.value,\n descriptor.precision,\n descriptor.scale\n );\n return refusal === undefined ? parsed : fail(refusal);\n };\n }\n\n return validate;\n}\n\n/**\n * Create a decimal schema: exact decimal in, canonical decimal string out.\n *\n * @example\n * const price = v.decimal({ decimal: { precision: 10, scale: 2 } });\n * const optionalPrice = v.decimal({ optional: true });\n */\nexport function decimal(): DecimalSchema<DecimalInput, DecimalOutput>;\nexport function decimal<const Opts extends DecimalOptions<any>>(\n options: Opts\n): DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\nexport function decimal(options?: DecimalOptions<any>): VibSchema<any, any> {\n // The custom schema is already composed into the value validator above, so it\n // is withheld from the wrapping options — `buildValidator` running it again\n // would re-refine a canonical STRING with a schema that expects a Decimal.\n // Everything the wrappers do own — nullable, optional, array, default —\n // passes through untouched.\n const wrapping =\n options === undefined ? undefined : { ...options, schema: undefined };\n return buildSchema(\"decimal\", buildDecimalValueValidator(options), wrapping);\n}\n\nexport { validateDecimal };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Enum Schema\n// =============================================================================\nexport type EnumValues<S extends VibSchema> =\n S extends EnumSchema<infer TValues, any, any> ? TValues : never;\nexport type BaseEnumSchema<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n> = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n>;\n\nexport interface EnumSchema<\n TValues extends readonly string[],\n TInput = TValues[number],\n TOutput = TValues[number],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"enum\";\n readonly values: TValues;\n}\n\n/**\n * Create an enum schema that validates a value is one of the allowed strings.\n *\n * The values may be a readonly tuple (`[\"a\", \"b\"] as const`). The mutable arm\n * of the constraint keeps an inline literal inferred as a mutable tuple, so\n * the types of existing schemas do not change.\n *\n * @example\n * const status = v.enum_([\"active\", \"inactive\", \"pending\"]);\n */\n// @__NO_SIDE_EFFECTS__\nexport function enum_<\n const TValues extends string[] | readonly string[],\n const Opts extends\n | ScalarOptions<TValues[number], any>\n | undefined = undefined,\n>(\n values: TValues,\n options?: Opts\n): EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n> {\n // Create a Set for O(1) lookup\n const valueSet = new Set<TValues[number]>(values);\n\n // Create base validator\n const baseValidate = (value: unknown) => {\n if (isString(value) && valueSet.has(value)) {\n return ok(value as TValues[number]);\n }\n return {\n issues: [\n {\n message: `Expected one of: ${values.join(\" | \")}`,\n },\n ],\n };\n };\n\n const schema = buildSchema(\"enum\", baseValidate, options, {\n values,\n }) as EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n return schema;\n}\n","import { ValidationError } from \"@errors\";\nimport type { Cast, ThunkCast, VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Path Utilities for Nested Object Access\n// =============================================================================\n\n/**\n * Gets the value at a dot path in an object type.\n * Supports nested paths like \"create.name\" or \"create.friends\".\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? T[Key] extends Record<string, any>\n ? PathValue<T[Key], Rest>\n : never\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n/**\n * Recursively extracts all dot paths that lead to VibSchema or ThunkCast instances.\n * Returns a union of all valid paths (e.g., \"create\" | \"create.name\").\n * Limited to 5 levels of nesting to avoid infinite recursion.\n */\ntype PathsToSchemas<\n T extends string,\n Prefix extends string = \"\",\n Depth extends readonly unknown[] = [],\n> = Depth[\"length\"] extends 5\n ? never\n : // Check if T is a VibSchema\n T extends VibSchema<any, any>\n ? Prefix\n : // Check if T is a ThunkCast (function returning Cast)\n T extends ThunkCast<any, any>\n ? Prefix\n : T extends () => Cast<any, any>\n ? Prefix\n : // Otherwise recurse into object properties\n T extends Record<string, any>\n ? {\n [K in keyof T]: K extends string\n ? PathsToSchemas<\n T[K],\n Prefix extends \"\" ? K : `${Prefix}.${K}`,\n [...Depth, unknown]\n >\n : never;\n }[keyof T]\n : never;\n\n/**\n * Normalize a schema entry to VibSchema.\n * Handles both direct VibSchema and ThunkCast (unwrapping the thunk's return type).\n */\ntype NormalizeSchemaEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\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\n/**\n * Gets the schema type at a specific path for a specific key.\n * Handles both VibSchema and ThunkCast entries.\n */\ntype SchemaAtPath<\n TObject extends Record<string, any>,\n TPath extends string,\n K extends keyof TObject,\n> = NormalizeSchemaEntry<PathValue<TObject[K], TPath>>;\n\n/**\n * Extracts all valid paths that lead to schemas from all keys in the object.\n */\nexport type AllPathsToSchemas<TObject extends Record<string, any>> = {\n [K in keyof TObject]: K extends string ? PathsToSchemas<TObject[K]> : never;\n}[keyof TObject];\n\n// =============================================================================\n// FromObject Schema Types\n// =============================================================================\n\n/**\n * Options for fromObject schemas (same as ObjectOptions).\n */\nexport type FromObjectOptions<T = unknown> = ObjectOptions<T>;\n\n/**\n * Compute the entries type from an object and path.\n */\ntype ComputeEntries<\n TObject extends Record<string, any>,\n TPath extends string,\n> = {\n [K in keyof TObject]: SchemaAtPath<TObject, TPath, K>;\n};\n\n// =============================================================================\n// FromObject Schema Implementation\n// =============================================================================\n\n/**\n * Runtime helper to get a nested value by dot path.\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split(\".\");\n let current = obj;\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n current = current[part];\n }\n return current;\n}\n\n/**\n * Whether `path` names a property of `value`, including one that holds\n * `undefined` — a member that DECLARES it has no schema there (an insert-only\n * scalar's `update`) is not a path typo, and contributes no entry.\n */\nfunction declaresPath(value: unknown, path: string): boolean {\n const cut = path.lastIndexOf(\".\");\n const parent = cut === -1 ? value : getNestedValue(value, path.slice(0, cut));\n return isRecord(parent) && path.slice(cut + 1) in parent;\n}\n\n/**\n * Project entries without constructing an object validator that a composer\n * would immediately discard. The public builder uses this same path boundary.\n */\nexport function entriesFromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n>(sourceObject: TObject, path: TPath): ComputeEntries<TObject, TPath> {\n const result: Record<string, VibSchema<any, any>> = {};\n for (const key of Object.keys(sourceObject)) {\n const value = getNestedValue(sourceObject[key], path);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n if (Object.keys(sourceObject).length > 0 && Object.keys(result).length === 0)\n refuseUnmatchedPath(sourceObject, path);\n // The runtime path projection is the boundary that establishes this mapping.\n return result as ComputeEntries<TObject, TPath>;\n}\n\n/**\n * Creates an object schema by extracting schemas from a record using a dot path.\n * This is a convenient way to build an object schema from a record with proper type inference.\n *\n * @param sourceObject - Source object containing nested schemas\n * @param path - Dot path to extract schemas (e.g., \"create\", \"filter.where\")\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // Given a record of models with nested schemas:\n * const models = {\n * user: { create: v.string(), update: v.string() },\n * post: { create: v.number(), update: v.number() },\n * };\n *\n * // Extract all \"create\" schemas into a single object schema:\n * const createSchema = fromObject(models, \"create\");\n * // Validates: { user: string, post: number }\n *\n * // With options:\n * const optionalSchema = fromObject(models, \"create\", { optional: true });\n * // Validates: { user: string, post: number } | undefined\n *\n * @example\n * // Nested paths work too:\n * const nestedModels = {\n * user: { schemas: { create: v.string() } },\n * post: { schemas: { create: v.number() } },\n * };\n * const nestedSchema = fromObject(nestedModels, \"schemas.create\");\n * // Validates: { user: string, post: number }\n */\nexport function fromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n // TPath extends AllPathsToSchemas<TObject>,\n const TOpts extends FromObjectOptions | undefined = undefined,\n>(\n sourceObject: TObject,\n path: TPath,\n options?: TOpts\n): ObjectSchema<ComputeEntries<TObject, TPath>, TOpts> {\n return object(entriesFromObject(sourceObject, path), options);\n}\n\nexport type { ComputeEntries as ComputeEntriesFromObject };\n\n/** An empty projection, refused unless some source declares the path empty. */\nfunction refuseUnmatchedPath(\n sourceObject: Record<string, unknown>,\n path: string\n): void {\n if (Object.values(sourceObject).some((value) => declaresPath(value, path)))\n return;\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"fromObject\", path },\n [\n {\n path,\n message: `fromObject path \"${path}\" did not match any entries in the source object`,\n },\n ]\n );\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate, isString } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// ISO Format Validators\n// =============================================================================\n\n// ISO timestamp regex: 2023-12-15T10:30:00.000Z\nconst ISO_TIMESTAMP_REGEX =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,3})?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\n// ISO date regex: 2023-12-15\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n// ISO time regex: 10:30:00 or 10:30:00.000\nconst ISO_TIME_REGEX = /^\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?$/;\n\n// Pre-computed errors\nconst NOT_STRING_OR_DATE_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected string or Date\" }),\n ]),\n});\n\n// =============================================================================\n// ISO Timestamp Schema\n// =============================================================================\n\nexport interface BaseIsoTimestampSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimestampSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_timestamp\";\n}\n\n// Pre-computed errors\nconst INVALID_TIMESTAMP_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)\",\n }),\n ]),\n});\nconst INVALID_TIMESTAMP_DATE = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Invalid date in ISO timestamp\" }),\n ]),\n});\n\n/**\n * Validate ISO timestamp format.\n * Accepts Date objects and converts them to ISO strings.\n */\nfunction validateIsoTimestamp(value: unknown) {\n // Handle Date objects - convert to ISO string\n if (isDate(value)) {\n const epochMilliseconds = Date.prototype.getTime.call(value);\n if (!isDateTimeInstant(epochMilliseconds)) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(Date.prototype.toISOString.call(value));\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_TIMESTAMP_REGEX.exec(value);\n if (!match) return INVALID_TIMESTAMP_FORMAT;\n const hasValidCalendarAndClock =\n isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n ) && isDateTimeClock(Number(match[4]), Number(match[5]), Number(match[6]));\n if (\n !hasValidCalendarAndClock ||\n Number(match[7] ?? 0) > 23 ||\n Number(match[8] ?? 0) > 59 ||\n !isDateTimeInstant(Date.parse(value))\n ) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(new Date(value).toISOString());\n}\n\n/**\n * Create an ISO timestamp schema.\n * Accepts strings in format: 2023-12-15T10:30:00.000Z or Date objects.\n * Date objects are automatically converted to ISO strings.\n *\n * @example\n * const timestamp = v.isoTimestamp();\n * parse(timestamp, new Date()) // Returns ISO string\n */\nexport function isoTimestamp<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\n \"iso_timestamp\",\n validateIsoTimestamp,\n options\n ) as IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Date Schema\n// =============================================================================\n\nexport interface BaseIsoDateSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoDateSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_date\";\n}\n\n// Pre-computed errors\nconst INVALID_DATE_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO date format (YYYY-MM-DD)\",\n }),\n ]),\n});\nconst INVALID_DATE = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid date\" })]),\n});\n\n/**\n * Validate ISO date format.\n * Accepts Date objects and converts them to ISO date strings (YYYY-MM-DD).\n */\nfunction validateIsoDate(value: unknown) {\n // Handle Date objects - convert to ISO date string\n if (isDate(value)) {\n if (!isDateTimeInstant(Date.prototype.getTime.call(value))) {\n return INVALID_DATE;\n }\n return ok(Date.prototype.toISOString.call(value).slice(0, 10));\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_DATE_REGEX.exec(value);\n if (!match) return INVALID_DATE_FORMAT;\n if (\n !isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n )\n ) {\n return INVALID_DATE;\n }\n return ok(value);\n}\n\n/**\n * Create an ISO date schema.\n * Accepts strings in format: 2023-12-15 or Date objects.\n * Date objects are automatically converted to ISO date strings (YYYY-MM-DD).\n *\n * @example\n * const birthDate = v.isoDate();\n * parse(birthDate, new Date()) // Returns \"2023-12-15\"\n */\nexport function isoDate<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_date\", validateIsoDate, options) as IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Time Schema\n// =============================================================================\n\nexport interface BaseIsoTimeSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimeSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_time\";\n}\n\n// Pre-computed errors\nconst INVALID_TIME_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO time format (HH:mm:ss)\",\n }),\n ]),\n});\nconst INVALID_TIME = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid time\" })]),\n});\n\n/**\n * Validate ISO time format.\n * Accepts Date objects and extracts the time portion (HH:mm:ss.sss).\n */\nfunction validateIsoTime(value: unknown) {\n // Handle Date objects - extract time portion\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) return INVALID_TIME;\n // Extract HH:mm:ss.sss from ISO string\n const isoString = Date.prototype.toISOString.call(value);\n const timePart = isoString.split(\"T\")[1]!.replace(\"Z\", \"\");\n return ok(timePart);\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_TIME_REGEX.test(value)) return INVALID_TIME_FORMAT;\n\n const parts = value.split(\":\");\n const hours = Number(parts[0]);\n const minutes = Number(parts[1]);\n const seconds = Math.trunc(Number(parts[2]));\n\n if (\n hours < 0 ||\n hours > 23 ||\n minutes < 0 ||\n minutes > 59 ||\n seconds < 0 ||\n seconds > 59\n ) {\n return INVALID_TIME;\n }\n return ok(value.padEnd(12, value.includes(\".\") ? \"0\" : \".000\"));\n}\n\n/**\n * Create an ISO time schema.\n * Accepts strings in format: 10:30:00 or Date objects.\n * Date objects are automatically converted to time strings (HH:mm:ss.sss).\n *\n * @example\n * const startTime = v.isoTime();\n * parse(startTime, new Date()) // Returns \"10:30:00.000\"\n */\nexport function isoTime<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_time\", validateIsoTime, options) as IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export validators for reuse\nexport { validateIsoTimestamp, validateIsoDate, validateIsoTime };\n","/**\n * Field references (Prisma `FieldRef` parity)\n *\n * A field reference is an opaque, symbol-branded token that stands for a COLUMN\n * instead of a bound parameter in a filter operand position:\n *\n * ```ts\n * client.post.findMany({ where: { views: { gt: (ctx) => ctx.fields.likes } } });\n * // -> ... WHERE \"t0\".\"views\" > \"t0\".\"likes\"\n * ```\n *\n * The token is the MECHANISM; the callback is the surface that hands one out —\n * `ctx.fields` is this file's per-model table, built for the model whose filter\n * the operand sits in (see `validation/primitives/operand.ts`). A token held\n * directly is just as valid: it is what the callback returns.\n *\n * The token carries only what both the validation layer and the SQL builders\n * need — the owning model's schema key, the field's schema key, and the field's\n * scalar type — so it can be created without touching the model graph and\n * compared without any registry lookup.\n *\n * Two rules govern it, and each is enforced where it is actually decidable:\n *\n * - TYPE. A reference's scalar type must match the filter operand's scalar\n * type. Decided by the validation layer ({@link file://../validation/primitives/operand.ts}),\n * which knows the operand's type and nothing about models — scalar filter\n * schemas are interned across models by design (see `validation/scalars/intern.ts`).\n *\n * - SAME MODEL. A reference may only be used in a filter on its own model\n * (Prisma's rule: a field reference compares two columns of the SAME row).\n * Decided by the where-builder ({@link file://../query-engine/builders/where-builder.ts}),\n * because \"the model being filtered\" is a property of the QUERY SCOPE, not of\n * the schema: a nested relation `where` re-scopes to the relation's target\n * model while reusing that model's own (interned, model-blind) filter schemas.\n * The builder must resolve the referenced column against the current scope to\n * emit it at all, so the check is intrinsic there, not a duplicated guard. It\n * runs at SQL-build time — before any I/O.\n */\n\nimport type { Model } from \"./model/model\";\nimport type { ScalarType } from \"./scalars/common\";\n\n/**\n * Brand carried by every field reference. `Symbol.for` (not a fresh symbol) so\n * a reference stays recognizable across duplicated module instances.\n */\nexport const FIELD_REF_BRAND: unique symbol = Symbol.for(\"viborm.field-ref\");\n\n/**\n * An opaque reference to a scalar column of `TModel`.\n *\n * `TType` is the field's scalar type; it is what makes an `Int` reference\n * unassignable to a `String` filter operand at the type level.\n */\n/** What a reference knows about its column, held UNDER the brand symbol. */\nexport interface FieldRefPayload<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n /** Schema key of the model owning the field (e.g. `\"post\"`). */\n readonly model: TModel;\n /** Schema key of the field (e.g. `\"likes\"`), NOT the mapped column name. */\n readonly field: string;\n /** Scalar type of the field (e.g. `\"int\"`). */\n readonly type: TType;\n /** Whether the field is a list scalar. List references are not supported. */\n readonly list: boolean;\n}\n\nexport interface FieldRef<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n // The ONLY key, and it is a symbol on purpose. A reference rides operand\n // unions everywhere a filter value goes; if it exposed string-keyed members\n // (`model`, `field`, ...) the editor would offer them as completions inside\n // every filter object literal that admits a reference. The payload lives\n // under the brand so the token contributes NOTHING to those completions.\n readonly [FIELD_REF_BRAND]: FieldRefPayload<TModel, TType>;\n}\n\n/** Any field reference, regardless of model or scalar type. */\nexport type AnyFieldRef = FieldRef<string, ScalarType>;\n\n/**\n * Runtime brand check. Deliberately a plain property probe: it runs once per\n * filter operand, so it must be a single `typeof` plus one symbol lookup.\n */\nexport function isFieldRef(value: unknown): value is AnyFieldRef {\n if (typeof value !== \"object\" || value === null) return false;\n const payload = (value as { [FIELD_REF_BRAND]?: unknown })[FIELD_REF_BRAND];\n return typeof payload === \"object\" && payload !== null;\n}\n\n/** The reference's column facts. The one sanctioned way to read them. */\nexport function fieldRefPayload(ref: AnyFieldRef): FieldRefPayload {\n return ref[FIELD_REF_BRAND];\n}\n\n/** Human-readable spelling of a reference, for error messages. */\nexport function formatFieldRef(ref: AnyFieldRef): string {\n const payload = fieldRefPayload(ref);\n return `${payload.model}.${payload.field}`;\n}\n\nfunction createFieldRef(\n model: string,\n field: string,\n type: ScalarType,\n list: boolean\n): AnyFieldRef {\n return Object.freeze({\n [FIELD_REF_BRAND]: Object.freeze({ model, field, type, list }),\n });\n}\n\n// =============================================================================\n// TYPE-LEVEL PROJECTION: model -> its reference table\n// =============================================================================\n\ntype ScalarsOf<M> = M extends { \"~\": { state: { scalars: infer S } } }\n ? S\n : never;\n\ntype ScalarTypeOf<S> = S extends {\n \"~\": { state: { type: infer T extends ScalarType } };\n}\n ? T\n : ScalarType;\n\ntype ReferenceableScalarKeys<M> = {\n [K in keyof ScalarsOf<M>]: ScalarTypeOf<ScalarsOf<M>[K]> extends \"point\"\n ? never\n : K;\n}[keyof ScalarsOf<M>];\n\n/**\n * One model's reference table — the type of `ctx.fields` inside an operand\n * callback: one reference per scalar field, and nothing else on it, so a\n * mistyped field name is a compile error before it is a runtime one.\n */\nexport type ModelFieldRefs<TModelName extends string, M> = {\n readonly [K in ReferenceableScalarKeys<M> & string]: FieldRef<\n TModelName,\n ScalarTypeOf<ScalarsOf<M>[K]>\n >;\n};\n\n// =============================================================================\n// RUNTIME PROJECTION\n// =============================================================================\n\nconst UNKNOWN_FIELD = (modelName: string, key: string, known: string[]) =>\n new Error(\n `Unknown scalar field \"${key}\" on model '${modelName}'. Known fields: ${known.join(\", \")}.`\n );\n\n/**\n * The reference table for ONE model: `{ likes, views, … }`, each entry built on\n * first read and memoized.\n *\n * This is what an operand callback receives as `ctx.fields`, built once per\n * model and cached there — a query that never compares columns never builds\n * one, and a model's table costs a single object until a field is read. The\n * model name is passed in because the token carries the model's SCHEMA KEY,\n * which is what the where-builder compares the query scope against (hydration\n * sets `names.ts` to that key — see `hydration.ts`).\n */\nexport function createModelFieldRefs<\n TName extends string,\n M extends Model<any>,\n>(modelName: TName, model: M): ModelFieldRefs<TName, M> {\n const cache = new Map<string, AnyFieldRef>();\n const scalars = model[\"~\"].state.scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => scalars[key]![\"~\"].state.type !== \"point\"\n );\n const referenceableSet = new Set(referenceableNames);\n const table = new Proxy(Object.create(null) as Record<string, AnyFieldRef>, {\n get(_target, key) {\n if (typeof key !== \"string\") return undefined;\n const cached = cache.get(key);\n if (cached) return cached;\n const scalar = referenceableSet.has(key) ? scalars[key] : undefined;\n if (!scalar) {\n throw UNKNOWN_FIELD(modelName, key, referenceableNames);\n }\n const state = scalar[\"~\"].state;\n const ref = createFieldRef(modelName, key, state.type, state.array);\n cache.set(key, ref);\n return ref;\n },\n has: (_target, key) => typeof key === \"string\" && referenceableSet.has(key),\n ownKeys: () => referenceableNames,\n getOwnPropertyDescriptor: (_target, key) =>\n typeof key === \"string\" && referenceableSet.has(key)\n ? {\n enumerable: true,\n configurable: true,\n }\n : undefined,\n });\n // The one projection this file owes its callers: the proxy answers exactly\n // the model's scalar keys (`has`/`ownKeys` above enforce it, and any other key\n // throws), which is what `ModelFieldRefs` describes and no proxy signature can.\n return table as ModelFieldRefs<TName, M>;\n}\n","import { isFieldRef } from \"@schema/field-ref\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isBoolean, isNumber, isRecord, isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// JSON Schema\n// =============================================================================\n\n/**\n * JSON-compatible value type.\n * Represents any value that can be safely serialized to JSON.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** JSON serialization omits undefined object members and nulls array holes. */\nexport type JsonInput =\n | string\n | number\n | boolean\n | null\n | readonly (JsonInput | undefined)[]\n | { [key: string]: JsonInput | undefined };\n\n/**\n * A JSON value in WRITE position: everything `JsonValue` allows EXCEPT a bare\n * top-level `null`.\n *\n * Once `DbNull` and `JsonNull` exist, a top-level `null` no longer says which\n * of the two nulls it means, so it is not a legal write value — the same line\n * Prisma draws with its own `InputJsonValue`. Nested nulls are untouched:\n * `{ a: null }` is an ordinary document.\n */\nexport type InputJsonValue = Exclude<JsonInput, null>;\n\nexport interface BaseJsonSchema<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n > {}\n\nexport interface JsonSchema<TInput = JsonInput, TOutput = JsonValue>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"json\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_JSON_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected JSON-compatible value\" }),\n ]),\n});\n\n/**\n * Check if a value is JSON-compatible (can be serialized without loss).\n * Rejects: undefined, functions, symbols, bigint, circular references.\n */\nconst INVALID_JSON = Symbol(\"invalid JSON\");\n\nfunction normalizeJson(\n value: unknown,\n seen = new WeakMap<object, JsonValue | typeof INVALID_JSON>()\n): JsonValue | typeof INVALID_JSON {\n if (value === null || isString(value) || isBoolean(value)) return value;\n if (isNumber(value)) return Number.isFinite(value) ? value : INVALID_JSON;\n if (!(isRecord(value) || Array.isArray(value))) return INVALID_JSON;\n if (isFieldRef(value)) return INVALID_JSON;\n const previous = seen.get(value);\n if (previous !== undefined) return previous;\n seen.set(value, INVALID_JSON); // A back-edge is a cycle; completed aliases are reusable.\n if (Array.isArray(value)) {\n const result: JsonValue[] = [];\n for (const original of value) {\n const member =\n original === undefined ? null : normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n result.push(member);\n }\n seen.set(value, result);\n return result;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype) return INVALID_JSON;\n const result: Record<string, JsonValue> = {};\n for (const key of Object.keys(value)) {\n const original = value[key];\n if (original === undefined) {\n continue;\n }\n const member = normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n Object.defineProperty(result, key, {\n value: member,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n seen.set(value, result);\n return result;\n}\n\n/**\n * Validate that a value is JSON-compatible.\n */\nfunction validateJson(value: unknown): ValidationResult<JsonValue> {\n const normalized = normalizeJson(value);\n return normalized === INVALID_JSON ? NOT_JSON_ERROR : ok(normalized);\n}\n\n/**\n * Create a JSON schema that validates any JSON-compatible value.\n * Accepts: strings, numbers (finite), booleans, null, arrays, plain objects.\n * Rejects: undefined, functions, symbols, bigint, circular references, class instances.\n *\n * @example\n * const data = v.json();\n * const optionalData = v.json({ optional: true });\n * const nullableData = v.json({ nullable: true });\n */\n// @__NO_SIDE_EFFECTS__\nexport function json<\n const Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n>(\n options?: Opts\n): JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>> {\n return buildSchema<JsonInput, Opts | undefined>(\n \"json\",\n validateJson,\n options\n ) as JsonSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n >;\n}\n\n// Export for reuse\nexport { validateJson };\n","/**\n * JSON null sentinels (Prisma `DbNull` / `JsonNull` / `AnyNull` parity)\n *\n * A nullable JSON column has TWO different nulls, and SQL can tell them apart\n * while JavaScript cannot:\n *\n * - the SQL NULL — the column holds no document at all (`col IS NULL`);\n * - the JSON null — the column holds a document, and that document is the\n * JSON value `null` (`'null'::jsonb`, `CAST('null' AS JSON)`, the text\n * `null` on SQLite).\n *\n * Both read back as JavaScript `null`, so a bare `null` cannot name either one\n * without guessing. Prisma solves this with three exported sentinel values, and\n * so does this file:\n *\n * ```ts\n * import { AnyNull, DbNull, JsonNull } from \"viborm\";\n *\n * await client.entry.update({ where, data: { meta: DbNull } }); // -> SQL NULL\n * await client.entry.update({ where, data: { meta: JsonNull } }); // -> 'null'\n * await client.entry.findMany({ where: { meta: { equals: AnyNull } } });\n * ```\n *\n * `AnyNull` is FILTER-ONLY, exactly as in Prisma: \"either null\" is a question,\n * not a value, so there is nothing for a write to store. The validation layer\n * refuses it in write position by name (see\n * {@link file://../validation/primitives/json-null.ts}).\n *\n * THE TOKENS ARE CLASS INSTANCES ON PURPOSE. `v.json()` accepts a plain object\n * with any keys, so a plain-object token would type-check as an ordinary JSON\n * document and could be PERSISTED as user data — the same hazard field\n * references have (see {@link file://./field-ref.ts}). A class instance has a\n * prototype that is not `Object.prototype`, so JSON validation rejects it\n * structurally: a sentinel nested anywhere inside a document\n * (`{ a: DbNull }`) fails validation instead of landing in the column as `{}`.\n * Only the top-level operand positions that explicitly opt in accept one.\n *\n * The `kind` property is an OWN ENUMERABLE STRING key, not only the symbol\n * brand, so a token reads as itself in a dump and a structural serializer at\n * least tells the three apart rather than flattening all three to `{}`.\n *\n * BEING TOLD APART IS NOT THE SAME AS BEING RECOGNIZED, and this file used to\n * claim otherwise. A JSON column accepts an ARBITRARY object, so\n * `{ kind: \"DbNull\" }` is ordinary user data — and a serializer walking\n * `Object.keys` gives it the same identity as the sentinel. The cache key\n * builder did exactly that, and a cached client served the rows of\n * `equals: DbNull` for `equals: { kind: \"DbNull\" }`, in both directions, for\n * the whole TTL. A consumer that must not confuse the two asks\n * {@link isJsonNullSentinel} and keys the answer somewhere a document cannot\n * reach, as {@link file://../cache/key.ts} now does.\n */\n\n/**\n * Brand carried by every JSON null sentinel. `Symbol.for` (not a fresh symbol)\n * so a token stays recognizable across duplicated module instances, exactly as\n * for field references.\n */\nexport const JSON_NULL_BRAND: unique symbol = Symbol.for(\"viborm.json-null\");\n\n/** The three sentinels, by name. */\nexport type JsonNullKind = \"DbNull\" | \"JsonNull\" | \"AnyNull\";\n\n/**\n * A JSON null sentinel. `TKind` is what makes `AnyNull` unassignable to a write\n * slot while `DbNull` and `JsonNull` are assignable to it.\n */\nexport class JsonNullSentinel<TKind extends JsonNullKind = JsonNullKind> {\n readonly [JSON_NULL_BRAND]: TKind;\n /** Own enumerable key so structural serializers separate the three. */\n readonly kind: TKind;\n\n constructor(kind: TKind) {\n this[JSON_NULL_BRAND] = kind;\n this.kind = kind;\n Object.freeze(this);\n }\n\n /** Readable in error messages: `DbNull`, not `[object Object]`. */\n toString(): string {\n return this.kind;\n }\n\n /** Distinct under `JSON.stringify` (instrumentation, dedup keys). */\n toJSON(): string {\n return `viborm.json-null:${this.kind}`;\n }\n}\n\n/** Any sentinel, regardless of kind. */\nexport type AnyJsonNullSentinel = JsonNullSentinel<JsonNullKind>;\n\n/** The database NULL: the column holds no JSON document. */\nexport const DbNull: JsonNullSentinel<\"DbNull\"> = new JsonNullSentinel(\n \"DbNull\"\n);\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> = new JsonNullSentinel(\n \"JsonNull\"\n);\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> = new JsonNullSentinel(\n \"AnyNull\"\n);\n\nconst KINDS: ReadonlySet<string> = new Set<JsonNullKind>([\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n]);\n\n/**\n * Runtime brand check. A property probe rather than `instanceof`, so a token\n * created by a duplicated copy of this module is still recognized (the same\n * reason {@link file://./field-ref.ts} probes its symbol).\n */\nexport function isJsonNullSentinel(\n value: unknown\n): value is AnyJsonNullSentinel {\n if (typeof value !== \"object\" || value === null) return false;\n const brand = (value as { [JSON_NULL_BRAND]?: unknown })[JSON_NULL_BRAND];\n return typeof brand === \"string\" && KINDS.has(brand);\n}\n\n/** The sentinel's kind, or `undefined` when the value is not a sentinel. */\nexport function jsonNullKindOf(value: unknown): JsonNullKind | undefined {\n return isJsonNullSentinel(value) ? value.kind : undefined;\n}\n","// JSON null sentinel operand schemas\n// Admits `DbNull` / `JsonNull` / `AnyNull` into the exact JSON slots that can\n// mean something by them, and refuses them everywhere else BY NAME.\n\nimport {\n type AnyJsonNullSentinel,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n type JsonNullSentinel,\n} from \"@schema/json-null\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n/**\n * Why this is a brand-discriminated wrapper and not `v.union([...])`: a union\n * rewrites every existing operand failure into \"Value did not match any union\n * member: …\". Here the brand is the discriminator, so a non-sentinel value is\n * handed straight to the wrapped schema and keeps its exact message, and a\n * sentinel gets a sentinel-specific one. Same reasoning as\n * {@link file://./field-ref.ts}.\n */\nexport interface JsonNullOrSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_null_or\";\n /** The sentinel kinds this slot accepts. */\n readonly allowed: readonly JsonNullKind[];\n /** The operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\n/**\n * A JSON WRITE slot: the sentinels it accepts, the whole JSON document\n * language, and — deliberately — NOT a bare `null`.\n *\n * `null` is excluded from the INPUT type as well as refused at runtime, which\n * is Prisma's rule: its `InputJsonValue` documents that `null` is disallowed at\n * the top level of a JSON write because its meaning would be ambiguous, and\n * directs callers to `Prisma.JsonNull` / `Prisma.DbNull`\n * (`@prisma/client`, `runtime/client.d.ts`, the `InputJsonValue` doc comment;\n * https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/working-with-json-fields#using-null-values).\n * `null` is only excluded at the TOP level — `{ a: null }` is an ordinary\n * document and stays legal, exactly as in Prisma.\n */\nexport interface JsonWriteSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_write\";\n readonly allowed: readonly JsonNullKind[];\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\nconst ALL_KINDS: readonly JsonNullKind[] = [\"DbNull\", \"JsonNull\", \"AnyNull\"];\n\n/** `DbNull, JsonNull or AnyNull` — for the refusal messages. */\nfunction listKinds(kinds: readonly JsonNullKind[]): string {\n if (kinds.length === 1) return kinds[0] as string;\n return `${kinds.slice(0, -1).join(\", \")} or ${kinds.at(-1)}`;\n}\n\n/**\n * The refusal a disallowed sentinel gets. It names the token the caller used\n * and the ones this slot would have accepted, because the whole point of the\n * sentinels is that \"null\" alone never says enough.\n */\nfunction refuseSentinel(\n sentinel: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n const rejected = ALL_KINDS.filter((kind) => !allowed.includes(kind));\n const reason =\n rejected.length === ALL_KINDS.length\n ? `JSON null sentinels are not supported in ${where}`\n : `${sentinel.kind} is not supported in ${where}; that slot accepts ${listKinds(allowed)}`;\n return fail(`${reason}.`);\n}\n\nfunction checkSentinel(\n value: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n return allowed.includes(value.kind)\n ? ok(value)\n : refuseSentinel(value, allowed, where);\n}\n\nfunction copyOptionality(\n schema: object,\n wrapped: VibSchema<any, any>,\n allowed: readonly JsonNullKind[]\n): void {\n (schema as { allowed: readonly JsonNullKind[] }).allowed = allowed;\n (schema as { wrapped: VibSchema<any, any> }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n}\n\n/**\n * A JSON FILTER operand that also accepts the sentinels in `allowed`.\n *\n * A bare `null` is NOT intercepted here: it keeps whatever the wrapped operand\n * already meant (at the document root, \"the column IS NULL\"; under a `path`,\n * \"the value at that path is the JSON null\"). That behavior predates the\n * sentinels and stays pinned — see the regression witnesses in\n * `tests/drivers/json-null-sentinel-behavior.ts`.\n */\nexport function jsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string\n): JsonNullOrSchema<TAllowed, TSchema> {\n const schema = createSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_null_or\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as JsonNullOrSchema<TAllowed, TSchema>;\n\n copyOptionality(schema, wrapped, allowed);\n return schema;\n}\n\n/**\n * A JSON WRITE slot: sentinels in `allowed`, any JSON document, no bare `null`.\n *\n * The bare-`null` refusal is the reason this is not just `jsonNullOr`. See\n * {@link JsonWriteSchema} for the rule and its citation.\n *\n * An OMITTED key is untouched: `undefined` falls through to the wrapped schema,\n * which applies the field's own default — for a nullable JSON field that\n * default is the database NULL, which is exactly what `DbNull` names. Only a\n * `null` the CALLER spelled is ambiguous, and only that one is refused.\n */\nexport function jsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string,\n nullRefusal: string\n): JsonWriteSchema<TAllowed, TSchema> {\n const schema = createSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_write\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n if (value === null) return fail(nullRefusal) as never;\n const result = validateSchema(wrapped, value);\n // A supplied document transformed to null is JSON null; omitted nullable\n // defaults keep their separate SQL NULL path.\n return (\n !result.issues && result.value === null && value !== undefined\n ? checkSentinel(JsonNull, allowed, where)\n : result\n ) as never;\n }) as JsonWriteSchema<TAllowed, TSchema>;\n\n copyOptionality(schema, wrapped, allowed);\n return schema;\n}\n","import type { VibSchema } from \"../types\";\nimport { isFunction } from \"../value-guards\";\n\n/**\n * Creates a lazy schema that defers evaluation until first access.\n * The schema is cached after first resolution.\n *\n * Uses a Proxy to transparently forward all property access, method calls,\n * and operations to the wrapped schema. This ensures the lazy schema\n * behaves identically to the wrapped type.\n *\n * The returned schema is typed as T, so it's transparent to consumers -\n * InferInput and InferOutput work as if it were the wrapped schema.\n *\n * @param factory - A function that returns the schema to wrap\n * @returns A schema typed as T that lazily resolves on first access\n */\nexport function lazy<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n // Use a Proxy to transparently forward all operations to the resolved schema\n const proxy = new Proxy({} as T, {\n get(_target, prop, receiver) {\n const resolved = resolve();\n const value = Reflect.get(resolved, prop, receiver);\n // Bind methods to the resolved schema to preserve `this` context\n return isFunction(value) ? value.bind(resolved) : value;\n },\n\n has(_target, prop) {\n return Reflect.has(resolve(), prop);\n },\n\n ownKeys(_target) {\n return Reflect.ownKeys(resolve());\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(resolve(), prop);\n },\n\n getPrototypeOf(_target) {\n return Reflect.getPrototypeOf(resolve());\n },\n });\n\n return proxy;\n}\n\n/**\n * Lightweight deferred schema reference.\n *\n * Unlike `lazy()` (a Proxy that resolves on ANY property access — including\n * the object validator's duck-typing reads), `lazyRef` exposes a static\n * `type` and a `~standard.validate` that only builds the wrapped schema when\n * the validator is first CALLED. Used for args→core schema cross-references\n * so an operation only constructs the core schemas its arguments actually\n * use (e.g. `findUnique({ where })` never builds select/include).\n *\n * NOT a general-purpose wrapper: it reports no `acceptsUndefined`/default\n * metadata, so it must only wrap schemas with no default value (true for all\n * core schema references).\n */\nexport function lazyRef<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n return {\n type: \"lazyRef\",\n /**\n * JSON-schema conversion unwraps through this (resolves on demand) — see\n * the `lazyRef` case in {@link file://../json-schema/converters.ts}. A\n * reference that points BACK at a schema still being converted (a scalar\n * filter's `not`) is closed there with a `$ref`, so unwrapping terminates.\n */\n get wrapped() {\n return resolve();\n },\n // Introspection surface (resolves on demand). Deliberately NOT exposed:\n // `options`/`acceptsUndefined`/`default` — the object validator\n // duck-types those during resolve(), and resolving getters there would\n // rebuild the wrapped schema eagerly, defeating the laziness.\n get entries() {\n return (resolve() as { entries?: unknown }).entries;\n },\n \"~standard\": {\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) => resolve()[\"~standard\"].validate(value),\n get jsonSchema() {\n return resolve()[\"~standard\"].jsonSchema;\n },\n },\n } as unknown as T;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Literal Schema\n// =============================================================================\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | bigint;\n\nexport interface LiteralSchema<T extends LiteralValue, TInput = T, TOutput = T>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"literal\";\n readonly value: T;\n}\n\n/**\n * Create a literal schema that matches an exact value.\n *\n * @example\n * const admin = v.literal(\"admin\");\n * const zero = v.literal(0);\n * const isTrue = v.literal(true);\n */\nexport function literal<\n const T extends LiteralValue,\n const Opts extends ScalarOptions<T, any> | undefined = undefined,\n>(\n expected: T,\n options?: Opts\n): LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>> {\n // Pre-compute error for fast path\n const expectedStr = expected === null ? \"null\" : String(expected);\n const errorResult = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected literal: ${expectedStr}`,\n }),\n ]),\n });\n\n // Create base validator\n const baseValidate = (value: unknown) =>\n value === expected ? ok(value as T) : errorResult;\n\n return buildSchema(\"literal\", baseValidate, options, {\n value: expected,\n }) as LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>>;\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { createSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Nullable Schema\n// =============================================================================\n\nexport interface NullableSchema<\n TWrapped extends VibSchema<any, any>,\n TInput = InferInput<TWrapped> | null,\n TOutput = InferOutput<TWrapped> | null,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"nullable\";\n readonly wrapped: TWrapped;\n}\n\n/**\n * Create a nullable schema that allows null values.\n *\n * @example\n * const nullableName = v.nullable(v.string());\n */\nexport function nullable<TWrapped extends VibSchema<any, any>>(\n wrapped: TWrapped\n): NullableSchema<TWrapped> {\n // Cache validate function directly\n const validate = wrapped[\"~standard\"].validate;\n\n const schema = createSchema(\n \"nullable\",\n (value): ValidationResult<InferOutput<TWrapped> | null> => {\n // Handle null - fast path\n if (value === null) {\n return ok(null);\n }\n\n // Delegate to wrapped schema (cast to our result type)\n return validate(value) as ValidationResult<InferOutput<TWrapped>>;\n }\n ) as NullableSchema<TWrapped>;\n\n // Add reference\n (schema as any).wrapped = wrapped;\n\n return schema;\n}\n\n/**\n * Conditionally wrap a schema in nullable based on a boolean flag.\n * Useful for building schemas dynamically where nullability is determined at compile time.\n *\n * @example\n * const schema = v.maybeNullable(v.string(), true); // NullableSchema<StringSchema>\n * const schema2 = v.maybeNullable(v.string(), false); // StringSchema\n */\nexport function maybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n>(\n wrapped: TWrapped,\n isNullable: TIsNullable\n): TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped {\n if (isNullable) {\n return nullable(wrapped) as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n }\n return wrapped as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n}\n","import { type ObjectSchema, object } from \"./object\";\nimport type { V } from \"./v\";\n\n/**\n * Create a new object schema with specific keys omitted.\n *\n * @param schema - The source object schema\n * @param keys - Array of keys to omit from the schema\n * @returns A new object schema without the specified keys\n *\n * @example\n * const user = v.object({\n * id: v.string(),\n * name: v.string(),\n * password: v.string(),\n * });\n *\n * const publicUser = v.omit(user, ['password']);\n * // { id?: string; name?: string }\n */\nexport function omit<\n TSchema extends ObjectSchema<any, any>,\n const TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n>(schema: TSchema, keys: TKeys): V.Omit<TSchema, TKeys> {\n return object(schema.entries, {\n ...(schema.options || {}),\n omit: keys,\n }) as V.Omit<TSchema, TKeys>;\n}\n","import type { VibSchema } from \"../types\";\nimport { fail } from \"./helpers\";\n\n// Filter parsing is synchronous. Bound semantic filter containers before\n// descending, including scalar `not`, without restricting JSON data depth.\nlet activeDepth = 0;\nconst MAX_FILTER_DEPTH = 16;\nlet bounded = true;\n\n/**\n * Run `parse` without the bound: a domain predicate is the application's own\n * data, whose termination its lowering proves (the bound is for payloads).\n */\nexport function withoutFilterDepthBound<T>(parse: () => T): T {\n const previous = bounded;\n bounded = false;\n try {\n return parse();\n } finally {\n bounded = previous;\n }\n}\n\nexport function limitFilterDepth<S extends VibSchema>(schema: S): S {\n const validate = schema[\"~standard\"].validate;\n Object.defineProperty(schema[\"~standard\"], \"validate\", {\n value: (value: unknown) => {\n if (bounded && activeDepth >= MAX_FILTER_DEPTH)\n return fail(`Filter nesting exceeds ${MAX_FILTER_DEPTH} levels`);\n activeDepth++;\n try {\n return validate(value);\n } finally {\n activeDepth--;\n }\n },\n });\n return schema;\n}\n","// A domain predicate (an extension's `rule`) names values the call supplies\n// and conditions on them. While one is admitted, every value position of the\n// `where` schemas asks the admission what its value stands for, and every\n// `where` asks what a filter word in its place stands for: the schemas, which\n// own which place is a value and which a filter, are the one judge of where a\n// word can sit. The nodes the admission answers are registered here and kept\n// as they are, by identity, so an admitted predicate admits again as itself.\n// Nothing else can produce one: the registries are module-private, so a\n// caller's payload never carries a node.\n\nimport type { VibSchema } from \"../types\";\nimport { withoutFilterDepthBound } from \"./filter-depth\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n/**\n * What a filter word stands for: `nodes`, kept as they are, and the filter\n * written with them that is parsed in the word's place (the first node\n * itself where there is none); or why the word is refused, at a path inside\n * it.\n */\nexport type FilterWord =\n | { readonly nodes: readonly object[]; readonly where?: unknown }\n | { readonly message: string; readonly path: readonly PropertyKey[] };\n\n/** What a domain predicate's admission makes of the markers it meets. */\nexport interface DomainMarkers {\n /** The node a value stands for (a call value), `undefined` for a literal. */\n value(value: unknown): object | undefined;\n /** What a filter word stands for, `undefined` for a value that is none. */\n filter(value: object): FilterWord | undefined;\n}\n\nconst values = new WeakSet<object>();\nconst conditions = new WeakSet<object>();\n\n/** The admission in progress, while a domain predicate is parsed. */\nlet admitting: DomainMarkers | undefined;\n\n/**\n * One admission's parsed filters, per `where` schema and input object. A\n * predicate shares sub-filters freely (a relation's target predicate is\n * inlined wherever it is read), so each shared object is parsed once per\n * schema and its admitted value shared alike. Only successes are kept: a\n * refusal is always reported from the place that reached it.\n */\nexport type AdmittedFilters = WeakMap<object, WeakMap<object, unknown>>;\nlet parsed: AdmittedFilters | undefined;\n\n/**\n * The node `value` is, or, while a domain predicate is admitted, the node it\n * stands for; `undefined` for any other value.\n */\nexport function valueNodeOf(value: unknown): object | undefined {\n if (typeof value === \"object\" && value !== null && values.has(value))\n return value;\n const node = admitting?.value(value);\n if (node !== undefined) values.add(node);\n return node;\n}\n\n/** A value position that also keeps a value node. */\nexport function valueNodeOr<S extends VibSchema<any, any>>(wrapped: S): S {\n const schema = createSchema<unknown, unknown>(\"value_node_or\", (value) => {\n const node = valueNodeOf(value);\n return node === undefined ? validateSchema(wrapped, value) : ok(node);\n });\n Object.assign(schema, {\n wrapped,\n acceptsUndefined:\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true,\n });\n return schema as unknown as S;\n}\n\n/**\n * A `where` that also keeps a condition node, and, while a domain predicate is\n * admitted, reads a filter word in its place as what the word stands for.\n * Wrapped in place: a `where` reaches itself through `AND`/`OR`/`NOT`, so\n * every nested position keeps one.\n */\nexport function conditionNodeOr<S extends VibSchema<any, any>>(where: S): S {\n const standard = where[\"~standard\"];\n const validate = standard.validate;\n const admit = (value: object) => {\n const word = admitting?.filter(value);\n if (word === undefined) return validate(value);\n if (\"message\" in word) return fail(word.message, [...word.path]);\n for (const node of word.nodes) conditions.add(node);\n return word.where === undefined ? ok(word.nodes[0]) : validate(word.where);\n };\n Object.defineProperty(standard, \"validate\", {\n value: (value: unknown) => {\n if (typeof value !== \"object\" || value === null) return validate(value);\n if (conditions.has(value)) return ok(value);\n const seen = admitting && parsed;\n if (!seen) return admit(value);\n let byValue = seen.get(standard);\n if (byValue === undefined) seen.set(standard, (byValue = new WeakMap()));\n const known = byValue.get(value);\n if (known !== undefined) return known;\n const result = admit(value) as { issues?: unknown };\n if (result.issues === undefined) byValue.set(value, result);\n return result;\n },\n });\n return where;\n}\n\n/**\n * Parse with a domain predicate's rules: its markers are `markers`' nodes, it\n * is the application's own finite data, so the caller payload's nesting\n * bound does not apply, and a recursion writes its depth.\n */\nexport function admittingDomainPredicate<T>(\n markers: DomainMarkers,\n admit: () => T,\n filters: AdmittedFilters = new WeakMap()\n): T {\n const previous = admitting;\n const previousFilters = parsed;\n admitting = markers;\n parsed = filters;\n try {\n return withoutFilterDepthBound(admit);\n } finally {\n admitting = previous;\n parsed = previousFilters;\n }\n}\n\n/**\n * A filter's `recurse`, which a domain predicate must give a depth: the\n * default one would stop inheritance at a number nobody wrote.\n */\nexport function writtenDepth<S extends VibSchema<any, any>>(recurrence: S): S {\n const schema = createSchema<unknown, unknown>(\"written_depth\", (value) =>\n admitting &&\n (value === true ||\n (typeof value === \"object\" &&\n value !== null &&\n (value as { depth?: unknown }).depth === undefined))\n ? fail(\n \"A row predicate's recurse must write its depth (false, or a number)\"\n )\n : validateSchema(recurrence, value)\n );\n Object.assign(schema, {\n wrapped: recurrence,\n acceptsUndefined:\n (recurrence as { acceptsUndefined?: boolean }).acceptsUndefined === true,\n });\n return schema as unknown as S;\n}\n","// Comparison Operand Schemas\n//\n// A comparison operand is the right-hand side of a scalar filter: the thing a\n// column is compared AGAINST. Four kinds live here, and this file is the only\n// place that decides which of them a given position accepts:\n//\n// 1. a plain value `{ views: { gt: 10 } }`\n// 2. a field reference `{ views: { gt: <FieldRef> } }` -> another column\n// 3. an SQL fragment `{ views: { gt: sql`…` } }` -> escape hatch\n// 4. a callback `{ views: { gt: (ctx) => … } }` -> sugar for 2 and 3\n//\n// The callback is RESOLVED HERE, during validation: it is invoked once and its\n// return value substituted, so the query engine's operand invariant stays\n// exactly \"plain value | FieldRef | Sql\" and no function ever reaches it. That\n// is what keeps validation the single home for payload normalization — the\n// engine does not learn a fourth operand kind, and neither does the cache key.\n\nimport {\n type AnyFieldRef,\n createModelFieldRefs,\n type FieldRef,\n fieldRefPayload,\n isFieldRef,\n type ModelFieldRefs,\n} from \"@schema/field-ref\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport { isSql, type Sql, sql } from \"@sql\";\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport { limitFilterDepth } from \"./filter-depth\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { valueNodeOf } from \"./parameter\";\n\n// =============================================================================\n// THE CALLBACK CONTEXT\n// =============================================================================\n\n/**\n * What a comparison-operand callback is handed.\n *\n * `fields` is the CURRENT model's reference table — the model whose filter the\n * operand sits in, which for a nested relation filter is the relation's TARGET,\n * not the root. Correlated references to an enclosing scope are deliberately\n * absent: a field reference compares two columns of the SAME row, and widening\n * that is a separate decision.\n *\n * `sql` is the ordinary tagged template; interpolations inside a fragment ride\n * along as bound parameters (see {@link file://../../sql/sql.ts}).\n *\n * PURITY IS THE CONTRACT for the callback handed this context. Validation may\n * run a payload's callbacks more than once — `upsert` re-parses its taken arm\n * (the C2 residue), so a callback under `upsert.update` can be invoked twice\n * for one call. A callback that counts its calls, mutates outer state, or\n * returns a different fragment each time gets exactly what it asks for; a pure\n * one is indistinguishable from a literal token, which is the whole point of\n * the sugar.\n */\nexport interface OperandCtx<TModel> {\n readonly fields: ModelFieldRefs<string, TModel>;\n readonly sql: typeof sql;\n}\n\n/** An operand context for an unknown model — the type-level default. */\nexport type AnyOperandCtx = OperandCtx<any>;\n\n// =============================================================================\n// THE PER-MODEL SCOPE\n// =============================================================================\n\n/**\n * The model whose filter is currently being validated.\n *\n * WHY AN AMBIENT SCOPE RATHER THAN A BAKED-IN CONTEXT: scalar filter schemas are\n * INTERNED across models on purpose (see `validation/scalars/intern.ts`) — two\n * `s.string()` fields on different models share one filter tree — so an operand\n * schema cannot carry a model. What IS per-model is the `where` schema that\n * contains it, and every re-scoping boundary is one of those (a nested relation\n * filter embeds the TARGET model's `where`). So the boundary pushes the model\n * and the operand reads it. Validation is synchronous and depth-first, which is\n * what makes a single slot with save/restore exact rather than merely likely.\n */\nlet activeModel: AnyModel | undefined;\n\n/** Contexts are built on first use and memoized per model. */\nconst contexts = new WeakMap<AnyModel, AnyOperandCtx>();\n\n/**\n * Run `validate` with `model` as the operand scope, restoring the previous one\n * afterwards. Re-entrant: a nested relation filter pushes its own target and\n * pops back to the parent.\n */\nexport function runInOperandScope<T>(model: AnyModel, validate: () => T): T {\n const previous = activeModel;\n activeModel = model;\n try {\n return validate();\n } finally {\n activeModel = previous;\n }\n}\n\n/**\n * Re-close a schema onto a model: everything validated through it resolves its\n * operand callbacks against `model`.\n *\n * The wrap is applied IN PLACE, and both reasons matter. The schema is a\n * freshly built, model-owned object whose `entries` / `extend` surface its own\n * factory and the factories above it still read, so returning a different object\n * would either lose that surface or force a copy of every entry. And a `where`\n * is SELF-REFERENTIAL — its `AND`/`OR`/`NOT` thunks close over the very const\n * being returned — so a copy would leave the recursion pointing at the\n * unwrapped original.\n */\nexport function scopeOperands<S extends VibSchema<any, any>>(\n schema: S,\n model: AnyModel\n): S {\n const standard = schema[\"~standard\"] as {\n validate: (value: unknown) => unknown;\n };\n const inner = standard.validate;\n standard.validate = (value: unknown) =>\n runInOperandScope(model, () => inner(value));\n return limitFilterDepth(schema);\n}\n\n/** The context for the model in scope, or `undefined` outside any filter. */\nfunction currentContext(): AnyOperandCtx | undefined {\n const model = activeModel;\n if (!model) return undefined;\n const cached = contexts.get(model);\n if (cached) return cached;\n const context: AnyOperandCtx = {\n fields: createModelFieldRefs(model[\"~\"].names.ts ?? \"unknown\", model),\n sql,\n };\n contexts.set(model, context);\n return context;\n}\n\n// =============================================================================\n// THE OPERAND SCHEMA\n// =============================================================================\n\n/**\n * A comparison operand: the wrapped scalar schema, a field reference of\n * `TType`, an SQL fragment, or a callback returning one of the latter two.\n *\n * This is deliberately not `v.union([...])`: a union would rewrite every\n * existing operand's failure message into \"Value did not match any union\n * member: …\". Here each non-value kind is recognized by its own discriminator,\n * so an ordinary bad value is handed straight to the wrapped schema and keeps\n * its exact message.\n *\n * The reference's MODEL is not checked here — scalar filter schemas are interned\n * across models and carry no model identity (see `validation/scalars/intern.ts`);\n * the same-model rule is a query-scope property and is enforced by the\n * where-builder before any I/O. See {@link file://../../schema/field-ref.ts}.\n */\nexport interface ComparisonOperandSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n> extends VibSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n > {\n readonly type: \"comparison_operand\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nconst CALLBACK_OUT_OF_SCOPE =\n \"A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.\";\n\nconst RETURN_REFUSAL =\n \"A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)\";\n\nfunction describe(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a value of type '${typeof value}'`;\n}\n\nfunction resolveCallback(\n callback: (ctx: AnyOperandCtx) => unknown,\n fieldType: ScalarType\n) {\n const context = currentContext();\n if (!context) {\n return fail(CALLBACK_OUT_OF_SCOPE);\n }\n\n let returned: unknown;\n try {\n returned = callback(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Filter callback threw: ${message}`);\n }\n\n if (isFieldRef(returned)) {\n return checkRef(returned, fieldType);\n }\n if (isSql(returned)) {\n return ok(returned);\n }\n if (isRecord(returned) && isFunction(returned.then)) {\n discardAsyncValidationResult(returned);\n return fail(\n `${RETURN_REFUSAL}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`\n );\n }\n return fail(`${RETURN_REFUSAL}; it returned ${describe(returned)}.`);\n}\n\n/**\n * Build a comparison operand around a scalar schema.\n *\n * ATTACH IT ONLY WHERE THE ENGINE CAN COMPILE THE RESULT. Acceptance that\n * outruns the builder is accept-and-ignore with extra steps: today that means\n * `equals` / `not` / `lt` / `lte` / `gt` / `gte` on non-list scalar filters, and\n * nothing else. `in` / `notIn` and the list operators take VALUES, `having` is\n * an aggregate over a group rather than a column of one row, and the string\n * predicates keep the narrower {@link fieldRefOr} (a reference, no fragment).\n */\nexport function comparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n>(\n fieldType: TType,\n wrapped: TSchema\n): ComparisonOperandSchema<TType, TSchema, TCtx> {\n const schema = createSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n >(\"comparison_operand\", (value) => {\n const node = valueNodeOf(value);\n if (node !== undefined) return ok(node) as never;\n if (isFunction(value)) {\n return resolveCallback(\n value as (ctx: AnyOperandCtx) => unknown,\n fieldType\n ) as never;\n }\n if (isFieldRef(value)) {\n return checkRef(value, fieldType) as never;\n }\n if (isSql(value)) {\n return ok(value) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // Neither a reference, a fragment, nor a callback is ever a default;\n // optionality is entirely the wrapped schema's business, so mirror it for the\n // object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\n}\n\n// =============================================================================\n// FIELD-REFERENCE-ONLY OPERAND\n// =============================================================================\n\n/**\n * A comparison operand that accepts EITHER a field reference of `TType` or the\n * wrapped scalar schema — no fragment, no callback.\n *\n * This is what the string predicates (`contains` / `startsWith` / `endsWith`)\n * take: the builder compiles a referenced column there, so the reference stays,\n * while the fragment and its callback sugar are drawn at the comparison\n * operators only.\n */\nexport interface FieldRefOrSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n > {\n readonly type: \"field_ref_or\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nexport function fieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n>(fieldType: TType, wrapped: TSchema): FieldRefOrSchema<TType, TSchema> {\n const schema = createSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n >(\"field_ref_or\", (value) => {\n const node = valueNodeOf(value);\n if (node !== undefined) return ok(node) as never;\n if (isFieldRef(value)) {\n return checkRef(value, fieldType);\n }\n return validateSchema(wrapped, value) as never;\n }) as FieldRefOrSchema<TType, TSchema>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // A reference is never a default; optionality is entirely the wrapped\n // schema's business, so mirror it for the object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\n}\n\n// =============================================================================\n// RE-CLOSING WRAPPER\n// =============================================================================\n\n/**\n * Re-closes a schema that transitively opened a non-value operand.\n *\n * Scalar filter schemas are shared: `having` reuses the very same interned\n * filter a `where` uses. Prisma does not allow field references in\n * `having`/`groupBy` (a HAVING operand is an aggregate over a group, not a\n * column of one row), and neither do we — so the reuse site wraps itself and\n * fails closed instead of inheriting the operand by accident.\n */\nexport interface NoFieldRefSchema<TSchema extends VibSchema<any, any>>\n extends VibSchema<InferInput<TSchema>, InferOutput<TSchema>> {\n readonly type: \"no_field_ref\";\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\nfunction closeOperands<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string,\n fragments: boolean\n): NoFieldRefSchema<TSchema> {\n const standard = wrapped[\"~standard\"];\n const captured = {\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate: standard.validate,\n },\n };\n const schema = createSchema<InferInput<TSchema>, InferOutput<TSchema>>(\n \"no_field_ref\",\n (value) => {\n const inputOperand = findOpaqueOperand(value, fragments);\n if (inputOperand)\n return fail(`${inputOperand} is not supported in ${where}.`);\n const result = validateSchema(captured, value);\n if (result.issues) return result as never;\n const found = findOpaqueOperand(\n (result as { value: unknown }).value,\n fragments\n );\n if (found) {\n return fail(`${found} is not supported in ${where}.`);\n }\n return result as never;\n }\n ) as NoFieldRefSchema<TSchema>;\n\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined ?? false;\n\n return schema;\n}\n\n/**\n * Close a schema to field references only.\n *\n * For the sites whose wrapped schema legitimately holds ARBITRARY DATA — the\n * JSON operand and JSON write data. Only the branded token is looked for there,\n * because it is the only non-value an ordinary document cannot also be: a real\n * `Sql` is a class instance and `v.json` already rejects it as\n * non-JSON-compatible, while a plain `{ strings: […], values: […] }` document\n * that merely LOOKS like a fragment is honest user data and must stay accepted.\n */\nexport function noFieldRef<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, false);\n}\n\n/**\n * Close a schema to field references AND SQL fragments.\n *\n * For the sites whose wrapped schema is a SCALAR FILTER — `having`, where a\n * fragment is refused for the same reason a reference is: whatever it names, it\n * is not the aggregate the group is keyed by. A plain object cannot be a legal\n * scalar operand in the first place, so there is no honest value here for the\n * structural fragment check to misread.\n */\nexport function noOperandExpression<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, true);\n}\n\n/**\n * Exhaustive, cycle-safe search for a field-reference token or an SQL fragment\n * inside an already-validated value; returns how to name the one it found.\n *\n * There is deliberately NO depth cap. An earlier version stopped at four levels\n * on the premise that \"filter values nest at most a couple of levels\" — false\n * on this branch, where scalar `not` nests arbitrarily\n * (`{ not: { not: { … { gt: ref } } } }`, see `buildNegatableFilterSchema`). A\n * five-deep chain therefore walked straight past the guard and emitted the\n * referenced column into HAVING: Postgres rejected the ungrouped column,\n * SQLite/LibSQL accepted it and returned a silently wrong row. A guard that\n * stops looking is accept-and-ignore, which is precisely what this wrapper\n * exists to prevent.\n *\n * Termination comes from structure, not from a budget: every object and array\n * is visited at most once (`seen`), so the walk is linear in the number of\n * distinct nodes the caller already materialized — the same order the\n * `validateSchema` call directly above just spent walking the very same value.\n * The worklist is explicit rather than recursive so a pathologically deep\n * payload cannot overflow the stack here. Binary payloads are skipped whole:\n * bytes cannot be a reference, and `Object.keys` on a typed array would\n * enumerate every index.\n */\nfunction findOpaqueOperand(\n root: unknown,\n fragments: boolean\n): string | undefined {\n // The set of visited objects is made at the second object: most values\n // checked here are one flat object (an `orderBy` term), and a `WeakSet` per\n // check was 5 % of an ordered nested read's validation (2026-11-16).\n let first: object | undefined;\n let seen: WeakSet<object> | undefined;\n const pending: unknown[] = [root];\n\n while (pending.length > 0) {\n const value = pending.pop();\n if (fragments && typeof value === \"function\") return \"A filter callback\";\n if (typeof value !== \"object\" || value === null) continue;\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return `Field reference '${payload.model}.${payload.field}'`;\n }\n if (fragments && isSql(value)) return \"An SQL fragment\";\n if (seen) {\n if (seen.has(value)) continue;\n seen.add(value);\n } else if (first === undefined) first = value;\n else if (value === first) continue;\n else seen = new WeakSet([first, value]);\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) pending.push(item);\n continue;\n }\n\n for (const key of Object.keys(value)) {\n pending.push((value as Record<string, unknown>)[key]);\n }\n }\n\n return undefined;\n}\n\nfunction checkRef(ref: AnyFieldRef, fieldType: ScalarType) {\n const payload = fieldRefPayload(ref);\n if (payload.list) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' is a list field; list fields cannot be used as a comparison operand.`\n );\n }\n if (payload.type !== fieldType) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' is of type '${payload.type}', but a '${fieldType}' operand is required here.`\n );\n }\n return ok(ref) as never;\n}\n","import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// Pipe Schema\n// =============================================================================\n\n/**\n * Transform action interface.\n */\nexport interface TransformAction<TIn, TOut> {\n readonly type: \"transform\";\n readonly transform: (value: TIn) => TOut;\n}\n\n/**\n * Create a transform action for use with pipe.\n *\n * @example\n * const upperCase = v.pipe(v.string(), v.transform(s => s.toUpperCase()));\n */\nexport function transform<TIn, TOut>(\n fn: (value: TIn) => TOut\n): TransformAction<TIn, TOut> {\n return {\n type: \"transform\",\n transform: fn,\n };\n}\n\n/**\n * Pipe action types.\n */\nexport type PipeAction<TIn, TOut> = TransformAction<TIn, TOut>;\n\n/**\n * Pipe schema interface.\n */\nexport interface PipeSchema<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n TInput = InferInput<TSchema>,\n TOutput = TActions extends readonly [...any[], PipeAction<any, infer TLast>]\n ? TLast\n : InferOutput<TSchema>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"pipe\";\n readonly schema: TSchema;\n readonly actions: TActions;\n}\n\n/**\n * Infer the final output type from a chain of actions.\n */\ntype InferPipeOutput<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n> = TActions extends readonly []\n ? InferOutput<TSchema>\n : TActions extends readonly [PipeAction<any, infer TOut>]\n ? TOut\n : TActions extends readonly [PipeAction<any, infer TMid>, ...infer TRest]\n ? TRest extends readonly PipeAction<any, any>[]\n ? InferPipeOutput<VibSchema<TMid, TMid>, TRest>\n : TMid\n : InferOutput<TSchema>;\n\n/**\n * Create a pipe schema that chains a base schema with transform actions.\n *\n * @example\n * const trimmedString = v.pipe(v.string(), v.transform(s => s.trim()));\n * const isoDate = v.pipe(v.date(), v.transform(d => d.toISOString()));\n */\nexport function pipe<\n TSchema extends VibSchema<any, any>,\n const TActions extends readonly PipeAction<any, any>[],\n>(\n schema: TSchema,\n ...actions: TActions\n): PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n> {\n const pipeSchema = createSchema<\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >(\"pipe\", (value) => {\n const result = validateSchema(schema, value);\n if (result.issues) {\n return result as any;\n }\n\n let current: unknown = (result as { value: unknown }).value;\n for (const action of actions) {\n if (action.type === \"transform\") {\n try {\n current = action.transform(current);\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n }\n\n return ok(current as InferPipeOutput<TSchema, TActions>);\n }) as PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >;\n\n (pipeSchema as any).schema = schema;\n (pipeSchema as any).actions = actions;\n\n return pipeSchema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { type GeoPoint, validateGeoPoint } from \"./geo-point-codec\";\nimport { buildSchema } from \"./helpers\";\n\n// =============================================================================\n// GeoPoint Schema ({ longitude: number, latitude: number })\n// =============================================================================\n\nexport interface BasePointSchema<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n > {}\n\nexport interface PointSchema<TInput = GeoPoint, TOutput = GeoPoint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"point\";\n}\n\n/**\n * Create a point schema for EPSG:4326 longitude/latitude coordinates.\n *\n * @example\n * const location = v.point();\n * const optionalPoint = v.point({ optional: true });\n * const pointArray = v.point({ array: true });\n */\nexport function point<\n const Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n>(\n options?: Opts\n): PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>> {\n return buildSchema(\"point\", validateGeoPoint, options) as PointSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n >;\n}\n","import type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Record Schema (dynamic keys)\n// =============================================================================\n\nexport interface RecordSchema<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n TInput = Record<InferInput<TKey>, InferInput<TValue>>,\n TOutput = Record<InferOutput<TKey>, InferOutput<TValue>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"record\";\n readonly key: TKey;\n readonly value: TValue;\n}\n\n/**\n * Create a record schema that validates keys and values.\n *\n * @example\n * const stringRecord = v.record(v.string(), v.number());\n * // Validates: { foo: 1, bar: 2 }\n */\nexport function record<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n>(key: TKey, value: TValue): RecordSchema<TKey, TValue> {\n const schema = createSchema<\n Record<InferInput<TKey>, InferInput<TValue>>,\n Record<InferOutput<TKey>, InferOutput<TValue>>\n >(\"record\", (input) => {\n if (!isRecord(input)) {\n return fail(\n `Expected object, received ${\n Array.isArray(input) ? \"array\" : typeof input\n }`\n );\n }\n\n const output: Record<string, unknown> = {};\n\n for (const [k, v] of Object.entries(input)) {\n const keyResult = validateSchema(key, k);\n if (keyResult.issues) {\n return fail(`Invalid key \"${k}\": ${keyResult.issues[0]!.message}`, [k]);\n }\n\n const valueResult = validateSchema(value, v);\n if (valueResult.issues) {\n const issue = valueResult.issues[0]!;\n // Use concat instead of spread for better performance\n const newPath = issue.path\n ? ([k] as PropertyKey[]).concat(issue.path)\n : [k];\n return fail(issue.message, newPath);\n }\n\n output[(keyResult as { value: string }).value] = (\n valueResult as { value: unknown }\n ).value;\n }\n\n return ok(output as Record<InferOutput<TKey>, InferOutput<TValue>>);\n }) as RecordSchema<TKey, TValue>;\n\n (schema as any).key = key;\n (schema as any).value = value;\n\n return schema;\n}\n\n// =============================================================================\n// FromKeys Schema (static keys with same value schema)\n// =============================================================================\n\n/**\n * Schema entry type - VibSchema or ThunkCast for circular references.\n */\ntype SchemaEntry =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Normalize a schema entry to VibSchema for type extraction.\n */\ntype NormalizeEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\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\n/**\n * Compute entries from a tuple of keys and a schema.\n */\nexport type ComputeEntriesFromKeys<\n TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n> = {\n [K in TKeys[number]]: NormalizeEntry<TSchema>;\n};\n\n/**\n * Options for fromKeys (same as ObjectOptions).\n */\nexport type FromKeysOptions<T = unknown> = ObjectOptions<T>;\n\n/** Project entries for composition without constructing a temporary schema. */\nexport function entriesFromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n>(keys: TKeys, schema: TSchema): ComputeEntriesFromKeys<TKeys, TSchema> {\n const entries: Record<string, SchemaEntry> = {};\n for (const key of keys) {\n entries[key] = schema;\n }\n // Preserve the builder's existing thunk-normalized inference boundary.\n return entries as unknown as ComputeEntriesFromKeys<TKeys, TSchema>;\n}\n\n/**\n * Creates an object schema from an array of keys, all mapping to the same schema.\n * This is a convenient wrapper around `object()` for creating uniform schemas.\n *\n * @param keys - Array of key names (use `as const` for type inference)\n * @param schema - Schema to use for all keys (can be a thunk for circular refs)\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // All keys have the same string schema\n * const schema = v.fromKeys([\"name\", \"email\", \"bio\"] as const, v.string());\n * // → ObjectSchema<{ name: string, email: string, bio: string }>\n *\n * @example\n * // With options\n * const optionalSchema = v.fromKeys(\n * [\"user\", \"post\"] as const,\n * v.number(),\n * { partial: false }\n * );\n * // → ObjectSchema<{ user: number, post: number }> (all required)\n *\n * @example\n * // With thunks for circular references\n * const nodeSchema: VibSchema<any, any> = v.object({ value: v.string() });\n * const schema = v.fromKeys(\n * [\"left\", \"right\"] as const,\n * () => nodeSchema,\n * { optional: true }\n * );\n */\nexport function fromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n const TOpts extends FromKeysOptions | undefined = undefined,\n>(\n keys: TKeys,\n schema: TSchema,\n options?: TOpts\n): ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts> {\n return object(entriesFromKeys(keys, schema), options);\n}\n","import type { VibSchema } from \"../types\";\nimport { createSchema, fail } from \"./helpers\";\n\n/**\n * A key that EXISTS on an object schema but accepts NOTHING.\n *\n * Leaving a key out already rejects it — with `Unknown key: gt`, which reads\n * like a typo. Some keys are absent for a reason worth telling the caller:\n * ordered comparison on an enum cannot answer the same on every provider\n * (see {@link file://../scalars/enum.ts}), `_distance` is only meaningful under\n * a vector order (see {@link file://../model/core/orderby.ts}). Spelling those\n * out as a refusal turns a shrug into an explanation, and keeps the key in the\n * schema where the reason can be read.\n *\n * Input and output are both `never`, so TypeScript refuses the key too —\n * the runtime refusal is the backstop for untyped callers.\n *\n * @param reason - the message the caller sees, stating WHY, not just \"no\"\n */\nexport function refused(reason: string): VibSchema<never, never> {\n return createSchema<never, never>(\"refused\", () => fail(reason));\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// Transform Schema Wrapper\n// =============================================================================\n\n/**\n * Schema that wraps another schema and transforms its output.\n */\nexport interface TransformSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"transform\";\n}\n\n/**\n * Wrap a schema with a transform function.\n * Validates with the wrapped schema, then applies the transform to the output.\n *\n * @param schema - The base schema to validate with\n * @param fn - Transform function: (validatedValue) => newValue\n *\n * @example\n * // String to uppercase\n * const upper = v.coerce(v.string(), s => s.toUpperCase());\n *\n * @example\n * // Parse string to number\n * const parseNum = v.coerce(v.string(), s => parseInt(s, 10));\n * type Out = InferOutput<typeof parseNum>; // number\n *\n * @example\n * // Date to ISO string\n * const isoDate = v.coerce(v.date(), d => d.toISOString());\n * type Out = InferOutput<typeof isoDate>; // string\n *\n * @example\n * // Extract property from object\n * const getName = v.coerce(\n * v.object({ name: v.string(), age: v.number() }),\n * obj => obj.name\n * );\n * type Out = InferOutput<typeof getName>; // string\n */\nexport function coerce<S extends VibSchema<any, any>, TOut>(\n schema: S,\n fn: (value: S[\" vibInferred\"][\"1\"]) => TOut\n): TransformSchema<InferInput<S>, TOut> & { wrapped: S } {\n const transformSchema = createSchema<InferInput<S>, TOut>(\n \"transform\",\n (value): ValidationResult<TOut> => {\n const result = validateSchema(schema, value);\n // The wrapped schema's issues keep their paths: a refusal inside a\n // coerced object names the member that refused.\n if (result.issues) return { issues: result.issues };\n try {\n return ok(fn((result as { value: InferOutput<S> }).value));\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n ) as TransformSchema<InferInput<S>, TOut> & { wrapped: S };\n\n (transformSchema as any).wrapped = schema;\n // Inherit acceptsUndefined from wrapped schema\n (transformSchema as any).acceptsUndefined =\n (schema as any).acceptsUndefined === true;\n\n return transformSchema;\n}\n\n/**\n * Alias for coerce - transform wrapper.\n */\nexport const map = coerce;\n","// Shorthand Coercion Schemas\n// Utilities for coercing simple values to structured objects\n\nimport type { VibSchema } from \"../types\";\nimport { coerce } from \"./transform\";\n\n/**\n * Coerces a value to a filter object with `equals` key.\n * Used for shorthand filter syntax: `\"value\"` -> `{ equals: \"value\" }`\n */\nexport const shorthandFilter = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ equals: val }));\n\n/**\n * Coerces a value to an update object with `set` key.\n * Used for shorthand update syntax: `\"value\"` -> `{ set: \"value\" }`\n */\nexport const shorthandUpdate = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ set: val }));\n\n/**\n * Coerces a single value to an array.\n * Used for shorthand array syntax: `\"value\"` -> `[\"value\"]`\n */\nexport const shorthandArray = <S extends VibSchema>(schema: S) =>\n coerce(\n schema,\n (val: S[\" vibInferred\"][\"1\"]) => [val] as [S[\" vibInferred\"][\"1\"]]\n );\n","import { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n InferInput,\n InferOutput,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail } from \"./helpers\";\n\n// =============================================================================\n// Union Schema\n// =============================================================================\n\nconst ASYNC_REFUSAL: readonly ValidationIssue[] = Object.freeze([\n Object.freeze({ message: \"Async schemas are not supported\" }),\n]);\n\nexport interface UnionSchema<\n TOptions extends readonly VibSchema<any, any>[],\n TInput = TOptions[number][\" vibInferred\"][\"0\"],\n TOutput = InferOutput<TOptions[number]>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"union\";\n readonly options: TOptions;\n}\n\n/**\n * The tag of a TAGGED union: one key at which every member is an object whose\n * entry is a required literal, each a different one. A value carrying one of\n * those literals was written for that member alone.\n */\ninterface Tags {\n readonly key: string;\n readonly members: ReadonlyMap<unknown, VibSchema[\"~standard\"][\"validate\"]>;\n}\n\nfunction tagsOf(options: readonly VibSchema<any, any>[]): Tags | undefined {\n let key: string | undefined;\n const members = new Map<unknown, VibSchema[\"~standard\"][\"validate\"]>();\n for (const option of options) {\n const {\n type,\n entries,\n options: shape,\n } = option as {\n type?: string;\n entries?: Record<string, unknown>;\n options?: { array?: boolean; omit?: readonly string[] };\n };\n if (type !== \"object\" || !entries || shape?.array === true) return;\n key ??= Object.keys(entries).find((name) => isLiteral(entries[name]));\n const tag = key === undefined ? undefined : entries[key];\n if (!(isLiteral(tag) && tag.acceptsUndefined !== true)) return;\n if (members.has(tag.value) || shape?.omit?.includes(key!)) return;\n members.set(tag.value, option[\"~standard\"].validate);\n }\n return key === undefined || members.size < 2 ? undefined : { key, members };\n}\n\nfunction isLiteral(\n entry: unknown\n): entry is { type: \"literal\"; value: unknown; acceptsUndefined?: boolean } {\n return isRecord(entry) && entry.type === \"literal\";\n}\n\n/**\n * Does `option` refuse every value but a boolean, reading nothing of it? A\n * `v.boolean()` without options (`validateBoolean`), or a `v.coerce` of one,\n * whose transform never runs on a refusal (`transform.ts`).\n */\nfunction takesBooleansAlone(option: object): boolean {\n const type = Reflect.get(option, \"type\");\n if (type === \"transform\") {\n const wrapped: unknown = Reflect.get(option, \"wrapped\");\n return isRecord(wrapped) && takesBooleansAlone(wrapped);\n }\n return type === \"boolean\" && Reflect.get(option, \"options\") === undefined;\n}\n\ntype MemberResult = ReturnType<VibSchema[\"~standard\"][\"validate\"]>;\n\n/** A member's result, an async member's promise being a refusal. */\nfunction settled<T>(result: MemberResult): ValidationResult<T> {\n if (!(\"then\" in result)) return result as ValidationResult<T>;\n discardAsyncValidationResult(result);\n return { issues: ASYNC_REFUSAL };\n}\n\n/** A member's first issue, spelled with its path for a refusal that lists several. */\nfunction describe({ message, path }: ValidationIssue): string {\n return path?.length ? `${path.join(\".\")}: ${message}` : message;\n}\n\n/**\n * Create a union schema that validates against multiple options.\n * Returns the result of the first matching schema.\n *\n * A refusal names the member the value was written for. In a tagged union\n * (every member an object with its own literal at one key) that is the member\n * its tag names, and only that member runs. Otherwise it is the member whose\n * first issue reads DEEPEST into the value (`{ gt: \"3\" }` is refused at `gt`\n * by the operator object, not at the root by the shorthand). Members that\n * refused equally deep leave no such member, and the refusal lists what each\n * one said, once (one issue, path kept, when they all said the same).\n *\n * @example\n * const stringOrNumber = v.union([v.string(), v.number()]);\n */\nexport function union<const TOptions extends readonly VibSchema<any, any>[]>(\n options: TOptions\n): UnionSchema<TOptions> {\n const validators = options.map((option) => option[\"~standard\"].validate);\n // Read on first use: a union nothing validates through never inspects its\n // members. Members whose entries are still unresolved thunks then read as\n // untagged for good, and the depth rule alone names the member.\n let tags: Tags | undefined | null = null;\n // Which members take booleans alone, read on first use like `tags`;\n // `undefined` when none does.\n let booleansOnly: readonly boolean[] | undefined | null = null;\n const schema = createSchema<\n InferInput<TOptions[number]>,\n InferOutput<TOptions[number]>\n >(\"union\", (value) => {\n if (tags === null) tags = tagsOf(options);\n const tagged = tags && isRecord(value) && tags.members.get(value[tags.key]);\n if (tagged) return settled<InferOutput<TOptions[number]>>(tagged(value));\n // A member that takes booleans alone refuses any other value without\n // reading it, so it is asked last, and only if no member matches: a\n // relation node written as an object skipped its `true` arm's refusal,\n // 9 % of a three-level include's validation (2026-11-16). Its refusal is\n // then weighed in its own place, so the union refuses as before.\n if (booleansOnly === null) {\n const marks = options.map(takesBooleansAlone);\n booleansOnly = marks.includes(true) ? marks : undefined;\n }\n const skipped = typeof value === \"boolean\" ? undefined : booleansOnly;\n let refused: (readonly ValidationIssue[] | undefined)[] | undefined;\n if (skipped) {\n for (let at = 0; at < validators.length; at++) {\n if (skipped[at]) continue;\n const result = settled<InferOutput<TOptions[number]>>(\n validators[at]!(value)\n );\n if (!result.issues) return result;\n (refused ??= [])[at] = result.issues;\n }\n }\n // Success returns the matching member's result as-is. Nothing about a\n // refusal is allocated until a second member refuses as deep as the first,\n // so the common \"first member misses, second matches\" pattern stays free.\n let deepest: readonly ValidationIssue[] | undefined;\n let depth = -1;\n let tied: string[] | undefined;\n\n for (let at = 0; at < validators.length; at++) {\n const result =\n skipped && !skipped[at]\n ? { issues: refused![at]! }\n : settled<InferOutput<TOptions[number]>>(validators[at]!(value));\n if (!result.issues) return result;\n const { issues } = result;\n const reach = issues[0]!.path?.length ?? 0;\n if (reach > depth) {\n deepest = issues;\n depth = reach;\n tied = undefined;\n } else if (reach === depth) {\n const said = describe(issues[0]!);\n tied ??= [describe(deepest![0]!)];\n if (!tied.includes(said)) tied.push(said);\n }\n }\n\n if (tied && tied.length > 1) return fail(tied.join(\", or \"));\n return deepest\n ? { issues: deepest }\n : fail(\"Expected no value: the union has no member\");\n }) as UnionSchema<TOptions>;\n\n (schema as any).options = options;\n\n return schema;\n}\n","// Single or Array Schema\n// Accepts either a single value or an array of values, normalizes to array\n\nimport type { VibSchema } from \"../types\";\nimport { array } from \"./array\";\nimport { coerce } from \"./transform\";\nimport { union } from \"./union\";\n\n/**\n * Creates a schema that accepts either a single value or an array of values.\n * Single values are coerced to a single-element array for consistent output.\n *\n * @example\n * const schema = v.singleOrArray(v.string());\n * // Accepts: \"foo\" -> [\"foo\"]\n * // Accepts: [\"foo\", \"bar\"] -> [\"foo\", \"bar\"]\n */\nexport const singleOrArray = <S extends VibSchema>(schema: S) => {\n return union([\n coerce(schema, (v: S[\" vibInferred\"][\"1\"]) => [v]),\n array(schema),\n ]);\n};\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// String Schema\n// =============================================================================\nexport interface StringSchema<TInput = string, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"string\";\n}\n\n// Pre-computed error for fast path (avoid allocation on error)\nconst STRING_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected string\" })]),\n});\n\n/**\n * Validate that a value is a string.\n */\nfunction validateString(value: unknown) {\n return isString(value) ? ok(value) : STRING_ERROR;\n}\n\n/**\n * Create a string schema.\n *\n * @example\n * const name = v.string();\n * const optionalName = v.string({ optional: true });\n * const tags = v.string({ array: true });\n */\nexport function string(): StringSchema<string, string>;\nexport function string<const Opts extends ScalarOptions<string, any>>(\n options: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\nexport function string<\n const Opts extends ScalarOptions<string, any> | undefined,\n>(\n options?: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>> {\n return buildSchema(\"string\", validateString, options) as StringSchema<\n ComputeInput<string, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateString };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isNumber } from \"../value-guards\";\nimport { buildSchema, fail, ok } from \"./helpers\";\n\n// =============================================================================\n// Vector Schema (array of numbers for embeddings/ML)\n// =============================================================================\n\nexport interface BaseVectorSchema<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > {}\n\nexport interface VectorSchema<TInput = number[], TOutput = number[]>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"vector\";\n}\n\n// Pre-computed error for fast path\nconst NOT_ARRAY_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected array of numbers\" }),\n ]),\n});\n\n/**\n * Validate that a value is a vector (array of numbers).\n * Optionally check for specific dimensions.\n */\nfunction createVectorValidator(dimensions?: number) {\n // Pre-compute dimension error if applicable\n const dimensionError =\n dimensions !== undefined\n ? Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected vector of ${dimensions} dimensions`,\n }),\n ]),\n })\n : null;\n\n return (value: unknown) => {\n if (!Array.isArray(value)) return NOT_ARRAY_ERROR;\n\n const len = value.length;\n for (let i = 0; i < len; i++) {\n if (!(isNumber(value[i]) && Number.isFinite(value[i]))) {\n return fail(`Expected finite number at index ${i}`);\n }\n }\n\n if (dimensionError && len !== dimensions) return dimensionError;\n\n return ok(value as number[]);\n };\n}\n\n/**\n * Create a vector schema for arrays of numbers (embeddings, coordinates, etc.)\n *\n * @param dimensions - Optional fixed number of dimensions\n * @param options - Schema options\n *\n * @example\n * const embedding = v.vector(); // Any length\n * const embedding3d = v.vector(3); // Exactly 3 dimensions\n * const optionalVector = v.vector(undefined, { optional: true });\n */\nexport function vector<\n const Opts extends ScalarOptions<number[], any> | undefined = undefined,\n>(\n dimensions?: number,\n options?: Opts\n): VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>> & {\n dimensions?: number;\n} {\n const baseValidate = createVectorValidator(dimensions);\n return buildSchema(\"vector\", baseValidate, options, {\n dimensions,\n }) as VectorSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > & { dimensions?: number };\n}\n\n// Export validator for reuse\nexport { createVectorValidator as validateVector };\n","// =============================================================================\n// VibORM Validation - Runtime and Type-Level Namespace\n// =============================================================================\n\nimport type { JsonNullKind } from \"@schema/json-null\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport type {\n ComputeInput,\n ComputeOutput,\n InferInput,\n InferOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport type { ArraySchema } from \"./array\";\nimport { array } from \"./array\";\nimport type { BigIntSchema } from \"./bigint\";\nimport { bigint } from \"./bigint\";\nimport type { BlobSchema } from \"./blob\";\nimport { blob } from \"./blob\";\nimport type { BooleanSchema } from \"./boolean\";\nimport { boolean } from \"./boolean\";\nimport type { DateSchema } from \"./date\";\nimport { date } from \"./date\";\nimport type {\n DecimalComputeInput,\n DecimalComputeOutput,\n DecimalOptions,\n DecimalSchema,\n} from \"./decimal\";\nimport { decimal } from \"./decimal\";\nimport type { EnumSchema } from \"./enum\";\nimport { enum_ } from \"./enum\";\nimport type { ComputeEntriesFromObject } from \"./from-object\";\nimport { fromObject } from \"./from-object\";\nimport type { GeoPoint } from \"./geo-point-codec\";\nimport type { IsoDateSchema, IsoTimeSchema, IsoTimestampSchema } from \"./iso\";\nimport { isoDate, isoTime, isoTimestamp } from \"./iso\";\nimport type { JsonInput, JsonSchema, JsonValue } from \"./json\";\nimport { json } from \"./json\";\nimport type { JsonNullOrSchema, JsonWriteSchema } from \"./json-null\";\nimport { jsonNullOr, jsonWrite } from \"./json-null\";\nimport { lazy, lazyRef } from \"./lazy\";\nimport type { LiteralSchema, LiteralValue } from \"./literal\";\nimport { literal } from \"./literal\";\nimport type { NullableSchema } from \"./nullable\";\nimport { maybeNullable, nullable } from \"./nullable\";\nimport type { IntegerSchema, NumberSchema } from \"./number\";\nimport { integer, number } from \"./number\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n OmittedObjectSchema,\n} from \"./object\";\nimport { object } from \"./object\";\nimport { omit } from \"./omit\";\nimport type {\n ComparisonOperandSchema,\n FieldRefOrSchema,\n NoFieldRefSchema,\n OperandCtx,\n} from \"./operand\";\nimport {\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n} from \"./operand\";\nimport type { OptionalSchema, WrappableSchema } from \"./optional\";\nimport { optional } from \"./optional\";\nimport type { PipeAction, PipeSchema } from \"./pipe\";\nimport { pipe, transform as transformAction } from \"./pipe\";\nimport type { PointSchema } from \"./point\";\nimport { point } from \"./point\";\nimport type { ComputeEntriesFromKeys, RecordSchema } from \"./record\";\nimport { fromKeys, record } from \"./record\";\nimport { refused } from \"./refused\";\nimport { shorthandArray, shorthandFilter, shorthandUpdate } from \"./shorthand\";\nimport { singleOrArray } from \"./single-or-array\";\nimport type { StringSchema } from \"./string\";\nimport { string } from \"./string\";\nimport type { TransformSchema } from \"./transform\";\nimport { coerce, map } from \"./transform\";\nimport type { UnionSchema } from \"./union\";\nimport { union } from \"./union\";\nimport type { VectorSchema } from \"./vector\";\nimport { vector } from \"./vector\";\n\ntype OmitOptions<\n TOptions extends ObjectOptions | undefined,\n TKeys extends readonly PropertyKey[] | undefined,\n> = (TOptions extends ObjectOptions ? Omit<TOptions, \"omit\"> : object) & {\n omit: TKeys;\n};\n\n// =============================================================================\n// Runtime Namespace (v.string(), v.number(), etc.)\n// =============================================================================\n\n/**\n * VibORM validation namespace.\n *\n * @example\n * import { v } from \"viborm/validation\";\n *\n * const user = v.object({\n * name: v.string(),\n * age: v.number({ optional: true }),\n * email: v.string(),\n * createdAt: v.date(),\n * });\n *\n * // Circular references use thunks\n * const node = v.object({\n * value: v.string(),\n * parent: () => node, // Thunk for self-reference\n * });\n */\nexport const v = {\n // Scalars\n string,\n number,\n integer,\n boolean,\n bigint,\n decimal,\n literal,\n enum: enum_,\n json,\n // Date & Time\n date,\n isoTimestamp,\n isoDate,\n isoTime,\n // Blob, Vector, Point\n blob,\n vector,\n point,\n // Wrappers\n array,\n nullable,\n maybeNullable,\n optional,\n // Objects\n object,\n omit,\n fromObject,\n // Composition\n union,\n pipe,\n transformAction,\n record,\n fromKeys,\n // Transform wrappers\n coerce,\n map,\n // Lazy evaluation\n lazy,\n lazyRef,\n // Single or array\n singleOrArray,\n // Shorthand coercions\n shorthandFilter,\n shorthandUpdate,\n shorthandArray,\n // Comparison operands: field references (Prisma FieldRef parity), SQL\n // fragments, and the callback that sugars both\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n // JSON null sentinels (Prisma DbNull/JsonNull/AnyNull parity)\n jsonNullOr,\n jsonWrite,\n // Keys that exist only to explain why they are refused\n refused,\n} as const;\n\nexport default v;\n\n// =============================================================================\n// Type-Level Namespace (V.String, V.Number, etc.)\n// =============================================================================\n\n/**\n * V Namespace - Type-level schema constructors for explicit type annotations.\n *\n * These mirror the runtime v.* functions but produce types directly without\n * needing to serialize the full schema structure in .d.ts files.\n *\n * @example\n * ```typescript\n * // In a .d.ts file:\n * import type { V } from \"@validation\";\n *\n * export type UserSchema = V.Object<{\n * id: V.String;\n * name: V.String<{ optional: true }>;\n * age: V.Number;\n * }>;\n * ```\n */\nexport namespace V {\n // =========================================================================\n // Scalar Types\n // =========================================================================\n\n /**\n * Type-level string schema.\n * @example V.String - Required string\n * @example V.String<{ optional: true }> - Optional string\n * @example V.String<{ nullable: true }> - Nullable string\n * @example V.String<{ array: true }> - Array of strings\n */\n export type String<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\n\n /**\n * Type-level number schema.\n * @example V.Number - Required number\n * @example V.Number<{ optional: true }> - Optional number\n */\n export type Number<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level integer schema.\n */\n export type Integer<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level decimal schema. Input and output differ on purpose: a decimal\n * accepts `Decimal | string` and validates to the canonical private\n * string every identity owner keys on. The public `Decimal` result is built\n * once per selected value at the typed result boundary, not here.\n * @example V.Decimal - Required decimal\n * @example V.Decimal<{ nullable: true }> - Nullable decimal\n * @example V.Decimal<{ decimal: { precision: 10; scale: 2 } }> - A declared domain\n */\n export type Decimal<\n Opts extends DecimalOptions<any> | undefined = undefined,\n > = DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\n\n /**\n * Type-level boolean schema.\n */\n export type Boolean<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n > = BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\n\n /**\n * Type-level bigint schema.\n */\n export type BigInt<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n > = BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>>;\n\n // =========================================================================\n // Date & Time Types\n // =========================================================================\n\n /**\n * Type-level Date schema (JavaScript Date object).\n */\n export type Date<\n Opts extends ScalarOptions<globalThis.Date, any> | undefined = undefined,\n > = DateSchema<\n ComputeInput<globalThis.Date, Opts>,\n ComputeOutput<globalThis.Date, Opts>\n >;\n\n /**\n * Type-level ISO timestamp schema (accepts string | Date, outputs string).\n */\n export type IsoTimestamp<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimestampSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO date schema (accepts string | Date, outputs string YYYY-MM-DD).\n */\n export type IsoDate<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoDateSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO time schema (accepts string | Date, outputs string HH:MM:SS).\n */\n export type IsoTime<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimeSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n // =========================================================================\n // Special Types\n // =========================================================================\n\n /**\n * Type-level JSON schema.\n */\n export type Json<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n > = JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>>;\n\n /**\n * Type-level blob schema (Uint8Array or Buffer-like).\n */\n export type Blob<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n > = BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n\n /**\n * Type-level vector schema (number array for embeddings).\n */\n export type Vector<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n > = VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>>;\n\n /**\n * Type-level point schema (geographic coordinates).\n */\n export type Point<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n > = PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>>;\n\n // =========================================================================\n // Composition Types\n // =========================================================================\n\n /**\n * Type-level object schema.\n * @example V.Object<{ name: V.String; age: V.Number }>\n * @example V.Object<{ name: V.String }, { partial: false }> - All required\n */\n export type Object<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<TEntries, TOpts>;\n\n /**\n * Type-level omit schema - creates a new object schema with keys removed.\n * @example V.Omit<UserSchema, [\"password\"]> - User without password field\n */\n export type Omit<\n TSchema extends ObjectSchema<any, any>,\n TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n > = OmittedObjectSchema<\n TSchema[\"entries\"],\n OmitOptions<TSchema[\"options\"], TKeys>,\n TKeys\n >;\n\n /**\n * Type-level from object schema.\n * @example V.FromObject<{ name: V.String }, \"name\"> - Object with name field\n */\n export type FromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromObject<TObject, TPath>, TOpts>;\n\n export type FromKeys<\n TKeys extends string[],\n TSchema extends VibSchema<any, any>,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts>;\n\n /**\n * Type-level array schema.\n * @example V.Array<V.String> - Array of strings\n */\n export type Array<TItem extends VibSchema<any, any>> = ArraySchema<TItem>;\n\n /**\n * Type-level union schema.\n * @example V.Union<[V.String, V.Number]>\n */\n export type Union<TOptions extends readonly VibSchema<any, any>[]> =\n UnionSchema<TOptions>;\n\n /**\n * Type-level enum schema.\n * @example V.Enum<[\"active\", \"inactive\", \"pending\"]>\n */\n export type Enum<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n > = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n /**\n * Type-level literal schema.\n * @example V.Literal<\"active\">\n */\n export type Literal<TValue extends LiteralValue> = LiteralSchema<TValue>;\n\n /**\n * Type-level record schema (dictionary with uniform value type).\n * @example V.Record<V.String, V.Number>\n */\n export type VRecord<\n TKey extends VibSchema<any, string>,\n TValue extends VibSchema<any, any>,\n > = RecordSchema<TKey, TValue>;\n\n // =========================================================================\n // Wrapper Types\n // =========================================================================\n\n /**\n * Type-level optional schema.\n * @example V.Optional<V.String> - string | undefined\n */\n export type Optional<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n > = OptionalSchema<TWrapped, TDefault>;\n\n /**\n * Type-level nullable schema.\n * @example V.Nullable<V.String> - string | null\n */\n export type Nullable<TWrapped extends VibSchema<any, any>> =\n NullableSchema<TWrapped>;\n\n export type MaybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n > = TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped;\n\n // =========================================================================\n // Transform Types\n // =========================================================================\n\n /**\n * Type-level transform schema.\n * @example V.Transform<string, number> - transforms string input to number output\n */\n export type Transform<TInput, TOutput> = TransformSchema<TInput, TOutput>;\n\n /**\n * Type-level pipe schema for chaining validations.\n * @example V.Pipe<V.String, [TrimAction, LowercaseAction]>\n */\n export type Pipe<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n > = PipeSchema<TSchema, TActions>;\n\n export type Coerce<\n TWrapped extends VibSchema<any, any>,\n TOutput,\n > = TransformSchema<InferInput<TWrapped>, TOutput> & { wrapped: TWrapped };\n\n export type ShorthandFilter<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { equals: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandUpdate<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { set: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandArray<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n [TWrapped[\" vibInferred\"][\"1\"]]\n >;\n\n /**\n * Type-level comparison operand that also accepts a field reference of the\n * given scalar type.\n * @example V.FieldRefOr<\"int\", V.Integer>\n */\n export type FieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n > = FieldRefOrSchema<TType, TSchema>;\n\n /**\n * Type-level comparison operand: the value, a field reference of the given\n * scalar type, an SQL fragment, or a callback returning one of the latter two\n * from `TCtx` — the context of the model being filtered.\n * @example V.ComparisonOperand<\"int\", V.Integer, V.OperandCtx<typeof post>>\n */\n export type ComparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends OperandCtx<any> = OperandCtx<any>,\n > = ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n /**\n * Type-level operand callback context: `{ fields, sql }` keyed to the scalars\n * of the model being filtered.\n */\n export type Operand<TModel> = OperandCtx<TModel>;\n\n /**\n * Type-level re-closing wrapper: same shape as the wrapped schema, but a\n * field reference anywhere inside the parsed value is rejected.\n */\n export type NoFieldRef<TSchema extends VibSchema<any, any>> =\n NoFieldRefSchema<TSchema>;\n\n /**\n * Type-level JSON filter operand that also accepts the named JSON null\n * sentinels (`DbNull` / `JsonNull` / `AnyNull`).\n * @example V.JsonNullOr<\"DbNull\" | \"JsonNull\" | \"AnyNull\", V.Json>\n */\n export type JsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonNullOrSchema<TAllowed, TSchema>;\n\n /**\n * Type-level JSON write slot: the sentinels in `TAllowed`, the whole JSON\n * document language, and no bare top-level `null` (Prisma's rule).\n */\n export type JsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonWriteSchema<TAllowed, TSchema>;\n\n export type SingleOrArray<TWrapped extends VibSchema<any, any>> = V.Union<\n readonly [\n V.Coerce<TWrapped, [TWrapped[\" vibInferred\"][\"1\"]]>,\n V.Array<TWrapped>,\n ]\n >;\n\n // =========================================================================\n // Utility Types\n // =========================================================================\n\n /**\n * Extract input type from a V.* type or VibSchema.\n */\n export type Input<T> = InferInput<T>;\n\n /**\n * Extract output type from a V.* type or VibSchema.\n */\n export type Output<T> = InferOutput<T>;\n\n /**\n * Any VibSchema - useful for generic constraints.\n */\n export type Schema<TInput = unknown, TOutput = TInput> = VibSchema<\n TInput,\n TOutput\n >;\n}\n","// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","// Shared immutable-terminal machinery: the construction-time refusal vocabulary\n// and the source-independent target once-cell.\n//\n// Every structurally knowable fact about a declaration is decided HERE or in the\n// factory/modifier that owns it, before the value enters trusted relation state.\n// Facts that need the schema graph — is the settled return a registered model,\n// which endpoint owns the foreign key, does the pair exist — belong to the\n// full-schema relation resolver and are deliberately absent.\n\nimport { ValidationError } from \"@errors\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type {\n JunctionReferentialAction,\n JunctionSideActions,\n NonEmptyFieldTuple,\n ReferentialAction,\n} from \"./types\";\n\n/** The builder label carried by every construction-time refusal. */\nexport type RelationBuilder = \"s.toOne\" | \"s.toMany\" | \"s.model\";\n\n/**\n * The one construction-time refusal. Structural input the factories and\n * modifiers can judge on their own never reaches the schema resolver as a\n * `SchemaValidationIssue`; it fails here, at the call the author wrote.\n */\nexport function refuseRelationInput(\n builder: RelationBuilder,\n path: string,\n message: string,\n cause?: Error\n): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path },\n [{ path, message }],\n cause === undefined ? undefined : { cause }\n );\n}\n\n// =============================================================================\n// PLAIN-RECORD READS\n// =============================================================================\n\n/**\n * A caller-supplied map is a variant declaration only when it is a plain\n * record: a hostile prototype would otherwise smuggle inherited entries past\n * own-key enumeration into schema truth.\n */\nexport function isPlainRecord(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Own ENUMERABLE string keys — the declaration surface of a record. Symbol keys\n * and inherited entries are not declarations, and neither is an own key hidden\n * behind `enumerable: false`.\n */\nexport function declaredKeys(record: Record<string, unknown>): string[] {\n return Object.keys(record);\n}\n\n/** Exactly these keys, in any order. */\nexport function hasExactKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n return (\n actual.length === expected.length &&\n expected.every((key) => actual.includes(key))\n );\n}\n\n/**\n * Read one caller-owned property exactly once. Accessors are executable input:\n * when one throws, the declaration boundary owns the V4002 refusal and keeps a\n * normalized cause instead of leaking the caller's thrown value.\n */\nexport function readCallerProperty(\n builder: RelationBuilder,\n record: Record<string, unknown>,\n property: string,\n path: string\n): unknown {\n try {\n return Reflect.get(record, property);\n } catch (thrown) {\n refuseRelationInput(\n builder,\n path,\n `Could not read relation input '${path}'`,\n normalizeThrown(\n thrown,\n `Reading relation input '${path}' threw a non-Error value`\n )\n );\n }\n}\n\n// =============================================================================\n// MODIFIER TOKENS\n// =============================================================================\n\n/**\n * A relation name is a non-empty PAIRING LABEL, not a SQL identifier: an\n * explicit `.through(...)` lets `\"Post tags/v2\"` name a pair without pretending\n * the label is a database name.\n */\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || name.length === 0) {\n refuseRelationInput(\n builder,\n \"name\",\n \"A relation name must be a non-empty string\"\n );\n }\n return name;\n}\n\nexport function normalizeReferentialAction(\n path: string,\n action: unknown\n): ReferentialAction {\n if (\n action === \"cascade\" ||\n action === \"setNull\" ||\n action === \"restrict\" ||\n action === \"noAction\"\n ) {\n return action;\n }\n refuseRelationInput(\n \"s.toOne\",\n path,\n \"A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'\"\n );\n}\n\n/** Junction actions exclude `setNull` at the type level and here. */\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\n \"s.toMany\",\n path,\n \"A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member\"\n );\n}\n\n/**\n * The ONE normalization of a junction action declaration. A bare action is the\n * symmetric shorthand and becomes the same pair a `{ source, target }` map\n * spells, so trusted state holds one form and no consumer asks which spelling\n * declared it. The map names both sides and nothing else: an omitted side\n * would silently keep a default the author never chose. Every object is read\n * as a map, so an array or a class instance is told what a map must be rather\n * than which actions exist.\n */\nexport function normalizeJunctionActions(\n path: \"onDelete\" | \"onUpdate\",\n declared: unknown\n): JunctionSideActions {\n if (typeof declared !== \"object\" || declared === null) {\n const action = normalizeJunctionAction(path, declared);\n return Object.freeze({ source: action, target: action });\n }\n if (\n !(\n isPlainRecord(declared) &&\n hasExactKeys(declaredKeys(declared), [\"source\", \"target\"])\n )\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `A junction '${path}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`\n );\n }\n const side = (name: \"source\" | \"target\"): JunctionReferentialAction =>\n normalizeJunctionAction(\n `${path}.${name}`,\n readCallerProperty(\"s.toMany\", declared, name, `${path}.${name}`)\n );\n return Object.freeze({ source: side(\"source\"), target: side(\"target\") });\n}\n\n/** One junction table name or side naming token. */\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Junction '${path}' must be a valid schema identifier`\n );\n }\n return token;\n}\n\n/** A non-empty foreign-key tuple whose members are distinct. */\nexport function normalizeFieldTuple(\n builder: RelationBuilder,\n path: string,\n fields: readonly string[]\n): NonEmptyFieldTuple {\n const [head, ...rest] = fields;\n if (head === undefined) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' requires at least one field key`\n );\n }\n if (new Set(fields).size !== fields.length) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' cannot repeat a field key in one foreign-key tuple`\n );\n }\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget =\n | { readonly settled: \"value\"; readonly value: unknown }\n | { readonly settled: \"error\"; readonly error: Error };\n\n/**\n * The declaration-lifetime target cell.\n *\n * A raw getter stays lazy, but it is invoked at most ONCE per target: the first\n * resolution settles its return or one normalized `Error`, and every later\n * consumer — including a second schema graph reusing the same immutable\n * terminal — observes that same outcome. A resolver-local cache alone would let\n * a stateful getter give validation, migrations and the query engine different\n * declaration truth.\n *\n * Only settled outcomes live here. The resolver decides whether a return is a\n * registered model and attaches its own model/field path to any issue, so\n * contextual diagnostics are never cached on the shared terminal.\n */\nexport function createTargetSettlement(\n readGetter: (variantKey: string | undefined) => unknown\n): (variantKey?: string) => unknown {\n const cells = new Map<string, SettledTarget>();\n return (variantKey?: string): unknown => {\n const cellKey = variantKey ?? \"\";\n let cell = cells.get(cellKey);\n if (cell === undefined) {\n cell = settleTargetOnce(readGetter, variantKey);\n cells.set(cellKey, cell);\n }\n if (cell.settled === \"value\") return cell.value;\n throw cell.error;\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n // READING the getter cannot fail: every `readGetter` handed to\n // {@link createTargetSettlement} is one property read over frozen\n // declaration state. INVOKING it can, and that is the one `try` below.\n const getter = readGetter(variantKey);\n // The read still may not produce one: a variant asked without a key or with\n // an unknown one has no entry, and a forged state can carry a non-function\n // target where the factories admit only a getter. Settling that as a failure\n // is what keeps every later consumer from re-reading a target that can never\n // resolve — and from reading `undefined` as a resolved one.\n if (typeof getter !== \"function\") {\n return {\n settled: \"error\",\n error: new Error(\"Relation target getter is not a function\"),\n };\n }\n try {\n return { settled: \"value\", value: getter() };\n } catch (thrown) {\n return {\n settled: \"error\",\n error: normalizeThrown(\n thrown,\n \"Relation target getter threw a non-Error value\"\n ),\n };\n }\n}\n\n/**\n * One normalization, owned here: a thrown `Error` keeps its identity across\n * every consumer, and a non-Error throw becomes exactly one `Error` that every\n * consumer then shares.\n */\nfunction normalizeThrown(thrown: unknown, nonErrorPrefix: string): Error {\n if (thrown instanceof Error) return thrown;\n let rendered: string;\n try {\n rendered = typeof thrown === \"symbol\" ? thrown.toString() : String(thrown);\n } catch {\n rendered = \"<unrenderable non-Error value>\";\n }\n return new Error(`${nonErrorPrefix}: ${rendered}`);\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it. `$through` is a selection's own key too, refused at runtime as\n * no identifier (F001); this names the reason a caller would otherwise guess at.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n readonly $through?: \"`$through` is reserved for a relation's link row (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n /** Indexes in the database's own language: see {@link Model.rawIndex}. */\n readonly rawIndexes: readonly RawIndexDefinition[];\n /** SQLite clusters the table by its primary key: see {@link Model.withoutRowid}. */\n readonly withoutRowid: boolean;\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\n/**\n * One index per dialect, written in that database's own language, for what the\n * index declaration cannot say (pgvector's HNSW, SurrealDB's HNSW, an expression).\n * Each text is a template: `{name}`, `{table}` and `{<field>}` become the driver's\n * escaped identifiers, the table qualified by the bound namespace. A dialect\n * without a text has no such index.\n */\nexport interface RawIndexTemplates {\n pg?: string;\n mysql?: string;\n sqlite?: string;\n surrealdb?: string;\n}\n\nexport interface RawIndexDefinition {\n readonly name: string;\n readonly templates: Readonly<RawIndexTemplates>;\n}\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n /**\n * An index the declaration cannot say, in each database's own language, which\n * migrations create, recognize and recreate when its text changes. It is never a\n * key and never covers a foreign key.\n */\n rawIndex(name: string, templates: RawIndexTemplates): Model<State> {\n // The migration that renders a template is what checks it. The list rides\n // the state object, so every builder's spread carries it, but not its type:\n // every state type maps over ModelState's keys, per model.\n const state = {\n ...this.#state,\n rawIndexes: [\n ...this[\"~\"].rawIndexes,\n { name, templates: { ...templates } },\n ],\n };\n return new Model<State>(state);\n }\n\n /**\n * On SQLite, a `WITHOUT ROWID` table: rows are stored in the primary key's\n * order, with no hidden rowid. Migrations create, recreate and verify it\n * so; other databases ignore it. A key generated by `.increment()` refuses\n * it (SQLite has no AUTOINCREMENT without a rowid).\n */\n withoutRowid(): Model<State> {\n // Held beside the typed state, as `rawIndex` is: see there.\n return new Model<State>({ ...this.#state, withoutRowid: true });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n get rawIndexes(): readonly RawIndexDefinition[] {\n // Held beside the typed state: see Model.rawIndex.\n return (\n (model.#state as { rawIndexes?: readonly RawIndexDefinition[] })\n .rawIndexes ?? []\n );\n },\n get withoutRowid(): boolean {\n return (model.#state as { withoutRowid?: true }).withoutRowid === true;\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n","import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\nimport type { NativeTypeDeclaration } from \"./native-types\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n\n// =============================================================================\n// THE CHAIN EVERY SCALAR SHARES\n// =============================================================================\n\n/** The scalar a modifier answers: this one's state with what the modifier changes. */\nexport const next = (\n scalar: ScalarChain,\n update: Partial<ScalarState>,\n rebuilt = false\n) => {\n const state = { ...scalar.state, ...update };\n // The base validator follows from the state: no modifier builds it itself.\n if (rebuilt) state.base = scalar.rebase(state);\n // The scalar a modifier answers is of the class that says how its base is\n // built, whatever the receiver is an instance of: a subclass's constructor\n // is not asked to carry a state it may not take.\n let concrete = Object.getPrototypeOf(scalar);\n while (!Object.hasOwn(concrete, \"rebase\"))\n concrete = Object.getPrototypeOf(concrete);\n return new concrete.constructor(state, scalar._nativeType);\n};\n\n/**\n * The modifiers every scalar has, written once. Each scalar class types them\n * for its own state and says how its base validator is built from a state.\n */\nabstract class ScalarChain {\n readonly state: ScalarState;\n readonly _nativeType?: NativeTypeDeclaration | undefined;\n #internal?: {\n state: ScalarState;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n constructor(state: ScalarState, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n abstract rebase(state: ScalarState): VibSchema;\n nullable() {\n return next(\n this,\n {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n },\n true\n );\n }\n default(value: unknown) {\n return next(this, { hasDefault: true, default: value, optional: true });\n }\n map(columnName: string) {\n return next(this, { columnName });\n }\n get [\"~\"]() {\n return (this.#internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\n/** The chain of a scalar that can be a list. */\nabstract class ListScalarChain extends ScalarChain {\n array() {\n return next(this, { array: true }, true);\n }\n}\n\n/** The chain of a scalar that can be a key and can carry a custom schema. */\nexport abstract class KeyedScalarChain extends ListScalarChain {\n id() {\n return next(this, { isId: true, isUnique: true });\n }\n unique() {\n return next(this, { isUnique: true });\n }\n schema(schema: StandardSchemaV1<any, any>) {\n return next(this, { schema }, true);\n }\n}\n\n/**\n * A chain as a scalar class extends it. The class types the members for its\n * own state; what it inherits here is one type for every scalar and state,\n * so a schema's fields cost a consumer's compiler nothing more.\n */\nexport declare abstract class TypedScalarChain {\n /** The base validator of a scalar in this state. */\n protected abstract rebase(state: any): VibSchema;\n}\ntype Chain = abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n) => TypedScalarChain;\n/**\n * The list chain with its members left untyped, for a class that types them\n * as methods of its own and hands their work back with `super`.\n */\nexport declare abstract class UntypedScalarChain extends TypedScalarChain {\n nullable(): unknown;\n array(): unknown;\n default(value: unknown): unknown;\n map(columnName: string): unknown;\n}\nexport const untypedListScalarChain =\n ListScalarChain as unknown as abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n ) => UntypedScalarChain;\n/** The keyed chain, untyped in the same way. */\nexport declare abstract class UntypedKeyedScalarChain extends UntypedScalarChain {\n id(): unknown;\n unique(): unknown;\n schema(schema: StandardSchemaV1<any, any>): unknown;\n}\nexport const untypedKeyedScalarChain =\n KeyedScalarChain as unknown as abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n ) => UntypedKeyedScalarChain;\nexport const scalarChain = ScalarChain as unknown as Chain;\nexport const listScalarChain = ListScalarChain as unknown as Chain;\nexport const keyedScalarChain = KeyedScalarChain as unknown as Chain;\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// The modifiers every scalar shares are implemented once, in the chain this\n// class extends; the class types them for this scalar's own state\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport type { StringSchema } from \"@validation/primitives/string\";\nimport v from \"@validation/primitives/v\";\nimport type { ComputeInput, ComputeOutput } from \"@validation/types\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n keyedScalarChain,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<\n State extends ScalarState<\"string\">,\n> extends keyedScalarChain<State> {\n private declare readonly state: State;\n private declare readonly _nativeType: NativeTypeDeclaration | undefined;\n declare readonly nullable: () => StringScalar<\n UpdateState<\n State,\n {\n readonly nullable: true;\n readonly hasDefault: true;\n readonly default: State[\"hasDefault\"] extends true\n ? State[\"default\"]\n : null;\n readonly optional: true;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }\n >\n >;\n }\n >\n >;\n declare readonly unique: () => StringScalar<\n UpdateState<\n State,\n {\n readonly isUnique: true;\n }\n >\n >;\n declare readonly default: <V extends DefaultValueInput<State>>(\n value: V\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly hasDefault: true;\n readonly default: V;\n readonly optional: true;\n }\n >\n >;\n declare readonly schema: <S extends StandardSchemaV1<string>>(\n schema: S\n ) => StringScalar<\n UpdateState<\n State,\n {\n readonly schema: S;\n readonly base: StringSchema<\n ComputeInput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >,\n ComputeOutput<\n string,\n {\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }\n >\n >;\n }\n >\n >;\n /**\n * Maps this scalar to a custom column name in the database\n */\n declare readonly map: (columnName: string) => StringScalar<\n UpdateState<\n State,\n {\n readonly columnName: string;\n }\n >\n >;\n declare readonly [\"~\"]: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n protected rebase(state: State) {\n return v.string({\n nullable: state.nullable,\n array: state.array,\n schema: state.schema,\n });\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"wqBAuBA,SAAgB,MACd,EACoB,CAEpB,IAAM,EAAW,EAAK,aAAa,SAE7B,EAAS,EACb,QACC,GAAU,GAAc,EAAO,EAAS,CAC1C,CAID,MAFC,GAAe,KAAO,EAEhB,ECVT,MAAM,EAAa,OAAO,OAAO,CAC/B,OAAQ,OAAO,OAAO,CAAC,OAAO,OAAO,CAAE,QAAS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