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
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CBuxSC66.mjs";import{b as r,
|
|
2
|
-
//# sourceMappingURL=datetime-physical-codec-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CBuxSC66.mjs";import{b as r,v as i,y as a}from"./native-types-DspZ0Z5E.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(a(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function digitsAt(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function decodeCanonicalTimestamp(e){if(e.length!==24||e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||e.charCodeAt(10)!==84||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58||e.charCodeAt(19)!==46||e.charCodeAt(23)!==90)return!1;let t=digitsAt(e,0,4),n=digitsAt(e,5,2),o=digitsAt(e,8,2),s=digitsAt(e,11,2),c=digitsAt(e,14,2),l=digitsAt(e,17,2),u=digitsAt(e,20,3);if(t<100||n<0||o<0||s<0||c<0||l<0||u<0)return!1;if(!(r(t,n,o)&&i(s,c,l)))return;let d=Date.UTC(t,n-1,o,s,c,l,u);return a(d)?new Date(d):void 0}function decodeProviderTimestamp(e){let t=decodeCanonicalTimestamp(e);if(t!==!1)return t;let n=c.exec(e);if(!n)return;let o=n[13]?1-Number(n[1]):Number(n[1]),s=Number(n[2]),l=Number(n[3]),u=Number(n[4]),d=Number(n[5]),f=Number(n[6]),p=Number(n[10]??0),m=Number(n[11]??0),h=Number(n[12]??0);if(!(r(o,s,l)&&i(u,d,f))||p>23||m>59||h>59)return;let g=new Date(0);g.setUTCFullYear(o,s-1,l),g.setUTCHours(u,d,f,Number((n[7]??``).padEnd(3,`0`).slice(0,3)));let _=(p*3600+m*60+h)*1e3,v=g.getTime()-(n[9]===`-`?-_:_);return a(v)?new Date(v):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
|
|
2
|
+
//# sourceMappingURL=datetime-physical-codec-BS2T81sD.mjs.map
|
package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime-physical-codec-Dj-APo9f.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"8JA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CAC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AAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
|
|
1
|
+
{"version":3,"file":"datetime-physical-codec-BS2T81sD.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"8JA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GA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O,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,r as n}from"./extension-CGepsF-p.mjs";import{j as r}from"./scalar-
|
|
2
|
-
//# sourceMappingURL=defaults-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,r as n}from"./extension-CGepsF-p.mjs";import{j as r}from"./scalar-B9WizsvR.mjs";import{h as i}from"./validator-CDYlO9HV.mjs";import{i as a}from"./schema-MB-pPNTO.mjs";import{ft as o}from"./query-Cdy8E2jM.mjs";import{h as s,m as c,n as l,p as u,t as d}from"./rule-words-C4lXzgW2.mjs";function omitPart(e,t){return{seal({next:n}){let r={...n.omit?.config};r[e]=Object.freeze({...r[e],[t]:!0}),n.omit=Object.freeze({config:Object.freeze(r)})}}}const f=new Set([`json`,`vector`,`point`,`blob`]);function orderOf(e,t){let n=Array.isArray(t)?t:[t],{scalars:a}=e[`~`].state;return i(e).rowKey!==void 0&&n.length>0&&n.every(e=>{let[t,...n]=r(e)?Object.keys(e):[],i=t!==void 0&&Object.hasOwn(a,t)?a[t][`~`].state:void 0,o=i&&e[t];return n.length===0&&(o===`asc`||o===`desc`)&&!i.array&&!f.has(i.type)})?n.map(e=>({...e})):void 0}var PlainDomain=class{rows;queries;defaults=this;judge=void 0;project=void 0;#e;constructor(e,t){this.rows=e,this.queries=t}prepare(e,t){return this.queries.prepareSelector(e,t)}conjunction(){return null}reads(){return this.#e??=this.queries.under(this)}selector(){}bound(){}restrictsLinkWrite(){return!1}refuseHiddenLinkRow(){}};const p=new WeakMap;function preparePlain(e,t){let n=a(a(p,e,()=>new WeakMap),this.domain,()=>new PlainDomain(this.domain,e));return{rows:this,domain:n,defaults:n,instant:t}}const m=new Map;var PlainBinding=class{#e;#t;constructor({defaultOrder:e,stamps:t}){let n={root:m,related:m,...e&&{order:new Map(Object.entries(e))}};this.#t=t,this.#e={domain:n,...t&&{stamps:t.all},prepare:preparePlain}}call(e,t){let n=this.#t;return n?.named?{...this.#e,stamps:n.of(t)}:this.#e}};const bindPlain=e=>new PlainBinding(e),h=new Set([`orderBy`,`create`,`update`,`fields`]);var Omitted=class extends d{join({key:e,field:t,model:n,bring:r,refuse:i}){e!==`fields.${t}`&&i(`${e} does not take omitted`),r(omitPart(n,t))}};const g=omittedValue();function omittedValue(){return new Omitted}function stampOf(e,t,n){if(e===void 0)return;if(!r(e))return n(`data is an object of fields`);let i={};for(let[r,a]of Object.entries(e))Object.hasOwn(t,r)||n(`names unknown field "${r}"`),i[r]=a instanceof l&&a.stamp?a.stamp():a;return i}const merged=(e,t)=>t===void 0?e:{...e,...t};function writeDefaults(e,t,i){let a={order:{},data:{},brought:[]},{order:o,data:s,brought:c}=a;for(let[a,l]of Object.entries(t)){let refuse=t=>n(`Extension "${e}" defaults.${a}: ${t}.`,e);Object.hasOwn(i,a)||n(`Extension "${e}" defaults names unknown model "${a}".`,e),r(l)||refuse(`an entry is an object`);for(let e of Object.keys(l))h.has(e)||refuse(`"${e}" is not a defaults key`);let t=i[a],{scalars:u}=t[`~`].state;l.orderBy!==void 0&&(o[a]=orderOf(t,l.orderBy)??refuse(`orderBy maps a model with a key to { field: "asc" | "desc" } terms over its ordered scalars`));for(let e of[`create`,`update`]){let t=stampOf(l[e],u,refuse);t!==void 0&&(s[a]={...s[a],[e]:merged(s[a]?.[e],t)})}if(l.fields!==void 0){r(l.fields)||refuse(`fields is an object`);for(let[e,t]of Object.entries(l.fields)){let n=`fields.${e}`;t instanceof d||refuse(`${n} is written omitted`),t.join({model:a,key:n,field:e,schema:i,bring:e=>c.push(e),lazy:!1,entry:()=>refuse(`${n} is written omitted`),refuse})}}}return a}function defaultsPart(e){let n={join(r){let{name:i,next:a,schema:c}=r,{order:l,data:d,brought:f}=t(r,n,()=>writeDefaults(i,e(c),c));for(let e of f)r.bring(e);if(Object.keys(l).length>0&&(a.defaultOrder={...a.defaultOrder,...l}),Object.keys(d).length===0)return;let p=[],m={...a.defaultData};for(let[e,t]of Object.entries(d)){let n=m[e];m[e]={create:merged(n?.create,t.create),update:merged(n?.update,t.update)};for(let e of[...Object.values(t.create??{}),...Object.values(t.update??{})])e instanceof o&&e.arg!==void 0&&p.push(e.arg)}s(r,p),a.defaultData=m,a.stamps=new u(a.defaultData)},seal(e){c(e,bindPlain)}};return n}function defaults(e){return defaultsPart(t=>typeof e==`function`?e(t):e)}export{g as n,defaults as t};
|
|
2
|
+
//# sourceMappingURL=defaults-CrtGVdEC.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults-DwOHWI_M.mjs","names":["#view","#facts","#stamps"],"sources":["../src/client/default-omit-identity.ts","../src/extensions/order.ts","../src/extensions/plain-domain.ts","../src/extensions/defaults.ts"],"sourcesContent":["/**\n * The fields `defaults` leaves out of results (`fields: { f: omitted }`), as\n * a chain meets them: each joined per model with those before it, on the\n * chain (`chain.omit`), which every later chain keeps and the client reads.\n */\nimport type { ExtensionPart } from \"@extensions/chain\";\nimport type { ClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\n/** What one `omitted` brings: its field left out of its model's results. */\nexport function omitPart(model: string, field: string): ExtensionPart {\n return {\n seal({ next }) {\n const config: ClientOmitConfig<Schema> = { ...next.omit?.config };\n config[model] = Object.freeze({ ...config[model], [field]: true });\n next.omit = Object.freeze({ config: Object.freeze(config) });\n },\n };\n}\n","/**\n * Default order: per model, the order its reads take when the caller gives\n * no `orderBy`. It reads no argument and filters no row.\n */\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\n\nconst UNORDERED_SCALARS = new Set([\"json\", \"vector\", \"point\", \"blob\"]);\n\n/**\n * One model's default order, read once: its terms, each `{ field: \"asc\" |\n * \"desc\" }`, or `undefined` where they are refused. The model must have a\n * row key (its reads end with it, so the order is total) and each field\n * must be one of its scalars that orders as a value (not a list, JSON,\n * vector or point).\n */\nexport function orderOf(\n model: AnyModel,\n given: unknown\n): readonly Input[] | undefined {\n const terms = Array.isArray(given) ? given : [given];\n const { scalars } = model[\"~\"].state;\n const valid =\n getModelKeyCatalog(model).rowKey !== undefined &&\n terms.length > 0 &&\n terms.every((term) => {\n const [field, ...others] = isPlainRecord(term) ? Object.keys(term) : [];\n const state =\n field !== undefined && Object.hasOwn(scalars, field)\n ? scalars[field]![\"~\"].state\n : undefined;\n // A field was read off `term`, so it is a record.\n const direction = state && (term as Input)[field!];\n return (\n others.length === 0 &&\n (direction === \"asc\" || direction === \"desc\") &&\n !state.array &&\n !UNORDERED_SCALARS.has(state.type)\n );\n });\n return valid ? terms.map((term) => ({ ...term })) : undefined;\n}\n","/**\n * The call facts of a chain whose parts order and stamp rows but neither\n * filter, keep nor judge any (`order`, `data`): a domain that answers every\n * question as one with no layer does, so neither the prepared domain, its\n * layers nor what admits predicates comes with them. Once a\n * part of the chain filters or keeps rows, its own binding reads the order\n * and the stamps too.\n */\nimport type {\n PreparedSelector,\n Queries,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallRows,\n CallScope,\n ModelDomain,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallRowsBinding, ResolvedExtensionChain } from \"./chain-state\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport type { Stamps } from \"./stamps\";\n\n/**\n * A domain with no layer, prepared for one engine view: it restricts no row,\n * judges and projects nothing, and holds the chain's order. It prepares a\n * predicate as the view does, for whoever asks.\n */\nexport class PlainDomain implements PreparedDomain {\n readonly rows: RowDomain;\n readonly queries: Queries;\n readonly defaults = this;\n readonly judge = undefined;\n readonly project = undefined;\n #view: Queries | undefined;\n constructor(rows: RowDomain, queries: Queries) {\n this.rows = rows;\n this.queries = queries;\n }\n prepare(model: AnyModel, input: Input): PreparedSelector {\n return this.queries.prepareSelector(model, input);\n }\n conjunction(): null {\n return null;\n }\n /** One read view for every call: a plain call carries no value to read. */\n reads(): Queries {\n return (this.#view ??= this.queries.under(this));\n }\n selector(): undefined {\n return undefined;\n }\n bound(): undefined {\n return undefined;\n }\n restrictsLinkWrite(): boolean {\n return false;\n }\n refuseHiddenLinkRow(): void {\n // No row is hidden and no field gated: every link reads as it is.\n }\n}\n\n/** Each plain domain, prepared once per query owner, as a filtered one is. */\nconst prepared = new WeakMap<Queries, WeakMap<RowDomain, PlainDomain>>();\n\nfunction preparePlain(\n this: CallRows,\n queries: Queries,\n instant: () => Date\n): CallScope {\n const domain = memo(\n memo(prepared, queries, () => new WeakMap()),\n this.domain,\n () => new PlainDomain(this.domain, queries)\n );\n return { rows: this, domain, defaults: domain, instant };\n}\n\n/** No model is restricted. */\nconst NONE: ModelDomain = new Map();\n\n/** The facts every call of a plain chain shares; its stamps are its own where they name an argument. */\nclass PlainBinding implements CallRowsBinding {\n readonly #facts: CallRows;\n readonly #stamps: Stamps | undefined;\n constructor({ defaultOrder: order, stamps }: ResolvedExtensionChain) {\n const domain: RowDomain = {\n root: NONE,\n related: NONE,\n ...(order && { order: new Map(Object.entries(order)) }),\n };\n this.#stamps = stamps;\n this.#facts = {\n domain,\n ...(stamps && { stamps: stamps.all }),\n prepare: preparePlain,\n };\n }\n call(_model: string, values: AdmittedArgs | undefined): CallRows {\n const stamps = this.#stamps;\n return stamps?.named\n ? { ...this.#facts, stamps: stamps.of(values) }\n : this.#facts;\n }\n}\n\n/** The call facts of a chain that only orders and stamps rows. */\nexport const bindPlain = (chain: ResolvedExtensionChain): CallRowsBinding =>\n new PlainBinding(chain);\n","/**\n * `defaults({ [model]: { orderBy?, create?, update?, fields? } })`: what\n * holds where the caller says nothing, and the caller may override: the\n * order a read takes without `orderBy`, the fields a create or an update\n * writes where the caller leaves them out, and the fields a result leaves\n * out by default (`fields: { passwordHash: omitted }`, the word bringing\n * what omits). A chain whose parts filter nothing reads them on a domain\n * that filters nothing (`plain-domain.ts`).\n */\nimport { omitPart } from \"@client/default-omit-identity\";\nimport type { Schema } from \"@client/types\";\nimport {\n type ModelStamps,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport { type ExtensionPart, extensionError, shared } from \"./chain\";\nimport type {\n AnyTarget,\n DefaultsFacts,\n DefaultsInput,\n ExactEntries,\n FromSchema,\n ModelName,\n OmittedWord,\n Part,\n} from \"./contract\";\nimport { orderOf } from \"./order\";\nimport { bindPlain } from \"./plain-domain\";\nimport { CarriedValue, PredicateWord, type Site } from \"./rule-words\";\nimport { Stamps } from \"./stamps\";\n\ntype Entry = Readonly<Record<string, unknown>>;\n\nconst DEFAULTS_KEYS = new Set([\"orderBy\", \"create\", \"update\", \"fields\"]);\n\n/** `omitted`'s value: it brings what omits. */\nclass Omitted extends CarriedValue {\n join({ key, field, model, bring, refuse }: Site): void {\n if (key !== `fields.${field}`) refuse(`${key} does not take omitted`);\n bring(omitPart(model, field!));\n }\n}\n\n/** The field leaves a model's default results; `omit: { f: false }` or a `select` brings it back. */\nexport const omitted: OmittedWord = /* @__PURE__ */ omittedValue();\nfunction omittedValue(): OmittedWord;\nfunction omittedValue(): unknown {\n return new Omitted();\n}\n\n/**\n * One kind's fields as a call writes them, each a constant, the call's\n * instant, or an argument's value (a parameter read per call).\n */\nfunction stampOf(\n given: unknown,\n scalars: Readonly<Record<string, unknown>>,\n refuse: (problem: string) => never\n): Input | undefined {\n if (given === undefined) return undefined;\n if (!isPlainRecord(given)) return refuse(\"data is an object of fields\");\n const out: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(given)) {\n if (!Object.hasOwn(scalars, field))\n refuse(`names unknown field \"${field}\"`);\n out[field] =\n value instanceof PredicateWord && value.stamp ? value.stamp() : value;\n }\n return out;\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nconst merged = (\n previous: Input | undefined,\n fields: Input | undefined\n): Input | undefined =>\n fields === undefined ? previous : { ...previous, ...fields };\n\n/** What one defaults part writes of one schema. */\ninterface Written {\n /** Per model, the order its reads take without one. */\n readonly order: Record<string, readonly Input[]>;\n /** Per model, the fields its creates and updates write. */\n readonly data: Record<string, ModelStamps>;\n /** The parts its words bring (`omitted`). */\n readonly brought: ExtensionPart[];\n}\n\n/** One defaults part's entries, read once per schema. */\nfunction writeDefaults(name: string, entries: Entry, schema: Schema): Written {\n const written: Written = { order: {}, data: {}, brought: [] };\n const { order, data, brought } = written;\n for (const [model, entry] of Object.entries(entries)) {\n const refuse: (problem: string) => never = (problem) =>\n extensionError(\n `Extension \"${name}\" defaults.${model}: ${problem}.`,\n name\n );\n if (!Object.hasOwn(schema, model))\n extensionError(\n `Extension \"${name}\" defaults names unknown model \"${model}\".`,\n name\n );\n if (!isPlainRecord(entry)) refuse(\"an entry is an object\");\n for (const key of Object.keys(entry))\n if (!DEFAULTS_KEYS.has(key)) refuse(`\"${key}\" is not a defaults key`);\n const own = schema[model]!;\n const { scalars } = own[\"~\"].state;\n if (entry.orderBy !== undefined)\n order[model] =\n orderOf(own, entry.orderBy) ??\n refuse(\n 'orderBy maps a model with a key to { field: \"asc\" | \"desc\" } terms over its ordered scalars'\n );\n for (const kind of [\"create\", \"update\"] as const) {\n const stamp = stampOf(entry[kind], scalars, refuse);\n if (stamp === undefined) continue;\n data[model] = {\n ...data[model],\n [kind]: merged(data[model]?.[kind], stamp),\n };\n }\n if (entry.fields === undefined) continue;\n if (!isPlainRecord(entry.fields)) refuse(\"fields is an object\");\n for (const [field, word] of Object.entries(entry.fields)) {\n const key = `fields.${field}`;\n if (!(word instanceof CarriedValue)) refuse(`${key} is written omitted`);\n word.join({\n model,\n key,\n field,\n schema,\n bring: (part) => brought.push(part),\n lazy: false,\n entry: () => refuse(`${key} is written omitted`),\n refuse,\n });\n }\n }\n return written;\n}\n\n/**\n * `defaults`: the default order (a later entry for a model replaces one)\n * and the default data (a later one wins a field). The arguments a field\n * names are declared on the chain by its own or an earlier extension.\n */\nfunction defaultsPart(read: (schema: Schema) => Entry): ExtensionPart {\n const part: ExtensionPart = {\n join(application) {\n const { name, next, schema } = application;\n const { order, data, brought } = shared(application, part, () =>\n writeDefaults(name, read(schema), schema)\n );\n for (const omits of brought) application.bring(omits);\n if (Object.keys(order).length > 0)\n next.defaultOrder = { ...next.defaultOrder, ...order };\n if (Object.keys(data).length === 0) return;\n const names: string[] = [];\n const entries: Record<string, ModelStamps> = { ...next.defaultData };\n for (const [model, entry] of Object.entries(data)) {\n const known = entries[model];\n entries[model] = {\n create: merged(known?.create, entry.create),\n update: merged(known?.update, entry.update),\n };\n for (const value of [\n ...Object.values(entry.create ?? {}),\n ...Object.values(entry.update ?? {}),\n ])\n if (value instanceof Parameter && value.arg !== undefined)\n names.push(value.arg);\n }\n refuseUndeclared(application, names);\n next.defaultData = entries;\n next.stamps = new Stamps(next.defaultData);\n },\n seal(application) {\n rebind(application, bindPlain);\n },\n };\n return part;\n}\n\n/**\n * What holds where the caller says nothing: the order of reads, the fields\n * writes stamp, the fields results leave out. Given a function of the\n * schema, it is read where the extension is applied.\n */\nexport function defaults<T extends AnyTarget, const D = DefaultsInput<T>>(\n defaults: D &\n (DefaultsInput<T> | FromSchema<T, DefaultsInput<T>>) &\n NoInfer<ExactEntries<D, DefaultsInput<T>>>\n): Part<T, DefaultsFacts<D, ModelName<T>>>;\nexport function defaults(\n entries: Entry | ((schema: Schema) => Entry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AAK,YAAc,EACnB,EAAK,OAAS,IAAI,EAAO,EAAK,YAAY,EAE5C,KAAK,EAAa,CAChB,EAAO,EAAa,UAAU,EAEjC,CACD,OAAO,EAaT,SAAgB,SACd,EACS,CACT,OAAO,aAAc,GACnB,OAAO,GAAY,WAAa,EAAQ,EAAO,CAAG,EACnD"}
|
|
1
|
+
{"version":3,"file":"defaults-CrtGVdEC.mjs","names":["#view","#facts","#stamps"],"sources":["../src/client/default-omit-identity.ts","../src/extensions/order.ts","../src/extensions/plain-domain.ts","../src/extensions/defaults.ts"],"sourcesContent":["/**\n * The fields `defaults` leaves out of results (`fields: { f: omitted }`), as\n * a chain meets them: each joined per model with those before it, on the\n * chain (`chain.omit`), which every later chain keeps and the client reads.\n */\nimport type { ExtensionPart } from \"@extensions/chain\";\nimport type { ClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\n/** What one `omitted` brings: its field left out of its model's results. */\nexport function omitPart(model: string, field: string): ExtensionPart {\n return {\n seal({ next }) {\n const config: ClientOmitConfig<Schema> = { ...next.omit?.config };\n config[model] = Object.freeze({ ...config[model], [field]: true });\n next.omit = Object.freeze({ config: Object.freeze(config) });\n },\n };\n}\n","/**\n * Default order: per model, the order its reads take when the caller gives\n * no `orderBy`. It reads no argument and filters no row.\n */\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\n\nconst UNORDERED_SCALARS = new Set([\"json\", \"vector\", \"point\", \"blob\"]);\n\n/**\n * One model's default order, read once: its terms, each `{ field: \"asc\" |\n * \"desc\" }`, or `undefined` where they are refused. The model must have a\n * row key (its reads end with it, so the order is total) and each field\n * must be one of its scalars that orders as a value (not a list, JSON,\n * vector or point).\n */\nexport function orderOf(\n model: AnyModel,\n given: unknown\n): readonly Input[] | undefined {\n const terms = Array.isArray(given) ? given : [given];\n const { scalars } = model[\"~\"].state;\n const valid =\n getModelKeyCatalog(model).rowKey !== undefined &&\n terms.length > 0 &&\n terms.every((term) => {\n const [field, ...others] = isPlainRecord(term) ? Object.keys(term) : [];\n const state =\n field !== undefined && Object.hasOwn(scalars, field)\n ? scalars[field]![\"~\"].state\n : undefined;\n // A field was read off `term`, so it is a record.\n const direction = state && (term as Input)[field!];\n return (\n others.length === 0 &&\n (direction === \"asc\" || direction === \"desc\") &&\n !state.array &&\n !UNORDERED_SCALARS.has(state.type)\n );\n });\n return valid ? terms.map((term) => ({ ...term })) : undefined;\n}\n","/**\n * The call facts of a chain whose parts order and stamp rows but neither\n * filter, keep nor judge any (`order`, `data`): a domain that answers every\n * question as one with no layer does, so neither the prepared domain, its\n * layers nor what admits predicates comes with them. Once a\n * part of the chain filters or keeps rows, its own binding reads the order\n * and the stamps too.\n */\nimport type {\n PreparedSelector,\n Queries,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallRows,\n CallScope,\n ModelDomain,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallRowsBinding, ResolvedExtensionChain } from \"./chain-state\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport type { Stamps } from \"./stamps\";\n\n/**\n * A domain with no layer, prepared for one engine view: it restricts no row,\n * judges and projects nothing, and holds the chain's order. It prepares a\n * predicate as the view does, for whoever asks.\n */\nexport class PlainDomain implements PreparedDomain {\n readonly rows: RowDomain;\n readonly queries: Queries;\n readonly defaults = this;\n readonly judge = undefined;\n readonly project = undefined;\n #view: Queries | undefined;\n constructor(rows: RowDomain, queries: Queries) {\n this.rows = rows;\n this.queries = queries;\n }\n prepare(model: AnyModel, input: Input): PreparedSelector {\n return this.queries.prepareSelector(model, input);\n }\n conjunction(): null {\n return null;\n }\n /** One read view for every call: a plain call carries no value to read. */\n reads(): Queries {\n return (this.#view ??= this.queries.under(this));\n }\n selector(): undefined {\n return undefined;\n }\n bound(): undefined {\n return undefined;\n }\n restrictsLinkWrite(): boolean {\n return false;\n }\n refuseHiddenLinkRow(): void {\n // No row is hidden and no field gated: every link reads as it is.\n }\n}\n\n/** Each plain domain, prepared once per query owner, as a filtered one is. */\nconst prepared = new WeakMap<Queries, WeakMap<RowDomain, PlainDomain>>();\n\nfunction preparePlain(\n this: CallRows,\n queries: Queries,\n instant: () => Date\n): CallScope {\n const domain = memo(\n memo(prepared, queries, () => new WeakMap()),\n this.domain,\n () => new PlainDomain(this.domain, queries)\n );\n return { rows: this, domain, defaults: domain, instant };\n}\n\n/** No model is restricted. */\nconst NONE: ModelDomain = new Map();\n\n/** The facts every call of a plain chain shares; its stamps are its own where they name an argument. */\nclass PlainBinding implements CallRowsBinding {\n readonly #facts: CallRows;\n readonly #stamps: Stamps | undefined;\n constructor({ defaultOrder: order, stamps }: ResolvedExtensionChain) {\n const domain: RowDomain = {\n root: NONE,\n related: NONE,\n ...(order && { order: new Map(Object.entries(order)) }),\n };\n this.#stamps = stamps;\n this.#facts = {\n domain,\n ...(stamps && { stamps: stamps.all }),\n prepare: preparePlain,\n };\n }\n call(_model: string, values: AdmittedArgs | undefined): CallRows {\n const stamps = this.#stamps;\n return stamps?.named\n ? { ...this.#facts, stamps: stamps.of(values) }\n : this.#facts;\n }\n}\n\n/** The call facts of a chain that only orders and stamps rows. */\nexport const bindPlain = (chain: ResolvedExtensionChain): CallRowsBinding =>\n new PlainBinding(chain);\n","/**\n * `defaults({ [model]: { orderBy?, create?, update?, fields? } })`: what\n * holds where the caller says nothing, and the caller may override: the\n * order a read takes without `orderBy`, the fields a create or an update\n * writes where the caller leaves them out, and the fields a result leaves\n * out by default (`fields: { passwordHash: omitted }`, the word bringing\n * what omits). A chain whose parts filter nothing reads them on a domain\n * that filters nothing (`plain-domain.ts`).\n */\nimport { omitPart } from \"@client/default-omit-identity\";\nimport type { Schema } from \"@client/types\";\nimport {\n type ModelStamps,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport { type ExtensionPart, extensionError, shared } from \"./chain\";\nimport type {\n AnyTarget,\n DefaultsFacts,\n DefaultsInput,\n ExactEntries,\n FromSchema,\n ModelName,\n OmittedWord,\n Part,\n} from \"./contract\";\nimport { orderOf } from \"./order\";\nimport { bindPlain } from \"./plain-domain\";\nimport { CarriedValue, PredicateWord, type Site } from \"./rule-words\";\nimport { Stamps } from \"./stamps\";\n\ntype Entry = Readonly<Record<string, unknown>>;\n\nconst DEFAULTS_KEYS = new Set([\"orderBy\", \"create\", \"update\", \"fields\"]);\n\n/** `omitted`'s value: it brings what omits. */\nclass Omitted extends CarriedValue {\n join({ key, field, model, bring, refuse }: Site): void {\n if (key !== `fields.${field}`) refuse(`${key} does not take omitted`);\n bring(omitPart(model, field!));\n }\n}\n\n/** The field leaves a model's default results; `omit: { f: false }` or a `select` brings it back. */\nexport const omitted: OmittedWord = /* @__PURE__ */ omittedValue();\nfunction omittedValue(): OmittedWord;\nfunction omittedValue(): unknown {\n return new Omitted();\n}\n\n/**\n * One kind's fields as a call writes them, each a constant, the call's\n * instant, or an argument's value (a parameter read per call).\n */\nfunction stampOf(\n given: unknown,\n scalars: Readonly<Record<string, unknown>>,\n refuse: (problem: string) => never\n): Input | undefined {\n if (given === undefined) return undefined;\n if (!isPlainRecord(given)) return refuse(\"data is an object of fields\");\n const out: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(given)) {\n if (!Object.hasOwn(scalars, field))\n refuse(`names unknown field \"${field}\"`);\n out[field] =\n value instanceof PredicateWord && value.stamp ? value.stamp() : value;\n }\n return out;\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nconst merged = (\n previous: Input | undefined,\n fields: Input | undefined\n): Input | undefined =>\n fields === undefined ? previous : { ...previous, ...fields };\n\n/** What one defaults part writes of one schema. */\ninterface Written {\n /** Per model, the order its reads take without one. */\n readonly order: Record<string, readonly Input[]>;\n /** Per model, the fields its creates and updates write. */\n readonly data: Record<string, ModelStamps>;\n /** The parts its words bring (`omitted`). */\n readonly brought: ExtensionPart[];\n}\n\n/** One defaults part's entries, read once per schema. */\nfunction writeDefaults(name: string, entries: Entry, schema: Schema): Written {\n const written: Written = { order: {}, data: {}, brought: [] };\n const { order, data, brought } = written;\n for (const [model, entry] of Object.entries(entries)) {\n const refuse: (problem: string) => never = (problem) =>\n extensionError(\n `Extension \"${name}\" defaults.${model}: ${problem}.`,\n name\n );\n if (!Object.hasOwn(schema, model))\n extensionError(\n `Extension \"${name}\" defaults names unknown model \"${model}\".`,\n name\n );\n if (!isPlainRecord(entry)) refuse(\"an entry is an object\");\n for (const key of Object.keys(entry))\n if (!DEFAULTS_KEYS.has(key)) refuse(`\"${key}\" is not a defaults key`);\n const own = schema[model]!;\n const { scalars } = own[\"~\"].state;\n if (entry.orderBy !== undefined)\n order[model] =\n orderOf(own, entry.orderBy) ??\n refuse(\n 'orderBy maps a model with a key to { field: \"asc\" | \"desc\" } terms over its ordered scalars'\n );\n for (const kind of [\"create\", \"update\"] as const) {\n const stamp = stampOf(entry[kind], scalars, refuse);\n if (stamp === undefined) continue;\n data[model] = {\n ...data[model],\n [kind]: merged(data[model]?.[kind], stamp),\n };\n }\n if (entry.fields === undefined) continue;\n if (!isPlainRecord(entry.fields)) refuse(\"fields is an object\");\n for (const [field, word] of Object.entries(entry.fields)) {\n const key = `fields.${field}`;\n if (!(word instanceof CarriedValue)) refuse(`${key} is written omitted`);\n word.join({\n model,\n key,\n field,\n schema,\n bring: (part) => brought.push(part),\n lazy: false,\n entry: () => refuse(`${key} is written omitted`),\n refuse,\n });\n }\n }\n return written;\n}\n\n/**\n * `defaults`: the default order (a later entry for a model replaces one)\n * and the default data (a later one wins a field). The arguments a field\n * names are declared on the chain by its own or an earlier extension.\n */\nfunction defaultsPart(read: (schema: Schema) => Entry): ExtensionPart {\n const part: ExtensionPart = {\n join(application) {\n const { name, next, schema } = application;\n const { order, data, brought } = shared(application, part, () =>\n writeDefaults(name, read(schema), schema)\n );\n for (const omits of brought) application.bring(omits);\n if (Object.keys(order).length > 0)\n next.defaultOrder = { ...next.defaultOrder, ...order };\n if (Object.keys(data).length === 0) return;\n const names: string[] = [];\n const entries: Record<string, ModelStamps> = { ...next.defaultData };\n for (const [model, entry] of Object.entries(data)) {\n const known = entries[model];\n entries[model] = {\n create: merged(known?.create, entry.create),\n update: merged(known?.update, entry.update),\n };\n for (const value of [\n ...Object.values(entry.create ?? {}),\n ...Object.values(entry.update ?? {}),\n ])\n if (value instanceof Parameter && value.arg !== undefined)\n names.push(value.arg);\n }\n refuseUndeclared(application, names);\n next.defaultData = entries;\n next.stamps = new Stamps(next.defaultData);\n },\n seal(application) {\n rebind(application, bindPlain);\n },\n };\n return part;\n}\n\n/**\n * What holds where the caller says nothing: the order of reads, the fields\n * writes stamp, the fields results leave out. Given a function of the\n * schema, it is read where the extension is applied.\n */\nexport function defaults<T extends AnyTarget, const D = DefaultsInput<T>>(\n defaults: D &\n (DefaultsInput<T> | FromSchema<T, DefaultsInput<T>>) &\n NoInfer<ExactEntries<D, DefaultsInput<T>>>\n): Part<T, DefaultsFacts<D, ModelName<T>>>;\nexport function defaults(\n entries: Entry | ((schema: Schema) => Entry)\n): unknown {\n return defaultsPart((schema) =>\n typeof entries === \"function\" ? entries(schema) : entries\n );\n}\n"],"mappings":"kVAUA,SAAgB,SAAS,EAAe,EAA8B,CACpE,MAAO,CACL,KAAK,CAAE,QAAQ,CACb,IAAM,EAAmC,CAAE,GAAG,EAAK,MAAM,OAAQ,CACjE,EAAO,GAAS,OAAO,OAAO,CAAE,GAAG,EAAO,IAAS,GAAQ,GAAM,CAAC,CAClE,EAAK,KAAO,OAAO,OAAO,CAAE,OAAQ,OAAO,OAAO,EAAO,CAAE,CAAC,EAE/D,CCRH,MAAM,EAAoB,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AS,aAAa,EAAgD,CACpE,IAAM,EAAsB,CAC1B,KAAK,EAAa,CAChB,GAAM,CAAE,OAAM,OAAM,UAAW,EACzB,CAAE,QAAO,OAAM,WAAY,EAAO,EAAa,MACnD,cAAc,EAAM,EAAK,EAAO,CAAE,EAAO,CAC1C,CACD,IAAK,IAAM,KAAS,EAAS,EAAY,MAAM,EAAM,CAGrD,GAFI,OAAO,KAAK,EAAM,CAAC,OAAS,IAC9B,EAAK,aAAe,CAAE,GAAG,EAAK,aAAc,GAAG,EAAO,EACpD,OAAO,KAAK,EAAK,CAAC,SAAW,EAAG,OACpC,IAAM,EAAkB,EAAE,CACpB,EAAuC,CAAE,GAAG,EAAK,YAAa,CACpE,IAAK,GAAM,CAAC,EAAO,KAAU,OAAO,QAAQ,EAAK,CAAE,CACjD,IAAM,EAAQ,EAAQ,GACtB,EAAQ,GAAS,CACf,OAAQ,OAAO,GAAO,OAAQ,EAAM,OAAO,CAC3C,OAAQ,OAAO,GAAO,OAAQ,EAAM,OAAO,CAC5C,CACD,IAAK,IAAM,IAAS,CAClB,GAAG,OAAO,OAAO,EAAM,QAAU,EAAE,CAAC,CACpC,GAAG,OAAO,OAAO,EAAM,QAAU,EAAE,CAAC,CACrC,CACK,aAAiB,GAAa,EAAM,MAAQ,IAAA,IAC9C,EAAM,KAAK,EAAM,IAAI,CAE3B,EAAiB,EAAa,EAAM,CACpC,EAAK,YAAc,EACnB,EAAK,OAAS,IAAI,EAAO,EAAK,YAAY,EAE5C,KAAK,EAAa,CAChB,EAAO,EAAa,UAAU,EAEjC,CACD,OAAO,EAaT,SAAgB,SACd,EACS,CACT,OAAO,aAAc,GACnB,OAAO,GAAY,WAAa,EAAQ,EAAO,CAAG,EACnD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ba as JunctionReferentialAction, Ft as ScalarType, Ho as NativeType, Va as ReferentialAction, Wo as NativeTypeMap, jt as AutoGenerateType, oa as JsonValue, qi as IndexType } from "./database-adapter-D62c-uC6.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/schema/json/document.d.ts
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,O as n,k as r}from"./error-mapping-
|
|
2
|
-
//# sourceMappingURL=driver-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,O as n,k as r}from"./error-mapping-DIRlrmDK.mjs";import{B as i}from"./scalar-B9WizsvR.mjs";import{t as a}from"./validation-D0LG854o.mjs";import{h as o,i as s}from"./unit-words-BGMVZ1MX.mjs";import{E as c,_ as l,a as u,c as d,n as f,r as p,t as m}from"./spans-BE-EjlZK.mjs";const h=`:reval`,g=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}async function marker(e,t,n){let r=`${t}${h}`;if(!n)return await e.delete([r]),!1;let i=await e.get(r);return i&&e.now()-i.createdAt<i.ttl?!1:(await e.set(r,g,{value:!0,createdAt:e.now(),ttl:g}),!0)}const _=`viborm`,v=`${_}:cache`;function encodeText(e){return e.split(``).map(e=>e.charCodeAt(0).toString(16).padStart(4,`0`)).join(``)}function encodeVersion(e){if(e===void 0)return`u`;if(typeof e==`number`){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!1),`n:${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}return`s:${encodeText(e)}`}function createOfficialCacheNamespace(e){return[v,`r6`,`d:${encodeText(e.dialect)}`,e.namespace===void 0?`x`:`k:${encodeText(e.namespace)}`,encodeVersion(e.version)].join(`:`)}function fastHash(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(n>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}const y=/^(\d+(?:\.\d+)?)\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/,b=[1,1e3,6e4,36e5,864e5,6048e5,2592e6];function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new t(`TTL must be positive, got: ${e}`);return e}let n=y.exec(e.trim().toLowerCase());if(!n)throw new t(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`);let r=Math.floor(Number.parseFloat(n[1])*b[n.slice(2).findIndex(e=>e!==void 0)]);if(!Number.isSafeInteger(r)||r<=0)throw new t(`TTL must be positive, got: ${r}ms from "${e}"`);return r}const x=i.object({invalidate:i.string({array:!0,optional:!0}),autoInvalidate:i.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e.invalidate!==void 0&&e.invalidate.length>0}const S=300*1e3,C=i.object({ttl:i.coerce(i.optional(i.union([i.string(),i.number()]),S),parseTTL),swr:i.coerce(i.optional(i.union([i.boolean(),i.string(),i.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:i.string({optional:!0}),bypass:i.boolean({optional:!0})},{optional:!0,default:{ttl:S,swr:!1,bypass:!1}}),w=Object.freeze([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function refused(e,t){throw new n(`Invalid ${e}: ${t.map(e=>e.message).join(`, `)}`)}function admitMutationOptions(e){let t=a(x,e);t.issues&&refused(`mutation cache options`,t.issues);let{autoInvalidate:n,invalidate:r}=t.value;if(r===void 0)return Object.freeze({autoInvalidate:n});let i=[...r];return Object.freeze(i),Object.freeze({autoInvalidate:n,invalidate:i})}function admitReadOptions(e){let t=a(C,e);t.issues&&refused(`cache options`,t.issues);let{bypass:n,key:r,ttl:i,swr:o}=t.value;return Object.freeze({ttlMs:i,swr:o===void 0||o===!1?!1:i+(o===!0?i:o),bypass:n,...r===void 0?{}:{key:r}})}const cacheOutcome=(e,t,n,r)=>({log:`cache`,at:Date.now(),meta:{event:e,status:t},error:n,...r});function placeSetFailure(e,t,n,r){s(e,cacheOutcome(`miss`,`cache-set-failed`,t))||s(n,cacheOutcome(`miss`,`cache-set-failed`,t,r))}function cacheStep(e,t,n,r,i){if(t===void 0)return r();let a={[m]:n,...i===void 0?{}:{[p]:String(i)},...e===`delete`||e===`clear`?{[l]:void 0}:{}};return o(t,{kind:`cache`,operation:e,note:{span:`viborm.cache.${e}`,attributes:a}},r)}const revalidationStart=(e,t)=>({...cacheOutcome(`revalidate`,`start`,void 0,e),span:c,root:!0,database:t,attributes:{[u]:e.model,[d]:e.operation}}),T={now:()=>Date.now(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>n.unref?.()}}},E=Symbol(`serve`),D=Symbol(`invalidate`),O=Symbol(`get`),k=Symbol(`set`),A=Symbol(`drop`),j=Symbol(`backend`);function scopedKey(e,t){if(t.startsWith(`${_}:`))throw new r(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${e}:${t}`}var CacheDriver=class{#e=0;driverName;clock;constructor(e,t=T){this.driverName=e,this.clock=t}async[E](e){let{id:t,read:n,namespace:r,codec:i,model:a,operation:o,origin:c}=e,l=scopedKey(r,`${a}:${o}:${fastHash(t)}${n.key===void 0?``:`:${n.key}`}`),u=JSON.stringify([t,n.key]),d=this.#e,store=(e,t)=>this[k](l,e,{ttl:n.ttlMs,swrTtl:n.swr||void 0},c,t,u,d),f=`bypass`;if(!n.bypass){let t=await this[O](l,c);if(t?.identity===u){let{createdAt:n,ttl:r,expiresAt:a}=t;if([n,r,a].every(Number.isFinite)&&r>0&&a>=n){let a=i.materialize(t.value),o=this.clock.now();if(o-n<r)return s(c,cacheOutcome(`hit`)),a;if(e.revalidate?.({request:e,entry:t,now:o,key:l,backend:this[j](),store}))return a}}f=`miss`}let p=await i.run();if(d===this.#e)try{scheduleBackground(store(i.snapshot(),e),e.waitUntil)}catch(e){s(c,cacheOutcome(`miss`,`cache-set-failed`,e))}return s(c,cacheOutcome(f)),p}async[O](e,t){return cacheStep(`get`,t,this.driverName,async t=>{let n=await this.get(e);return t!==void 0&&s(t,{attributes:{[f]:n?this.clock.now()-n.createdAt>n.ttl?`stale`:`hit`:`miss`}}),n})}async[k](e,t,n,r,i,a,o){if(o!==void 0&&o!==this.#e)return;let s=n.swrTtl??n.ttl,c=this.clock.now(),l={value:t,createdAt:c,ttl:n.ttl,...a===void 0?{}:{identity:a,expiresAt:c+s}};return cacheStep(`set`,r,this.driverName,async t=>{try{await this.set(e,s,l),o!==void 0&&o!==this.#e&&await this.delete([e])}catch(e){throw i!==void 0&&t!==void 0&&placeSetFailure(i.origin,e,t,i),e}},n.ttl)}[j](){return{get:e=>this.get(e),set:(e,t,n)=>this.set(e,t,n),delete:e=>this.delete(e),now:()=>this.clock.now()}}async[D](e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=t===void 0||t.autoInvalidate===!0?[[`clear`,r(e)]]:[];for(let e of t?.invalidate??[])i.push(e.endsWith(`*`)?[`clear`,r(e.slice(0,-1))]:[`delete`,r(e)]);return cacheStep(`invalidate`,n,this.driverName,async e=>{await Promise.all(i.map(([t,n])=>this[A](t,n,e)))})}[A](e,t,n){return this.#e+=1,cacheStep(e,n,this.driverName,()=>e===`clear`?this.clear(t):this.delete([t,`${t}${h}`]))}};export{createOfficialCacheNamespace as _,D as a,scopedKey as c,w as d,admitMutationOptions as f,v as g,_ as h,O as i,cacheOutcome as l,hasCacheInvalidationWork as m,CacheDriver as n,E as o,admitReadOptions as p,A as r,k as s,j as t,revalidationStart as u,marker as v,scheduleBackground as y};
|
|
2
|
+
//# sourceMappingURL=driver-D1grnHEr.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver-BGVcgnIX.mjs","names":["v","#fillRevision"],"sources":["../src/cache/cache-background.ts","../src/cache/key.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/units.ts","../src/cache/driver.ts"],"sourcesContent":["import type { CacheEntry, WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nconst REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n\n/** A driver's own storage primitives, unobserved, and its clock. */\nexport interface Backend {\n get(key: string): Promise<CacheEntry | null>;\n set(key: string, ttl: number, entry: CacheEntry): Promise<void>;\n delete(keys: string[]): Promise<void>;\n now(): number;\n}\n\n/**\n * Claim the refresh of the entry at `key` (whether this caller performs\n * it), or release the claim: a marker beside the entry, with a short TTL.\n */\nexport async function marker(\n backend: Backend,\n key: string,\n claim: boolean\n): Promise<boolean> {\n const marked = `${key}${REVALIDATING_SUFFIX}`;\n if (!claim) {\n await backend.delete([marked]);\n return false;\n }\n const existing = await backend.get(marked);\n if (existing && backend.now() - existing.createdAt < existing.ttl)\n return false;\n await backend.set(marked, REVALIDATING_TTL_MS, {\n value: true,\n createdAt: backend.now(),\n ttl: REVALIDATING_TTL_MS,\n });\n return true;\n}\n","/**\n * Cache key spaces: the official namespace one cache scope partitions on,\n * and the hash that names an entry inside it. What a read is keyed on is the\n * prepared call itself (`key(run)`).\n */\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for the official cache extension's scopes. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\n// r5 entries are keyed by the prepared call (`key(run)`): the statement the\n// engine sends, so a rule's filter, order and projection key an entry by\n// what they do to that statement.\n// r6 entries hold the rows the driver returned, not the decoded answer: an r5\n// answer read as rows would be refused at best.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r6\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n // `split(\"\")` gives the code units, never a pair as one code point.\n return value\n .split(\"\")\n .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, \"0\"))\n .join(\"\");\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n return `n:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n // `x` unknown, `k:<hex>` known. An unknown namespace is a bare `x` with\n // no body, so it cannot be reached by encoding any string whatsoever — a\n // database literally named `undefined` encodes as `k:0075...`. Absence is\n // a distinct value here, not a spelling.\n facts.namespace === undefined ? \"x\" : `k:${encodeText(facts.namespace)}`,\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nexport function fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/** `<number> <unit>`, each unit's spellings one group, in the order of `UNIT_MS`. */\nconst TTL_PATTERN =\n /^(\\d+(?:\\.\\d+)?)\\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/;\n\n/** Milliseconds per unit, a month being thirty days. */\nconst UNIT_MS = [1, 1e3, 6e4, 36e5, 864e5, 6048e5, 2592e6];\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const match = TTL_PATTERN.exec(ttl.trim().toLowerCase());\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`\n );\n }\n\n const result = Math.floor(\n Number.parseFloat(match[1]!) *\n UNIT_MS[match.slice(2).findIndex((unit) => unit !== undefined)]!\n );\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport { parse } from \"@validation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\ntype CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nconst cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nconst DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\ntype WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nconst withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n parseTTL\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) =>\n value === undefined || typeof value === \"boolean\"\n ? value\n : parseTTL(value)\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// THE CACHE'S TWO ARGUMENTS, AND THE READS IT SERVES\n// =============================================================================\n\n/**\n * The reads a cached view serves, as its refusal of anything else lists\n * them.\n */\nexport const CACHEABLE: readonly string[] = Object.freeze([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** One read's options, as the cache applies them. */\nexport interface CacheReadOptions {\n readonly ttlMs: number;\n readonly swr: number | false;\n readonly bypass: boolean;\n readonly key?: string;\n}\n\nfunction refused(what: string, issues: readonly { message: string }[]): never {\n throw new CacheConfigurationError(\n `Invalid ${what}: ${issues.map((issue) => issue.message).join(\", \")}`\n );\n}\n\n/**\n * A write's `cache` argument: what it invalidates once durable. Frozen, as\n * the argument a call admitted and nothing else holds.\n */\nexport function admitMutationOptions(value: unknown): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, value);\n if (parsed.issues) refused(\"mutation cache options\", parsed.issues);\n const { autoInvalidate, invalidate } = parsed.value;\n if (invalidate === undefined) return Object.freeze({ autoInvalidate });\n const keys = [...invalidate];\n Object.freeze(keys);\n return Object.freeze({ autoInvalidate, invalidate: keys });\n}\n\n/** `$withCache(options)`: the options of every read through the view. */\nexport function admitReadOptions(value: unknown): CacheReadOptions {\n const parsed = parse(withCacheSchema, value);\n if (parsed.issues) refused(\"cache options\", parsed.issues);\n const { bypass, key, ttl, swr } = parsed.value;\n return Object.freeze({\n ttlMs: ttl,\n // The SWR window: the stale window added to the TTL, `true` the TTL again.\n swr:\n swr === undefined || swr === false\n ? false\n : ttl + (swr === true ? ttl : swr),\n bypass,\n ...(key === undefined ? {} : { key }),\n });\n}\n","/**\n * The cache's units (`get`, `set`, `invalidate`, `revalidate`, and the\n * `delete` and `clear` an invalidation runs) and the outcomes of a read\n * (`hit`, a stale `hit`, `miss`, `bypass`, `cache-set-failed`), written with\n * the words any extension has: each step is a `cache` unit it emits with\n * `work` (on the call's context or `run`, a method's scope, or the unit of\n * the step it is part of), and what a presenter shows of it is noted on it\n * with `note`, in the shape the official instrumentation presents any\n * extension's units with (`InstrumentationNote`): the span as the unit\n * starts, then its attributes and its logs. A read's outcomes are noted on\n * the call's own `operation` unit.\n */\nimport type { UnitContext } from \"@extensions/contract\";\nimport type { Database } from \"@extensions/database\";\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport {\n ATTR_CACHE_DRIVER,\n ATTR_CACHE_TTL,\n ATTR_DB_COLLECTION,\n ATTR_DB_OPERATION_NAME,\n ATTR_VIBORM_CORRELATION_ID,\n SPAN_OPERATION,\n type VibORMSpanName,\n} from \"../instrumentation/spans\";\nimport type { InstrumentationNote } from \"../instrumentation/types\";\n\n/** The call a step's logs name: its model and the operation it asked. */\ninterface CacheCall {\n readonly model: string;\n readonly operation: string;\n}\n\n/**\n * One decision of a read, as a cache log presents it: the call is named\n * where the note is not on the call's own unit. Never a key or a suffix.\n */\nexport const cacheOutcome = (\n event: string,\n status?: string,\n error?: unknown,\n call?: CacheCall\n): InstrumentationNote => ({\n log: \"cache\",\n at: Date.now(),\n meta: { event, status },\n error,\n ...call,\n});\n\n/**\n * A background set failure joins its read's outcomes while that read's\n * operation still runs, so it presents after the logical miss; otherwise the\n * set unit presents it itself.\n */\nexport function placeSetFailure(\n background: object,\n failure: unknown,\n unit: UnitContext,\n call: CacheCall | undefined\n): void {\n if (!note(background, cacheOutcome(\"miss\", \"cache-set-failed\", failure)))\n note(unit, cacheOutcome(\"miss\", \"cache-set-failed\", failure, call));\n}\n\n/**\n * Run one cache step as a `cache` unit of the chain `origin` belongs to;\n * `execute` is handed the unit, to note what the step learns. A step asked\n * with no origin (a backend method called directly) belongs to no chain.\n */\nexport function cacheStep<T>(\n step: \"get\" | \"set\" | \"invalidate\" | \"delete\" | \"clear\",\n origin: object | undefined,\n driverName: string,\n execute: (unit?: UnitContext) => Promise<T>,\n ttl?: number\n): Promise<T> {\n if (origin === undefined) return execute();\n const attributes: InstrumentationNote[\"attributes\"] = {\n [ATTR_CACHE_DRIVER]: driverName,\n ...(ttl === undefined ? {} : { [ATTR_CACHE_TTL]: String(ttl) }),\n // A backend step of an invalidation names its driver alone.\n ...(step === \"delete\" || step === \"clear\"\n ? { [ATTR_VIBORM_CORRELATION_ID]: undefined }\n : {}),\n };\n return work(\n origin,\n // Its span is the public `SPAN_CACHE_<STEP>`: spelled from the step,\n // which costs no bytes, and checked against those constants.\n {\n kind: \"cache\",\n operation: step,\n note: {\n span: `viborm.cache.${step}` satisfies VibORMSpanName,\n attributes,\n },\n },\n execute\n );\n}\n\n/**\n * What a revalidation's own `cache` unit starts with: it is presented as the\n * root operation it replays.\n */\nexport const revalidationStart = (\n call: CacheCall,\n database: Database\n): InstrumentationNote => ({\n ...cacheOutcome(\"revalidate\", \"start\", undefined, call),\n span: SPAN_OPERATION,\n root: true,\n database,\n attributes: {\n [ATTR_DB_COLLECTION]: call.model,\n [ATTR_DB_OPERATION_NAME]: call.operation,\n },\n});\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport type { Database } from \"@extensions/database\";\nimport { note } from \"@extensions/unit-words\";\nimport { ATTR_CACHE_RESULT } from \"../instrumentation/spans\";\nimport {\n type Backend,\n REVALIDATING_SUFFIX,\n scheduleBackground,\n} from \"./cache-background\";\nimport { CACHE_PREFIX, fastHash } from \"./key\";\nimport {\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\nimport { cacheOutcome, cacheStep, placeSetFailure } from \"./units\";\n\n/** A timer a `CacheClock` armed, cancelled through its handle. */\nexport interface CacheTimer {\n cancel(): void;\n /** Release the host's hold on the event loop, where it has one. */\n unref?(): void;\n}\n\n/**\n * Where a cache reads time and arms its timers: the host's own, unless a\n * test hands a clock it advances instead of sleeping through a TTL.\n */\nexport interface CacheClock {\n now(): number;\n setTimeout(callback: () => void, ms: number): CacheTimer;\n}\n\nconst hostClock: CacheClock = {\n // Read when called: a test's fake timers replace `Date.now`.\n now: () => Date.now(),\n setTimeout: (callback, ms) => {\n const timer = setTimeout(callback, ms);\n // A host that is not Node hands back a number, with no `unref`.\n return { cancel: () => clearTimeout(timer), unref: () => timer.unref?.() };\n },\n};\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/**\n * One read's codec: `run` runs the prepared read (during the serve, or once\n * after it as a refresh), `snapshot` stores what that run returned.\n */\nexport interface DetachedCacheResultCodec<T> {\n run(): Promise<T>;\n snapshot(): unknown;\n materialize(snapshot: unknown): T;\n}\n\n/** One read the official cache serves, as its extension hands it over. */\ninterface CacheServe<T> {\n /** The prepared call's key: equal for two reads that send one statement. */\n readonly id: string;\n readonly codec: DetachedCacheResultCodec<T>;\n readonly read: CacheReadOptions;\n readonly namespace: string;\n readonly waitUntil: WaitUntilFn | undefined;\n readonly model: string;\n readonly operation: string;\n /** The call's `run`: what the read's units and outcomes belong to. */\n readonly origin: object;\n /** The database the read works against, which a revalidation presents. */\n readonly database: Database;\n /** What refreshes a stale entry: `staleWhileRevalidate`, when the cache was given it. */\n readonly revalidate?: Revalidate | undefined;\n}\n\n/**\n * One stale entry, as the driver hands it over: its read, its entry and\n * age, its prefixed key and the driver's backend (what the marker that\n * claims a refresh uses), and the store of the new rows.\n */\nexport interface Refresh {\n readonly request: CacheServe<unknown>;\n readonly entry: CacheEntry<unknown>;\n readonly now: number;\n readonly key: string;\n readonly backend: Backend;\n store(stored: unknown): Promise<void>;\n}\n\n/**\n * Whether a stale entry is served while it is refreshed in the background:\n * what `swr` brings, so a cache without it carries none of it.\n */\nexport type Revalidate = (refresh: Refresh) => boolean;\n\n/**\n * The keys of the two methods a driver serves its extension with: one read\n * through the store, and a namespace's invalidation. No package entry\n * exports them, so only the cache's own extension calls them.\n */\nexport const SERVE = Symbol(\"serve\");\nexport const INVALIDATE = Symbol(\"invalidate\");\n\n/**\n * The keys of the steps on a prefixed key the driver owns, observed as\n * `cache` units: what its extension and the unscoped storage functions\n * (`storage.ts`, which an application that never calls them does not carry)\n * reach. No package entry exports them either.\n */\nexport const GET = Symbol(\"get\");\nexport const SET = Symbol(\"set\");\nexport const DROP = Symbol(\"drop\");\nexport const BACKEND = Symbol(\"backend\");\n\n/** How a key is dropped: the entries under it, or the one entry it names. */\ntype Drop = \"clear\" | \"delete\";\n\n/**\n * A relative key rebased into an official scope. An EMPTY relative key is\n * the whole scope — `$invalidate(\"*\")` — and it rebases to `<scope>:`, WITH\n * the separator, because the storage backends clear by `startsWith`. A bare\n * `<scope>` would also match every sibling scope whose namespace string\n * merely extends this one, and one axis of the scope grammar can do that:\n * the cache `version` is the last component and its `s:` body is\n * variable-length, so `version: \"a\"` is a strict prefix of `version: \"ab\"`\n * at the same dialect and namespace. That axis is exactly what §7.1 leaves\n * users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's\n * entries. Adding the separator loses nothing: every key this scope can hold\n * is `<model>:<operation>:<hash>`, so no stored key is ever equal to the\n * bare scope.\n */\nexport function scopedKey(namespace: string, key: string): string {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Symbol-keyed steps handle prefixed keys, instrumentation, and delegation\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: CacheClock;\n\n constructor(driverName: string, clock: CacheClock = hostClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async [SERVE]<T>(request: CacheServe<T>): Promise<T> {\n const { id, read, namespace, codec, model, operation, origin } = request;\n const cacheKey = scopedKey(\n namespace,\n `${model}:${operation}:${fastHash(id)}${read.key === undefined ? \"\" : `:${read.key}`}`\n );\n const identity = JSON.stringify([id, read.key]);\n const revision = this.#fillRevision;\n const store = (stored: unknown, background?: CacheServe<unknown>) =>\n this[SET](\n cacheKey,\n stored,\n { ttl: read.ttlMs, swrTtl: read.swr || undefined },\n origin,\n background,\n identity,\n revision\n );\n let outcome = \"bypass\";\n if (!read.bypass) {\n const cached = await this[GET]<unknown>(cacheKey, origin);\n // Read as the backend gives it: an entry of another identity, or whose\n // times are not a finite span, is a miss.\n if (cached?.identity === identity) {\n const { createdAt, ttl, expiresAt } = cached;\n if (\n [createdAt, ttl, expiresAt].every(Number.isFinite) &&\n ttl > 0 &&\n expiresAt! >= createdAt\n ) {\n const value = codec.materialize(cached.value);\n const now = this.clock.now();\n if (now - createdAt < ttl) {\n note(origin, cacheOutcome(\"hit\"));\n return value;\n }\n if (\n request.revalidate?.({\n request,\n entry: cached,\n now,\n key: cacheKey,\n backend: this[BACKEND](),\n store,\n })\n )\n return value;\n }\n }\n outcome = \"miss\";\n }\n const result = await codec.run();\n if (revision === this.#fillRevision) {\n try {\n // The observed set unit presents a failure, which the background\n // promise then holds.\n scheduleBackground(store(codec.snapshot(), request), request.waitUntil);\n } catch (error) {\n note(origin, cacheOutcome(\"miss\", \"cache-set-failed\", error));\n }\n }\n note(origin, cacheOutcome(outcome));\n return result;\n }\n\n // ============================================================\n // STEPS - on prefixed keys, observed as `cache` units\n // ============================================================\n\n async [GET]<T>(\n prefixedKey: string,\n origin?: object\n ): Promise<CacheEntry<T> | null> {\n return cacheStep(\"get\", origin, this.driverName, async (unit) => {\n const entry = await this.get<T>(prefixedKey);\n if (unit !== undefined)\n note(unit, {\n attributes: {\n [ATTR_CACHE_RESULT]: entry\n ? this.clock.now() - entry.createdAt > entry.ttl\n ? \"stale\"\n : \"hit\"\n : \"miss\",\n },\n });\n return entry;\n });\n }\n\n async [SET]<T>(\n prefixedKey: string,\n value: T,\n options: CacheSetOptions,\n origin?: object,\n /** The read a background set belongs to, whose outcomes a failure joins. */\n background?: CacheServe<unknown>,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n const createdAt = this.clock.now();\n const entry: CacheEntry<T> = {\n value,\n createdAt,\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : { identity, expiresAt: createdAt + storageTtl }),\n };\n\n return cacheStep(\n \"set\",\n origin,\n this.driverName,\n async (unit) => {\n try {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n } catch (failure) {\n if (background !== undefined && unit !== undefined)\n placeSetFailure(background.origin, failure, unit, background);\n throw failure;\n }\n },\n options.ttl\n );\n }\n\n /** The backend's own primitives, unobserved, and the clock. */\n [BACKEND](): Backend {\n return {\n get: (key) => this.get(key),\n set: (key, ttl, entry) => this.set(key, ttl, entry),\n delete: (keys) => this.delete(keys),\n now: () => this.clock.now(),\n };\n }\n\n /**\n * Invalidate after a mutation: the entries under `prefix` (relative keys\n * rebased by `prefixed`), and the targets `options` names.\n */\n async [INVALIDATE](\n prefix: string,\n options: CacheInvalidationOptions | undefined,\n origin: object | undefined,\n prefixed: (key: string) => string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n // Every target is rebased, and so validated, before any is dropped.\n const targets: [Drop, string][] =\n options === undefined || options.autoInvalidate === true\n ? [[\"clear\", prefixed(prefix)]]\n : [];\n for (const entry of options?.invalidate ?? [])\n targets.push(\n entry.endsWith(\"*\")\n ? [\"clear\", prefixed(entry.slice(0, -1))]\n : [\"delete\", prefixed(entry)]\n );\n return cacheStep(\"invalidate\", origin, this.driverName, async (unit) => {\n await Promise.all(\n targets.map(([drop, key]) => this[DROP](drop, key, unit))\n );\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n /**\n * Drop the entries under `prefixedKey` (`clear`), or that entry and its\n * revalidation marker (`delete`). Not `async`: a step that fails is\n * rejected by the promise the caller holds, with no promise between them\n * left a tick without a handler (workerd reports one).\n */\n [DROP](drop: Drop, prefixedKey: string, origin?: object): Promise<void> {\n this.#fillRevision += 1;\n return cacheStep(drop, origin, this.driverName, () =>\n drop === \"clear\"\n ? this.clear(prefixedKey)\n : this.delete([prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`])\n );\n }\n}\n"],"mappings":"wUAEA,MAAa,EAAsB,SAC7B,EAAsB,IAE5B,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GAiBV,eAAsB,OACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAS,GAAG,IAAM,IACxB,GAAI,CA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AGV,EAAQ,IACT,CAIH,CAAC,IAAoB,CACnB,MAAO,CACL,IAAM,GAAQ,KAAK,IAAI,EAAI,CAC3B,KAAM,EAAK,EAAK,IAAU,KAAK,IAAI,EAAK,EAAK,EAAM,CACnD,OAAS,GAAS,KAAK,OAAO,EAAK,CACnC,QAAW,KAAK,MAAM,KAAK,CAC5B,CAOH,MAAO,GACL,EACA,EACA,EACA,EACe,CACf,GAAI,CAAC,yBAAyB,EAAQ,CAAE,OACxC,MAAA,GAAsB,EAEtB,IAAM,EACJ,IAAY,IAAA,IAAa,EAAQ,iBAAmB,GAChD,CAAC,CAAC,QAAS,EAAS,EAAO,CAAC,CAAC,CAC7B,EAAE,CACR,IAAK,IAAM,KAAS,GAAS,YAAc,EAAE,CAC3C,EAAQ,KACN,EAAM,SAAS,IAAI,CACf,CAAC,QAAS,EAAS,EAAM,MAAM,EAAG,GAAG,CAAC,CAAC,CACvC,CAAC,SAAU,EAAS,EAAM,CAAC,CAChC,CACH,OAAO,UAAU,aAAc,EAAQ,KAAK,WAAY,KAAO,IAAS,CACtE,MAAM,QAAQ,IACZ,EAAQ,KAAK,CAAC,EAAM,KAAS,KAAK,GAAM,EAAM,EAAK,EAAK,CAAC,CAC1D,EACD,CAmBJ,CAAC,GAAM,EAAY,EAAqB,EAAgC,CAEtE,MADA,OAAA,GAAsB,EACf,UAAU,EAAM,EAAQ,KAAK,eAClC,IAAS,QACL,KAAK,MAAM,EAAY,CACvB,KAAK,OAAO,CAAC,EAAa,GAAG,IAAc,IAAsB,CAAC,CACvE"}
|
|
1
|
+
{"version":3,"file":"driver-D1grnHEr.mjs","names":["v","#fillRevision"],"sources":["../src/cache/cache-background.ts","../src/cache/key.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/units.ts","../src/cache/driver.ts"],"sourcesContent":["import type { CacheEntry, WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nconst REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n\n/** A driver's own storage primitives, unobserved, and its clock. */\nexport interface Backend {\n get(key: string): Promise<CacheEntry | null>;\n set(key: string, ttl: number, entry: CacheEntry): Promise<void>;\n delete(keys: string[]): Promise<void>;\n now(): number;\n}\n\n/**\n * Claim the refresh of the entry at `key` (whether this caller performs\n * it), or release the claim: a marker beside the entry, with a short TTL.\n */\nexport async function marker(\n backend: Backend,\n key: string,\n claim: boolean\n): Promise<boolean> {\n const marked = `${key}${REVALIDATING_SUFFIX}`;\n if (!claim) {\n await backend.delete([marked]);\n return false;\n }\n const existing = await backend.get(marked);\n if (existing && backend.now() - existing.createdAt < existing.ttl)\n return false;\n await backend.set(marked, REVALIDATING_TTL_MS, {\n value: true,\n createdAt: backend.now(),\n ttl: REVALIDATING_TTL_MS,\n });\n return true;\n}\n","/**\n * Cache key spaces: the official namespace one cache scope partitions on,\n * and the hash that names an entry inside it. What a read is keyed on is the\n * prepared call itself (`key(run)`).\n */\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for the official cache extension's scopes. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\n// r5 entries are keyed by the prepared call (`key(run)`): the statement the\n// engine sends, so a rule's filter, order and projection key an entry by\n// what they do to that statement.\n// r6 entries hold the rows the driver returned, not the decoded answer: an r5\n// answer read as rows would be refused at best.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r6\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n // `split(\"\")` gives the code units, never a pair as one code point.\n return value\n .split(\"\")\n .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, \"0\"))\n .join(\"\");\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n return `n:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n // `x` unknown, `k:<hex>` known. An unknown namespace is a bare `x` with\n // no body, so it cannot be reached by encoding any string whatsoever — a\n // database literally named `undefined` encodes as `k:0075...`. Absence is\n // a distinct value here, not a spelling.\n facts.namespace === undefined ? \"x\" : `k:${encodeText(facts.namespace)}`,\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nexport function fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/** `<number> <unit>`, each unit's spellings one group, in the order of `UNIT_MS`. */\nconst TTL_PATTERN =\n /^(\\d+(?:\\.\\d+)?)\\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/;\n\n/** Milliseconds per unit, a month being thirty days. */\nconst UNIT_MS = [1, 1e3, 6e4, 36e5, 864e5, 6048e5, 2592e6];\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const match = TTL_PATTERN.exec(ttl.trim().toLowerCase());\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`\n );\n }\n\n const result = Math.floor(\n Number.parseFloat(match[1]!) *\n UNIT_MS[match.slice(2).findIndex((unit) => unit !== undefined)]!\n );\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport { parse } from \"@validation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\ntype CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nconst cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nconst DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\ntype WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nconst withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n parseTTL\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) =>\n value === undefined || typeof value === \"boolean\"\n ? value\n : parseTTL(value)\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// THE CACHE'S TWO ARGUMENTS, AND THE READS IT SERVES\n// =============================================================================\n\n/**\n * The reads a cached view serves, as its refusal of anything else lists\n * them.\n */\nexport const CACHEABLE: readonly string[] = Object.freeze([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** One read's options, as the cache applies them. */\nexport interface CacheReadOptions {\n readonly ttlMs: number;\n readonly swr: number | false;\n readonly bypass: boolean;\n readonly key?: string;\n}\n\nfunction refused(what: string, issues: readonly { message: string }[]): never {\n throw new CacheConfigurationError(\n `Invalid ${what}: ${issues.map((issue) => issue.message).join(\", \")}`\n );\n}\n\n/**\n * A write's `cache` argument: what it invalidates once durable. Frozen, as\n * the argument a call admitted and nothing else holds.\n */\nexport function admitMutationOptions(value: unknown): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, value);\n if (parsed.issues) refused(\"mutation cache options\", parsed.issues);\n const { autoInvalidate, invalidate } = parsed.value;\n if (invalidate === undefined) return Object.freeze({ autoInvalidate });\n const keys = [...invalidate];\n Object.freeze(keys);\n return Object.freeze({ autoInvalidate, invalidate: keys });\n}\n\n/** `$withCache(options)`: the options of every read through the view. */\nexport function admitReadOptions(value: unknown): CacheReadOptions {\n const parsed = parse(withCacheSchema, value);\n if (parsed.issues) refused(\"cache options\", parsed.issues);\n const { bypass, key, ttl, swr } = parsed.value;\n return Object.freeze({\n ttlMs: ttl,\n // The SWR window: the stale window added to the TTL, `true` the TTL again.\n swr:\n swr === undefined || swr === false\n ? false\n : ttl + (swr === true ? ttl : swr),\n bypass,\n ...(key === undefined ? {} : { key }),\n });\n}\n","/**\n * The cache's units (`get`, `set`, `invalidate`, `revalidate`, and the\n * `delete` and `clear` an invalidation runs) and the outcomes of a read\n * (`hit`, a stale `hit`, `miss`, `bypass`, `cache-set-failed`), written with\n * the words any extension has: each step is a `cache` unit it emits with\n * `work` (on the call's context or `run`, a method's scope, or the unit of\n * the step it is part of), and what a presenter shows of it is noted on it\n * with `note`, in the shape the official instrumentation presents any\n * extension's units with (`InstrumentationNote`): the span as the unit\n * starts, then its attributes and its logs. A read's outcomes are noted on\n * the call's own `operation` unit.\n */\nimport type { UnitContext } from \"@extensions/contract\";\nimport type { Database } from \"@extensions/database\";\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport {\n ATTR_CACHE_DRIVER,\n ATTR_CACHE_TTL,\n ATTR_DB_COLLECTION,\n ATTR_DB_OPERATION_NAME,\n ATTR_VIBORM_CORRELATION_ID,\n SPAN_OPERATION,\n type VibORMSpanName,\n} from \"../instrumentation/spans\";\nimport type { InstrumentationNote } from \"../instrumentation/types\";\n\n/** The call a step's logs name: its model and the operation it asked. */\ninterface CacheCall {\n readonly model: string;\n readonly operation: string;\n}\n\n/**\n * One decision of a read, as a cache log presents it: the call is named\n * where the note is not on the call's own unit. Never a key or a suffix.\n */\nexport const cacheOutcome = (\n event: string,\n status?: string,\n error?: unknown,\n call?: CacheCall\n): InstrumentationNote => ({\n log: \"cache\",\n at: Date.now(),\n meta: { event, status },\n error,\n ...call,\n});\n\n/**\n * A background set failure joins its read's outcomes while that read's\n * operation still runs, so it presents after the logical miss; otherwise the\n * set unit presents it itself.\n */\nexport function placeSetFailure(\n background: object,\n failure: unknown,\n unit: UnitContext,\n call: CacheCall | undefined\n): void {\n if (!note(background, cacheOutcome(\"miss\", \"cache-set-failed\", failure)))\n note(unit, cacheOutcome(\"miss\", \"cache-set-failed\", failure, call));\n}\n\n/**\n * Run one cache step as a `cache` unit of the chain `origin` belongs to;\n * `execute` is handed the unit, to note what the step learns. A step asked\n * with no origin (a backend method called directly) belongs to no chain.\n */\nexport function cacheStep<T>(\n step: \"get\" | \"set\" | \"invalidate\" | \"delete\" | \"clear\",\n origin: object | undefined,\n driverName: string,\n execute: (unit?: UnitContext) => Promise<T>,\n ttl?: number\n): Promise<T> {\n if (origin === undefined) return execute();\n const attributes: InstrumentationNote[\"attributes\"] = {\n [ATTR_CACHE_DRIVER]: driverName,\n ...(ttl === undefined ? {} : { [ATTR_CACHE_TTL]: String(ttl) }),\n // A backend step of an invalidation names its driver alone.\n ...(step === \"delete\" || step === \"clear\"\n ? { [ATTR_VIBORM_CORRELATION_ID]: undefined }\n : {}),\n };\n return work(\n origin,\n // Its span is the public `SPAN_CACHE_<STEP>`: spelled from the step,\n // which costs no bytes, and checked against those constants.\n {\n kind: \"cache\",\n operation: step,\n note: {\n span: `viborm.cache.${step}` satisfies VibORMSpanName,\n attributes,\n },\n },\n execute\n );\n}\n\n/**\n * What a revalidation's own `cache` unit starts with: it is presented as the\n * root operation it replays.\n */\nexport const revalidationStart = (\n call: CacheCall,\n database: Database\n): InstrumentationNote => ({\n ...cacheOutcome(\"revalidate\", \"start\", undefined, call),\n span: SPAN_OPERATION,\n root: true,\n database,\n attributes: {\n [ATTR_DB_COLLECTION]: call.model,\n [ATTR_DB_OPERATION_NAME]: call.operation,\n },\n});\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport type { Database } from \"@extensions/database\";\nimport { note } from \"@extensions/unit-words\";\nimport { ATTR_CACHE_RESULT } from \"../instrumentation/spans\";\nimport {\n type Backend,\n REVALIDATING_SUFFIX,\n scheduleBackground,\n} from \"./cache-background\";\nimport { CACHE_PREFIX, fastHash } from \"./key\";\nimport {\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\nimport { cacheOutcome, cacheStep, placeSetFailure } from \"./units\";\n\n/** A timer a `CacheClock` armed, cancelled through its handle. */\nexport interface CacheTimer {\n cancel(): void;\n /** Release the host's hold on the event loop, where it has one. */\n unref?(): void;\n}\n\n/**\n * Where a cache reads time and arms its timers: the host's own, unless a\n * test hands a clock it advances instead of sleeping through a TTL.\n */\nexport interface CacheClock {\n now(): number;\n setTimeout(callback: () => void, ms: number): CacheTimer;\n}\n\nconst hostClock: CacheClock = {\n // Read when called: a test's fake timers replace `Date.now`.\n now: () => Date.now(),\n setTimeout: (callback, ms) => {\n const timer = setTimeout(callback, ms);\n // A host that is not Node hands back a number, with no `unref`.\n return { cancel: () => clearTimeout(timer), unref: () => timer.unref?.() };\n },\n};\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/**\n * One read's codec: `run` runs the prepared read (during the serve, or once\n * after it as a refresh), `snapshot` stores what that run returned.\n */\nexport interface DetachedCacheResultCodec<T> {\n run(): Promise<T>;\n snapshot(): unknown;\n materialize(snapshot: unknown): T;\n}\n\n/** One read the official cache serves, as its extension hands it over. */\ninterface CacheServe<T> {\n /** The prepared call's key: equal for two reads that send one statement. */\n readonly id: string;\n readonly codec: DetachedCacheResultCodec<T>;\n readonly read: CacheReadOptions;\n readonly namespace: string;\n readonly waitUntil: WaitUntilFn | undefined;\n readonly model: string;\n readonly operation: string;\n /** The call's `run`: what the read's units and outcomes belong to. */\n readonly origin: object;\n /** The database the read works against, which a revalidation presents. */\n readonly database: Database;\n /** What refreshes a stale entry: `staleWhileRevalidate`, when the cache was given it. */\n readonly revalidate?: Revalidate | undefined;\n}\n\n/**\n * One stale entry, as the driver hands it over: its read, its entry and\n * age, its prefixed key and the driver's backend (what the marker that\n * claims a refresh uses), and the store of the new rows.\n */\nexport interface Refresh {\n readonly request: CacheServe<unknown>;\n readonly entry: CacheEntry<unknown>;\n readonly now: number;\n readonly key: string;\n readonly backend: Backend;\n store(stored: unknown): Promise<void>;\n}\n\n/**\n * Whether a stale entry is served while it is refreshed in the background:\n * what `swr` brings, so a cache without it carries none of it.\n */\nexport type Revalidate = (refresh: Refresh) => boolean;\n\n/**\n * The keys of the two methods a driver serves its extension with: one read\n * through the store, and a namespace's invalidation. No package entry\n * exports them, so only the cache's own extension calls them.\n */\nexport const SERVE = Symbol(\"serve\");\nexport const INVALIDATE = Symbol(\"invalidate\");\n\n/**\n * The keys of the steps on a prefixed key the driver owns, observed as\n * `cache` units: what its extension and the unscoped storage functions\n * (`storage.ts`, which an application that never calls them does not carry)\n * reach. No package entry exports them either.\n */\nexport const GET = Symbol(\"get\");\nexport const SET = Symbol(\"set\");\nexport const DROP = Symbol(\"drop\");\nexport const BACKEND = Symbol(\"backend\");\n\n/** How a key is dropped: the entries under it, or the one entry it names. */\ntype Drop = \"clear\" | \"delete\";\n\n/**\n * A relative key rebased into an official scope. An EMPTY relative key is\n * the whole scope — `$invalidate(\"*\")` — and it rebases to `<scope>:`, WITH\n * the separator, because the storage backends clear by `startsWith`. A bare\n * `<scope>` would also match every sibling scope whose namespace string\n * merely extends this one, and one axis of the scope grammar can do that:\n * the cache `version` is the last component and its `s:` body is\n * variable-length, so `version: \"a\"` is a strict prefix of `version: \"ab\"`\n * at the same dialect and namespace. That axis is exactly what §7.1 leaves\n * users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's\n * entries. Adding the separator loses nothing: every key this scope can hold\n * is `<model>:<operation>:<hash>`, so no stored key is ever equal to the\n * bare scope.\n */\nexport function scopedKey(namespace: string, key: string): string {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Symbol-keyed steps handle prefixed keys, instrumentation, and delegation\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: CacheClock;\n\n constructor(driverName: string, clock: CacheClock = hostClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async [SERVE]<T>(request: CacheServe<T>): Promise<T> {\n const { id, read, namespace, codec, model, operation, origin } = request;\n const cacheKey = scopedKey(\n namespace,\n `${model}:${operation}:${fastHash(id)}${read.key === undefined ? \"\" : `:${read.key}`}`\n );\n const identity = JSON.stringify([id, read.key]);\n const revision = this.#fillRevision;\n const store = (stored: unknown, background?: CacheServe<unknown>) =>\n this[SET](\n cacheKey,\n stored,\n { ttl: read.ttlMs, swrTtl: read.swr || undefined },\n origin,\n background,\n identity,\n revision\n );\n let outcome = \"bypass\";\n if (!read.bypass) {\n const cached = await this[GET]<unknown>(cacheKey, origin);\n // Read as the backend gives it: an entry of another identity, or whose\n // times are not a finite span, is a miss.\n if (cached?.identity === identity) {\n const { createdAt, ttl, expiresAt } = cached;\n if (\n [createdAt, ttl, expiresAt].every(Number.isFinite) &&\n ttl > 0 &&\n expiresAt! >= createdAt\n ) {\n const value = codec.materialize(cached.value);\n const now = this.clock.now();\n if (now - createdAt < ttl) {\n note(origin, cacheOutcome(\"hit\"));\n return value;\n }\n if (\n request.revalidate?.({\n request,\n entry: cached,\n now,\n key: cacheKey,\n backend: this[BACKEND](),\n store,\n })\n )\n return value;\n }\n }\n outcome = \"miss\";\n }\n const result = await codec.run();\n if (revision === this.#fillRevision) {\n try {\n // The observed set unit presents a failure, which the background\n // promise then holds.\n scheduleBackground(store(codec.snapshot(), request), request.waitUntil);\n } catch (error) {\n note(origin, cacheOutcome(\"miss\", \"cache-set-failed\", error));\n }\n }\n note(origin, cacheOutcome(outcome));\n return result;\n }\n\n // ============================================================\n // STEPS - on prefixed keys, observed as `cache` units\n // ============================================================\n\n async [GET]<T>(\n prefixedKey: string,\n origin?: object\n ): Promise<CacheEntry<T> | null> {\n return cacheStep(\"get\", origin, this.driverName, async (unit) => {\n const entry = await this.get<T>(prefixedKey);\n if (unit !== undefined)\n note(unit, {\n attributes: {\n [ATTR_CACHE_RESULT]: entry\n ? this.clock.now() - entry.createdAt > entry.ttl\n ? \"stale\"\n : \"hit\"\n : \"miss\",\n },\n });\n return entry;\n });\n }\n\n async [SET]<T>(\n prefixedKey: string,\n value: T,\n options: CacheSetOptions,\n origin?: object,\n /** The read a background set belongs to, whose outcomes a failure joins. */\n background?: CacheServe<unknown>,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n const createdAt = this.clock.now();\n const entry: CacheEntry<T> = {\n value,\n createdAt,\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : { identity, expiresAt: createdAt + storageTtl }),\n };\n\n return cacheStep(\n \"set\",\n origin,\n this.driverName,\n async (unit) => {\n try {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n } catch (failure) {\n if (background !== undefined && unit !== undefined)\n placeSetFailure(background.origin, failure, unit, background);\n throw failure;\n }\n },\n options.ttl\n );\n }\n\n /** The backend's own primitives, unobserved, and the clock. */\n [BACKEND](): Backend {\n return {\n get: (key) => this.get(key),\n set: (key, ttl, entry) => this.set(key, ttl, entry),\n delete: (keys) => this.delete(keys),\n now: () => this.clock.now(),\n };\n }\n\n /**\n * Invalidate after a mutation: the entries under `prefix` (relative keys\n * rebased by `prefixed`), and the targets `options` names.\n */\n async [INVALIDATE](\n prefix: string,\n options: CacheInvalidationOptions | undefined,\n origin: object | undefined,\n prefixed: (key: string) => string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n // Every target is rebased, and so validated, before any is dropped.\n const targets: [Drop, string][] =\n options === undefined || options.autoInvalidate === true\n ? [[\"clear\", prefixed(prefix)]]\n : [];\n for (const entry of options?.invalidate ?? [])\n targets.push(\n entry.endsWith(\"*\")\n ? [\"clear\", prefixed(entry.slice(0, -1))]\n : [\"delete\", prefixed(entry)]\n );\n return cacheStep(\"invalidate\", origin, this.driverName, async (unit) => {\n await Promise.all(\n targets.map(([drop, key]) => this[DROP](drop, key, unit))\n );\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n /**\n * Drop the entries under `prefixedKey` (`clear`), or that entry and its\n * revalidation marker (`delete`). Not `async`: a step that fails is\n * rejected by the promise the caller holds, with no promise between them\n * left a tick without a handler (workerd reports one).\n */\n [DROP](drop: Drop, prefixedKey: string, origin?: object): Promise<void> {\n this.#fillRevision += 1;\n return cacheStep(drop, origin, this.driverName, () =>\n drop === \"clear\"\n ? this.clear(prefixedKey)\n : this.delete([prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`])\n );\n }\n}\n"],"mappings":"wUAEA,MAAa,EAAsB,SAC7B,EAAsB,IAE5B,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GAiBV,eAAsB,OACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAS,GAAG,IAAM,IACxB,GAAI,CAAC,EAEH,OADA,MAAM,EAAQ,OAAO,CAAC,EAAO,CAAC,CACvB,GAET,IAAM,EAAW,MAAM,EAAQ,IAAI,EAAO,CAQ1C,OAPI,GAAY,EAAQ,KAAK,CAAG,EAAS,UAAY,EAAS,IACrD,IACT,MAAM,EAAQ,IAAI,EAAQ,EAAqB,CAC7C,MAAO,GACP,UAAW,EAAQ,KAAK,CACxB,IAAK,EACN,CAAC,CACK,ICvCT,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QAgD7D,SAAS,WAA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