viborm 1.15.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DD-BQ2Wk.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +13 -9
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-BvA37zBZ.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-BmEpMmjI.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-BWFI7-vU.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-DZ39sYy2.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-BGGv2du0.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-D62c-uC6.d.mts → database-adapter-BMjJiBFm.d.mts} +4692 -4733
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-CrtGVdEC.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-o5Bd5ZoJ.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-0cdCF_KD.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-BHEmfLOW.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/{execution-context-VMQm-9CH.mjs.map → execution-context-couU2tgh.mjs.map} +1 -1
- package/dist/{exports-Bzvtum3F.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/{identifiers-BTCfD5ic.mjs.map → identifiers-BxOf57qy.mjs.map} +1 -1
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/{judge-words-DpwxOfre.mjs.map → judge-words-k5GCc4cV.mjs.map} +1 -1
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-1Z6WKrnE.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-gjKMy3Ql.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs.map +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-D5x-Yf7w.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-DvrfHGje.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +3 -112
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-Ckoxeruk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-Byp7Zpop.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +14 -62
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-BaU-LuuI.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-C4lXzgW2.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/{select-assembly-SuVxJjps.mjs.map → select-assembly-CEpNu-Gw.mjs.map} +1 -1
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-Dkk5w1vE.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-6sBLJi34.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-BE-EjlZK.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-BE-EjlZK.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-CXtSIPzy.d.mts → sql-C4_sFNDm.d.mts} +7 -0
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-CSaAB0su.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-BGMVZ1MX.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-BLlgSQIo.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-Byqn5wAh.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-B_ZLWzLW.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +48 -35
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DD-BQ2Wk.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-BvA37zBZ.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-BmEpMmjI.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-BWFI7-vU.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-CVCC-D1j.mjs +0 -2
- package/dist/client-CVCC-D1j.mjs.map +0 -1
- package/dist/client-DtPTegtA.mjs +0 -9
- package/dist/client-DtPTegtA.mjs.map +0 -1
- package/dist/confine-BGGv2du0.mjs +0 -2
- package/dist/coordination-BY6Np3xV.mjs +0 -2
- package/dist/coordination-BY6Np3xV.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-BS2T81sD.mjs +0 -2
- package/dist/datetime-physical-codec-BS2T81sD.mjs.map +0 -1
- package/dist/defaults-CrtGVdEC.mjs +0 -2
- package/dist/driver-D1grnHEr.mjs +0 -2
- package/dist/driver-D1grnHEr.mjs.map +0 -1
- package/dist/driver-Df88hu4U.mjs +0 -2
- package/dist/driver-Df88hu4U.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- package/dist/error-mapping-DIRlrmDK.mjs +0 -2
- package/dist/error-mapping-DIRlrmDK.mjs.map +0 -1
- package/dist/every-BHEmfLOW.mjs +0 -2
- package/dist/execution-context-VMQm-9CH.mjs +0 -2
- package/dist/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-BDvW7IH-.mjs +0 -2
- package/dist/geo-area-codec-BDvW7IH-.mjs.map +0 -1
- package/dist/hydration-D7U8HACL.mjs +0 -2
- package/dist/hydration-D7U8HACL.mjs.map +0 -1
- package/dist/identifier-conversion-Ci_iaJ0b.mjs +0 -2
- package/dist/identifier-conversion-Ci_iaJ0b.mjs.map +0 -1
- package/dist/identifiers-BTCfD5ic.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-C4T5gt9O.mjs +0 -2
- package/dist/introspect-C4T5gt9O.mjs.map +0 -1
- package/dist/json-CHdgejCt.mjs +0 -2
- package/dist/json-CHdgejCt.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-DpwxOfre.mjs +0 -2
- package/dist/key-B3xgpu0M.mjs +0 -2
- package/dist/key-B3xgpu0M.mjs.map +0 -1
- package/dist/keys-1Z6WKrnE.mjs +0 -2
- package/dist/libsql-DJRsCDT_.mjs +0 -3
- package/dist/libsql-DJRsCDT_.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-gjKMy3Ql.mjs +0 -2
- package/dist/methods-part-DoTrY6b9.mjs +0 -2
- package/dist/methods-part-DoTrY6b9.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BH0Z3PlH.mjs +0 -100
- package/dist/mysql-BH0Z3PlH.mjs.map +0 -1
- package/dist/mysql-adapter-B06Ve3ds.mjs +0 -2
- package/dist/mysql-adapter-B06Ve3ds.mjs.map +0 -1
- package/dist/named-statements-CMj1QEyw.mjs +0 -2
- package/dist/named-statements-CMj1QEyw.mjs.map +0 -1
- package/dist/native-types-DspZ0Z5E.mjs +0 -2
- package/dist/native-types-DspZ0Z5E.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-WIE0DGGG.mjs +0 -2
- package/dist/object-store-WIE0DGGG.mjs.map +0 -1
- package/dist/on-DvrfHGje.mjs +0 -2
- package/dist/pending-operation-Dq4rv-Ml.mjs +0 -2
- package/dist/pending-operation-Dq4rv-Ml.mjs.map +0 -1
- package/dist/physical-wboFLAg9.mjs +0 -2
- package/dist/physical-wboFLAg9.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-DQ_pO0hi.mjs +0 -437
- package/dist/postgres-DQ_pO0hi.mjs.map +0 -1
- package/dist/postgres-adapter-Byp7Zpop.mjs +0 -2
- package/dist/postgres-adapter-Ia4u0-Ht.mjs +0 -2
- package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +0 -1
- package/dist/postgres-result-CiS5OWp1.mjs +0 -2
- package/dist/postgres-result-CiS5OWp1.mjs.map +0 -1
- package/dist/provider-limits-CCOa4d1E.mjs +0 -2
- package/dist/provider-limits-CCOa4d1E.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-C0ehKSAA.mjs +0 -2
- package/dist/provider-parameter-snapshot-C0ehKSAA.mjs.map +0 -1
- package/dist/query-Cdy8E2jM.mjs +0 -2
- package/dist/query-Cdy8E2jM.mjs.map +0 -1
- package/dist/query-inspection-C-T2ttRx.mjs +0 -2
- package/dist/query-inspection-C-T2ttRx.mjs.map +0 -1
- package/dist/raw-uaVIxHcE.mjs +0 -2
- package/dist/raw-uaVIxHcE.mjs.map +0 -1
- package/dist/relation-bound-BaU-LuuI.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-C4lXzgW2.mjs +0 -2
- package/dist/scalar-B9WizsvR.mjs +0 -4
- package/dist/scalar-B9WizsvR.mjs.map +0 -1
- package/dist/schema-MB-pPNTO.mjs +0 -2
- package/dist/schema-MB-pPNTO.mjs.map +0 -1
- package/dist/schema-TthAXPVP.mjs +0 -2
- package/dist/schema-TthAXPVP.mjs.map +0 -1
- package/dist/schema-introspection-wMVZowIF.mjs +0 -6
- package/dist/schema-introspection-wMVZowIF.mjs.map +0 -1
- package/dist/select-assembly-SuVxJjps.mjs +0 -2
- package/dist/serializer-B2kk7NAR.mjs +0 -51
- package/dist/serializer-B2kk7NAR.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-Dkk5w1vE.mjs +0 -2
- package/dist/snowflake-6sBLJi34.mjs +0 -2
- package/dist/sql-BGjAsoBE.mjs +0 -2
- package/dist/sql-BGjAsoBE.mjs.map +0 -1
- package/dist/sql-CFxGrk3K.mjs +0 -2
- package/dist/sql-CFxGrk3K.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-fIbNDvwO.mjs +0 -2
- package/dist/sqlite-adapter-fIbNDvwO.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-DcQct689.mjs +0 -2
- package/dist/sqlite-utils-DcQct689.mjs.map +0 -1
- package/dist/standard-sql-Bsf5nrla.mjs +0 -6
- package/dist/standard-sql-Bsf5nrla.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-DY7sgVnJ.mjs +0 -2
- package/dist/surrealql-DY7sgVnJ.mjs.map +0 -1
- package/dist/to-many-DiP6cOSQ.mjs +0 -2
- package/dist/to-many-DiP6cOSQ.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-CSaAB0su.mjs +0 -2
- package/dist/unit-words-BGMVZ1MX.mjs +0 -2
- package/dist/utils-BLlgSQIo.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-D0LG854o.mjs +0 -2
- package/dist/validation-D0LG854o.mjs.map +0 -1
- package/dist/validator-CDYlO9HV.mjs +0 -2
- package/dist/validator-CDYlO9HV.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-Byqn5wAh.mjs +0 -2
- package/dist/version-B_ZLWzLW.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
- /package/dist/{named-statements-Bdz2GD5R.d.mts → named-statements-NF7Iycjk.d.mts} +0 -0
package/dist/cache.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.mjs","names":["codec","key","key","codec","key"],"sources":["../src/cache/result-codec.ts","../src/cache/extension.ts","../src/cache/revalidate.ts","../src/cache/storage.ts"],"sourcesContent":["import { CacheConfigurationError } from \"../errors/cache\";\nimport type { Codec } from \"../index\";\n\n/** One codec step, its failure the cache's: named, exposing no value. */\nfunction step<T>(\n method: \"snapshot\" | \"materialize\",\n operation: string,\n message: string,\n run: () => T\n): T {\n try {\n return run();\n } catch (cause) {\n throw new CacheConfigurationError(message, {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method, operation },\n });\n }\n}\n\n/**\n * A call's codec whose failures are the cache's: a value the codec cannot\n * represent, and a stored entry that does not follow the shape, are each a\n * `CacheConfigurationError` that names the step and exposes no value.\n */\nexport function cacheCodec<R>(codec: Codec<R>, operation: string): Codec<R> {\n return {\n run: () => codec.run(),\n snapshot: () =>\n step(\n \"snapshot\",\n operation,\n \"The operation result cannot be represented by the cache result codec.\",\n () => codec.snapshot()\n ),\n materialize: (snapshot) =>\n step(\n \"materialize\",\n operation,\n \"The cached result snapshot is malformed.\",\n () => codec.materialize(snapshot)\n ),\n };\n}\n","/**\n * VibORM's cache, written with the public extension contract:\n * `client.$extends(cache({ driver }))`.\n *\n * - `$withCache(options)` binds the view's read options (`cacheRead`, a\n * bound argument): what marks a read the cache serves.\n * - A read through that view is served closest to the core (`inner`), keyed\n * on the prepared call (`key(run)`), and run uncached when it has no key\n * or runs in a transaction or an array.\n * - A write invalidates the scope once durable (`settled`), as its own\n * `cache` argument says; `$invalidate` once the view's work is durable.\n * - The scope is a pure function of the cache `version` and the database the\n * call works against (`database`), so two clients of one database share\n * entries and two databases never do.\n */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CachedClientOf, MutationOperations } from \"../client/exports\";\nimport { VibORMError } from \"../errors/base\";\nimport {\n CacheConfigurationError,\n CacheOperationNotCacheableError,\n} from \"../errors/cache\";\nimport { accepts, args, bound } from \"../extensions/args\";\nimport { around, call } from \"../extensions/call\";\nimport { codec } from \"../extensions/codec\";\nimport { type Database, database } from \"../extensions/database\";\nimport { extension } from \"../extensions/extension\";\nimport { key } from \"../extensions/key\";\nimport { methods } from \"../extensions/methods-part\";\nimport { reads, target, writes } from \"../extensions/on\";\nimport { settled } from \"../extensions/settled\";\nimport type {\n AnyTarget,\n Extension,\n Facts,\n PlacedArgument,\n Run,\n} from \"../index\";\nimport {\n CacheDriver,\n INVALIDATE,\n type Revalidate,\n SERVE,\n scopedKey,\n type WaitUntilFn,\n} from \"./driver\";\nimport { createOfficialCacheNamespace } from \"./key\";\nimport { cacheCodec } from \"./result-codec\";\nimport {\n admitMutationOptions,\n admitReadOptions,\n CACHEABLE,\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n type WithCacheOptions,\n} from \"./schema\";\n\nexport interface CacheExtensionConfig {\n readonly driver: CacheDriver;\n readonly version?: string | number;\n readonly waitUntil?: WaitUntilFn;\n /**\n * `staleWhileRevalidate`, imported from `viborm/cache`: what lets a view's\n * `swr` option serve a stale entry and refresh it in the background.\n */\n readonly swr?: Revalidate;\n}\n\ntype ConfigKeys<Config> = Config extends unknown ? keyof Config : never;\n\ntype ExactCacheExtensionConfig<Config> = Record<\n Exclude<ConfigKeys<Config>, keyof CacheExtensionConfig>,\n never\n>;\n\n/** `Self` is a client, not a transaction nor a view: what the cache's methods are called on. */\ntype OnClient<Self> = [CachedClientOf<Self>] extends [never] ? never : unknown;\n\n/**\n * The client methods the cache adds, typed through `this` from the client\n * they are called on, whatever the chain added after the cache.\n */\nexport interface CacheMethods {\n /** A view whose reads the cache serves: read operations only. */\n $withCache<Self>(\n this: Self & OnClient<Self>,\n options?: WithCacheOptions\n ): CachedClientOf<Self>;\n /** Invalidate entries by keys or patterns (a `*` suffix matches a prefix). */\n $invalidate<Self>(\n this: Self & OnClient<Self>,\n ...keys: string[]\n ): Promise<void>;\n}\n\n/** What the cache adds to a client: its `cache` argument on writes, `$withCache`, `$invalidate`. */\ntype CacheFacts = Facts<\n CacheMethods,\n Record<never, never>,\n {\n readonly cache: PlacedArgument<\n CacheInvalidationOptions,\n PropertyKey,\n MutationOperations\n >;\n },\n never,\n never,\n Record<never, never>,\n Record<never, never>,\n false\n>;\n\n/** A validator as a Standard Schema: what an argument of the cache is checked by. */\nconst validator = <T>(admit: (value: unknown) => T): StandardSchemaV1<T> => ({\n \"~standard\": {\n version: 1,\n vendor: \"viborm.cache\",\n validate: (value: unknown) => ({ value: admit(value) }),\n },\n});\n\nfunction configurationError(message: string): never {\n throw new CacheConfigurationError(message);\n}\n\n/** The cache's view of one read: what its moment one leaves its second. */\ninterface Values {\n readonly cache?: CacheInvalidationOptions;\n readonly cacheRead?: CacheReadOptions;\n}\n\n/**\n * VibORM's fixed-name cache extension: `client.$extends(cache({ driver }))`.\n */\nexport function cache<T extends AnyTarget, const Config>(\n config: Config &\n NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>\n): Extension<T, CacheFacts>;\nexport function cache(config: CacheExtensionConfig): unknown {\n const { driver, version, waitUntil, swr } = config;\n if (!(driver instanceof CacheDriver))\n configurationError(\n \"Cache extension configuration requires a CacheDriver instance.\"\n );\n if (\n version !== undefined &&\n !(typeof version === \"string\" || Number.isFinite(version))\n )\n configurationError(\n 'Cache extension configuration \"version\" must be a string or finite number.'\n );\n if (waitUntil !== undefined && typeof waitUntil !== \"function\")\n configurationError(\n 'Cache extension configuration \"waitUntil\" must be a function.'\n );\n\n // Pure in its facts: the same version and database always give one scope.\n const namespaceOf = ({ dialect, namespace }: Database): string =>\n createOfficialCacheNamespace({ version, dialect, namespace });\n /**\n * Invalidate the scope of `origin`'s database. A backend failure is the\n * cache's; after a write (`meta`), whatever failed is, and a key\n * `$invalidate` was handed that the scope refuses is said as it is.\n */\n const invalidate = async (\n origin: object,\n options: CacheInvalidationOptions | undefined,\n meta?: {\n model?: string;\n operation: string;\n commitCertainty: \"committed\" | \"may-have-committed\";\n }\n ): Promise<void> => {\n try {\n const namespace = namespaceOf(database(origin));\n await driver[INVALIDATE](\"\", options, origin, (key) =>\n scopedKey(namespace, key)\n );\n } catch (cause) {\n if (meta === undefined && cause instanceof VibORMError) throw cause;\n throw new CacheConfigurationError(\n meta\n ? `Cache invalidation failed after mutation '${meta.operation}' on model '${meta.model}'.`\n : \"Cache invalidation failed.\",\n {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method: \"invalidate\", ...meta },\n }\n );\n }\n };\n\n return extension(\n \"viborm.cache\",\n args({\n // A write's own invalidation options.\n cache: accepts(validator(admitMutationOptions)).on(writes),\n // Only `$withCache` binds it: the mark of a read the cache serves.\n cacheRead: bound(\n validator((value) => {\n const read = admitReadOptions(value);\n if (read.swr !== false && swr === undefined)\n configurationError(\n 'A view\\'s \"swr\" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).'\n );\n return read;\n })\n ),\n }),\n\n // Writes: none through the read view; the scope is invalidated once the\n // write is durable.\n call((c) => {\n const values: Values = c.values;\n // Only reads are served through the view: this part sees writes alone.\n if (values.cacheRead !== undefined)\n throw new CacheOperationNotCacheableError(c.operation, [...CACHEABLE]);\n const options = values.cache;\n if (!hasCacheInvalidationWork(options)) return;\n settled(c, ({ certainty }) =>\n invalidate(c, options, {\n model: c.model,\n operation: c.operation,\n commitCertainty: certainty,\n })\n );\n }, target(writes)),\n\n // Reads through the view: answered from the store, closest to the core,\n // so every other part sees each call and the core's answer is stored.\n around(\n (c) => {\n const values: Values = c.values;\n const read = values.cacheRead;\n if (read === undefined) return;\n // target(reads) selects model calls only: each names its model.\n const model = c.model!;\n return <R>(run: Run<unknown, R>): Promise<R> => {\n // A transaction's and an array's reads see their own writes.\n if (run.mode !== \"direct\") return run();\n const id = key(run);\n if (id === undefined) return run();\n const db = database(run);\n return driver[SERVE]({\n id,\n codec: cacheCodec(codec(run), c.operation),\n read,\n namespace: namespaceOf(db),\n waitUntil,\n model,\n operation: c.operation,\n origin: run,\n database: db,\n revalidate: swr,\n });\n };\n },\n target(reads),\n { inner: true }\n ),\n\n methods((scope) => ({\n $withCache: (options?: WithCacheOptions) =>\n scope.$bind({ cacheRead: options }),\n $invalidate: (...keys: string[]) =>\n settled(scope, () => invalidate(scope, { invalidate: keys })),\n }))\n );\n}\n","/**\n * Stale-while-revalidate, a value the cache is configured with\n * (`cache({ driver, swr: staleWhileRevalidate })`): a cache without it\n * carries none of this code, and refuses a view's `swr` option.\n */\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport { marker, scheduleBackground } from \"./cache-background\";\nimport type { Refresh, Revalidate } from \"./driver\";\nimport { cacheOutcome, revalidationStart } from \"./units\";\n\n/**\n * A stale entry within its window is served, and refreshed in the\n * background: claim the backend's marker (best effort; another request\n * holding it skips), replay the read's core keeping its rows, store them,\n * and always clear the marker. Nothing here rejects: its `revalidate` unit\n * presents a failure, the replay's primary over the cleanup's, both\n * retained.\n */\nexport const staleWhileRevalidate: Revalidate = (refresh) => {\n const { request, entry, now } = refresh;\n const window = request.read.swr;\n if (\n window === false ||\n now - entry.createdAt >= window ||\n now >= entry.expiresAt!\n )\n return false;\n // Stale, served; refreshed in the background, where the read runs once\n // more after this serve returned: the core alone.\n scheduleBackground(refreshed(refresh), request.waitUntil);\n note(request.origin, cacheOutcome(\"hit\", \"stale\"));\n return true;\n};\n\nasync function refreshed({\n request,\n key,\n backend,\n store,\n}: Refresh): Promise<void> {\n try {\n if (!(await marker(backend, key, true))) return;\n } catch {\n // A marker that cannot be claimed skips the refresh, never the read.\n return;\n }\n const { codec } = request;\n // Its own `cache` unit, whose terminal outcome is noted on it; a failure\n // of the replay is primary over the cleanup's, both retained.\n await work(\n request.origin,\n {\n kind: \"cache\",\n operation: \"revalidate\",\n note: revalidationStart(request, request.database),\n },\n async (unit) => {\n let failed = false;\n let failure: unknown;\n let terminal: ReturnType<typeof cacheOutcome>;\n try {\n await codec.run();\n await store(codec.snapshot());\n terminal = cacheOutcome(\"revalidate\", \"success\", undefined, request);\n } catch (error) {\n failed = true;\n failure = error;\n terminal = cacheOutcome(\"revalidate\", \"error\", error, request);\n }\n try {\n await marker(backend, key, false);\n } catch (cleanupFailure) {\n failure = failed\n ? new AggregateError(\n [failure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: failure }\n )\n : cleanupFailure;\n failed = true;\n }\n note(unit, terminal);\n if (failed) throw failure;\n }\n );\n}\n","/**\n * The unscoped storage of a cache driver, outside the official cache: what a\n * backend's own test or an application reads and writes under the bare\n * `viborm` root. Functions of the driver rather than its methods, so an\n * application that never calls them carries none of them; none of them\n * reaches the official namespace, which only an applied cache extension\n * writes.\n */\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { marker } from \"./cache-background\";\nimport {\n BACKEND,\n type CacheDriver,\n type CacheEntry,\n type CacheSetOptions,\n DROP,\n GET,\n INVALIDATE,\n SET,\n} from \"./driver\";\nimport { CACHE_PREFIX, OFFICIAL_CACHE_NAMESPACE_ROOT } from \"./key\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\n/**\n * A public storage key under the bare `viborm` root (a key that already\n * begins with `viborm:` is taken as it is), refused inside the official\n * namespace. There is only one such root, so no sibling exists for a clear\n * to cross into.\n */\nfunction unscoped(key: string): string {\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.\"\n );\n }\n return prefixedKey;\n}\n\n/** The entry stored under `key`, or `null`. */\nexport async function getEntry<T>(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<CacheEntry<T> | null> {\n return driver[GET]<T>(unscoped(key), origin);\n}\n\n/** Store `value` under `key` for `options.ttl` milliseconds. */\nexport async function setEntry<T>(\n driver: CacheDriver,\n key: string,\n value: T,\n options: CacheSetOptions,\n origin?: object\n): Promise<void> {\n return driver[SET](unscoped(key), value, options, origin);\n}\n\n/** Delete the entry under `key` and its revalidation marker. */\nexport async function deleteEntry(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"delete\", unscoped(key), origin);\n}\n\n/** Clear every entry under `prefix`; every unscoped entry without one. */\nexport async function clearEntries(\n driver: CacheDriver,\n prefix?: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"clear\", unscoped(prefix ?? \"\"), origin);\n}\n\n/**\n * Invalidate `model`'s entries (`autoInvalidate`, the default) and the keys\n * or `*` prefixes `options.invalidate` names, validated whole first.\n */\nexport async function invalidateEntries(\n driver: CacheDriver,\n model: string,\n options?: CacheInvalidationOptions,\n origin?: object\n): Promise<void> {\n return driver[INVALIDATE](`${model}:`, options, origin, unscoped);\n}\n\n/** Claim the refresh of `key`: whether this caller performs it. */\nexport async function markRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<boolean> {\n return marker(driver[BACKEND](), unscoped(key), true);\n}\n\n/** Release the claim on the refresh of `key`. */\nexport async function clearRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<void> {\n await marker(driver[BACKEND](), unscoped(key), false);\n}\n"],"mappings":"yrBAIA,SAAS,KACP,EACA,EACA,EACA,EACG,CACH,GAAI,CACF,OAAO,GAAK,OACL,EAAO,CACd,MAAM,IAAI,EAAwB,EAAS,CACzC,MAAO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AK,SAASA,EAAI,CAAE,EAAO,EAAS,EAAO,CAI3D,eAAsB,YACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,SAAU,SAASA,EAAI,CAAE,EAAO,CAItD,eAAsB,aACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,QAAS,SAAS,GAAU,GAAG,CAAE,EAAO,CAO9D,eAAsB,kBACpB,EACA,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAY,GAAG,EAAM,GAAI,EAAS,EAAQ,SAAS,CAInE,eAAsB,iBACpB,EACA,EACkB,CAClB,OAAO,EAAO,EAAO,IAAU,CAAE,SAASA,EAAI,CAAE,GAAK,CAIvD,eAAsB,kBACpB,EACA,EACe,CACf,MAAM,EAAO,EAAO,IAAU,CAAE,SAASA,EAAI,CAAE,GAAM"}
|
|
1
|
+
{"version":3,"file":"cache.mjs","names":["codec","key","key","codec","key"],"sources":["../src/cache/result-codec.ts","../src/cache/extension.ts","../src/cache/revalidate.ts","../src/cache/storage.ts"],"sourcesContent":["import { CacheConfigurationError } from \"../errors/cache\";\nimport type { Codec } from \"../index\";\n\n/** One codec step, its failure the cache's: named, exposing no value. */\nfunction step<T>(\n method: \"snapshot\" | \"materialize\",\n operation: string,\n message: string,\n run: () => T\n): T {\n try {\n return run();\n } catch (cause) {\n throw new CacheConfigurationError(message, {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method, operation },\n });\n }\n}\n\n/**\n * A call's codec whose failures are the cache's: a value the codec cannot\n * represent, and a stored entry that does not follow the shape, are each a\n * `CacheConfigurationError` that names the step and exposes no value.\n */\nexport function cacheCodec<R>(codec: Codec<R>, operation: string): Codec<R> {\n return {\n run: () => codec.run(),\n snapshot: () =>\n step(\n \"snapshot\",\n operation,\n \"The operation result cannot be represented by the cache result codec.\",\n () => codec.snapshot()\n ),\n materialize: (snapshot) =>\n step(\n \"materialize\",\n operation,\n \"The cached result snapshot is malformed.\",\n () => codec.materialize(snapshot)\n ),\n };\n}\n","/**\n * VibORM's cache, written with the public extension contract:\n * `client.$extends(cache({ driver }))`.\n *\n * - `$withCache(options)` binds the view's read options (`cacheRead`, a\n * bound argument): what marks a read the cache serves.\n * - A read through that view is served closest to the core (`inner`), keyed\n * on the prepared call (`key(run)`), and run uncached when it has no key\n * or runs in a transaction or an array.\n * - A write invalidates the scope once durable (`settled`), as its own\n * `cache` argument says; `$invalidate` once the view's work is durable.\n * - The scope is a pure function of the cache `version` and the database the\n * call works against (`database`), so two clients of one database share\n * entries and two databases never do.\n */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CachedClientOf, MutationOperations } from \"../client/exports\";\nimport { VibORMError } from \"../errors/base\";\nimport {\n CacheConfigurationError,\n CacheOperationNotCacheableError,\n} from \"../errors/cache\";\nimport { accepts, args, bound } from \"../extensions/args\";\nimport { around, call } from \"../extensions/call\";\nimport { codec } from \"../extensions/codec\";\nimport { type Database, database } from \"../extensions/database\";\nimport { extension } from \"../extensions/extension\";\nimport { key } from \"../extensions/key\";\nimport { methods } from \"../extensions/methods-part\";\nimport { reads, target, writes } from \"../extensions/on\";\nimport { settled } from \"../extensions/settled\";\nimport type {\n AnyTarget,\n Extension,\n Facts,\n PlacedArgument,\n Run,\n} from \"../index\";\nimport {\n CacheDriver,\n INVALIDATE,\n type Revalidate,\n SERVE,\n scopedKey,\n type WaitUntilFn,\n} from \"./driver\";\nimport { createOfficialCacheNamespace } from \"./key\";\nimport { cacheCodec } from \"./result-codec\";\nimport {\n admitMutationOptions,\n admitReadOptions,\n CACHEABLE,\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n type WithCacheOptions,\n} from \"./schema\";\n\nexport interface CacheExtensionConfig {\n readonly driver: CacheDriver;\n readonly version?: string | number;\n readonly waitUntil?: WaitUntilFn;\n /**\n * `staleWhileRevalidate`, imported from `viborm/cache`: what lets a view's\n * `swr` option serve a stale entry and refresh it in the background.\n */\n readonly swr?: Revalidate;\n}\n\ntype ConfigKeys<Config> = Config extends unknown ? keyof Config : never;\n\ntype ExactCacheExtensionConfig<Config> = Record<\n Exclude<ConfigKeys<Config>, keyof CacheExtensionConfig>,\n never\n>;\n\n/** `Self` is a client, not a transaction nor a view: what the cache's methods are called on. */\ntype OnClient<Self> = [CachedClientOf<Self>] extends [never] ? never : unknown;\n\n/**\n * The client methods the cache adds, typed through `this` from the client\n * they are called on, whatever the chain added after the cache.\n */\nexport interface CacheMethods {\n /** A view whose reads the cache serves: read operations only. */\n $withCache<Self>(\n this: Self & OnClient<Self>,\n options?: WithCacheOptions\n ): CachedClientOf<Self>;\n /** Invalidate entries by keys or patterns (a `*` suffix matches a prefix). */\n $invalidate<Self>(\n this: Self & OnClient<Self>,\n ...keys: string[]\n ): Promise<void>;\n}\n\n/** What the cache adds to a client: its `cache` argument on writes, `$withCache`, `$invalidate`. */\ntype CacheFacts = Facts<\n CacheMethods,\n Record<never, never>,\n {\n readonly cache: PlacedArgument<\n CacheInvalidationOptions,\n PropertyKey,\n MutationOperations\n >;\n },\n never,\n never,\n Record<never, never>,\n Record<never, never>,\n false\n>;\n\n/** A validator as a Standard Schema: what an argument of the cache is checked by. */\nconst validator = <T>(admit: (value: unknown) => T): StandardSchemaV1<T> => ({\n \"~standard\": {\n version: 1,\n vendor: \"viborm.cache\",\n validate: (value: unknown) => ({ value: admit(value) }),\n },\n});\n\nfunction configurationError(message: string): never {\n throw new CacheConfigurationError(message);\n}\n\n/** The cache's view of one read: what its moment one leaves its second. */\ninterface Values {\n readonly cache?: CacheInvalidationOptions;\n readonly cacheRead?: CacheReadOptions;\n}\n\n/**\n * VibORM's fixed-name cache extension: `client.$extends(cache({ driver }))`.\n */\nexport function cache<T extends AnyTarget, const Config>(\n config: Config &\n NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>\n): Extension<T, CacheFacts>;\nexport function cache(config: CacheExtensionConfig): unknown {\n const { driver, version, waitUntil, swr } = config;\n if (!(driver instanceof CacheDriver))\n configurationError(\n \"Cache extension configuration requires a CacheDriver instance.\"\n );\n if (\n version !== undefined &&\n !(typeof version === \"string\" || Number.isFinite(version))\n )\n configurationError(\n 'Cache extension configuration \"version\" must be a string or finite number.'\n );\n if (waitUntil !== undefined && typeof waitUntil !== \"function\")\n configurationError(\n 'Cache extension configuration \"waitUntil\" must be a function.'\n );\n\n // Pure in its facts: the same version and database always give one scope.\n const namespaceOf = ({ dialect, namespace }: Database): string =>\n createOfficialCacheNamespace({ version, dialect, namespace });\n /**\n * Invalidate the scope of `origin`'s database. A backend failure is the\n * cache's; after a write (`meta`), whatever failed is, and a key\n * `$invalidate` was handed that the scope refuses is said as it is.\n */\n const invalidate = async (\n origin: object,\n options: CacheInvalidationOptions | undefined,\n meta?: {\n model?: string;\n operation: string;\n commitCertainty: \"committed\" | \"may-have-committed\";\n }\n ): Promise<void> => {\n try {\n const namespace = namespaceOf(database(origin));\n await driver[INVALIDATE](\"\", options, origin, (key) =>\n scopedKey(namespace, key)\n );\n } catch (cause) {\n if (meta === undefined && cause instanceof VibORMError) throw cause;\n throw new CacheConfigurationError(\n meta\n ? `Cache invalidation failed after mutation '${meta.operation}' on model '${meta.model}'.`\n : \"Cache invalidation failed.\",\n {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method: \"invalidate\", ...meta },\n }\n );\n }\n };\n\n return extension(\n \"viborm.cache\",\n args({\n // A write's own invalidation options.\n cache: accepts(validator(admitMutationOptions)).on(writes),\n // Only `$withCache` binds it: the mark of a read the cache serves.\n cacheRead: bound(\n validator((value) => {\n const read = admitReadOptions(value);\n if (read.swr !== false && swr === undefined)\n configurationError(\n 'A view\\'s \"swr\" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).'\n );\n return read;\n })\n ),\n }),\n\n // Writes: none through the read view; the scope is invalidated once the\n // write is durable.\n call((c) => {\n const values: Values = c.values;\n // Only reads are served through the view: this part sees writes alone.\n if (values.cacheRead !== undefined)\n throw new CacheOperationNotCacheableError(c.operation, [...CACHEABLE]);\n const options = values.cache;\n if (!hasCacheInvalidationWork(options)) return;\n settled(c, ({ certainty }) =>\n invalidate(c, options, {\n model: c.model,\n operation: c.operation,\n commitCertainty: certainty,\n })\n );\n }, target(writes)),\n\n // Reads through the view: answered from the store, closest to the core,\n // so every other part sees each call and the core's answer is stored.\n around(\n (c) => {\n const values: Values = c.values;\n const read = values.cacheRead;\n if (read === undefined) return;\n // target(reads) selects model calls only: each names its model.\n const model = c.model!;\n return <R>(run: Run<unknown, R>): Promise<R> => {\n // A transaction's and an array's reads see their own writes.\n if (run.mode !== \"direct\") return run();\n const id = key(run);\n if (id === undefined) return run();\n const db = database(run);\n return driver[SERVE]({\n id,\n codec: cacheCodec(codec(run), c.operation),\n read,\n namespace: namespaceOf(db),\n waitUntil,\n model,\n operation: c.operation,\n origin: run,\n database: db,\n revalidate: swr,\n });\n };\n },\n target(reads),\n { inner: true }\n ),\n\n methods((scope) => ({\n $withCache: (options?: WithCacheOptions) =>\n scope.$bind({ cacheRead: options }),\n $invalidate: (...keys: string[]) =>\n settled(scope, () => invalidate(scope, { invalidate: keys })),\n }))\n );\n}\n","/**\n * Stale-while-revalidate, a value the cache is configured with\n * (`cache({ driver, swr: staleWhileRevalidate })`): a cache without it\n * carries none of this code, and refuses a view's `swr` option.\n */\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport { marker, scheduleBackground } from \"./cache-background\";\nimport type { Refresh, Revalidate } from \"./driver\";\nimport { cacheOutcome, revalidationStart } from \"./units\";\n\n/**\n * A stale entry within its window is served, and refreshed in the\n * background: claim the backend's marker (best effort; another request\n * holding it skips), replay the read's core keeping its rows, store them,\n * and always clear the marker. Nothing here rejects: its `revalidate` unit\n * presents a failure, the replay's primary over the cleanup's, both\n * retained.\n */\nexport const staleWhileRevalidate: Revalidate = (refresh) => {\n const { request, entry, now } = refresh;\n const window = request.read.swr;\n if (\n window === false ||\n now - entry.createdAt >= window ||\n now >= entry.expiresAt!\n )\n return false;\n // Stale, served; refreshed in the background, where the read runs once\n // more after this serve returned: the core alone.\n scheduleBackground(refreshed(refresh), request.waitUntil);\n note(request.origin, cacheOutcome(\"hit\", \"stale\"));\n return true;\n};\n\nasync function refreshed({\n request,\n key,\n backend,\n store,\n}: Refresh): Promise<void> {\n try {\n if (!(await marker(backend, key, true))) return;\n } catch {\n // A marker that cannot be claimed skips the refresh, never the read.\n return;\n }\n const { codec } = request;\n // Its own `cache` unit, whose terminal outcome is noted on it; a failure\n // of the replay is primary over the cleanup's, both retained.\n await work(\n request.origin,\n {\n kind: \"cache\",\n operation: \"revalidate\",\n note: revalidationStart(request, request.database),\n },\n async (unit) => {\n let failed = false;\n let failure: unknown;\n let terminal: ReturnType<typeof cacheOutcome>;\n try {\n await codec.run();\n await store(codec.snapshot());\n terminal = cacheOutcome(\"revalidate\", \"success\", undefined, request);\n } catch (error) {\n failed = true;\n failure = error;\n terminal = cacheOutcome(\"revalidate\", \"error\", error, request);\n }\n try {\n await marker(backend, key, false);\n } catch (cleanupFailure) {\n failure = failed\n ? new AggregateError(\n [failure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: failure }\n )\n : cleanupFailure;\n failed = true;\n }\n note(unit, terminal);\n if (failed) throw failure;\n }\n );\n}\n","/**\n * The unscoped storage of a cache driver, outside the official cache: what a\n * backend's own test or an application reads and writes under the bare\n * `viborm` root. Functions of the driver rather than its methods, so an\n * application that never calls them carries none of them; none of them\n * reaches the official namespace, which only an applied cache extension\n * writes.\n */\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { marker } from \"./cache-background\";\nimport {\n BACKEND,\n type CacheDriver,\n type CacheEntry,\n type CacheSetOptions,\n DROP,\n GET,\n INVALIDATE,\n SET,\n} from \"./driver\";\nimport { CACHE_PREFIX, OFFICIAL_CACHE_NAMESPACE_ROOT } from \"./key\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\n/**\n * A public storage key under the bare `viborm` root (a key that already\n * begins with `viborm:` is taken as it is), refused inside the official\n * namespace. There is only one such root, so no sibling exists for a clear\n * to cross into.\n */\nfunction unscoped(key: string): string {\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.\"\n );\n }\n return prefixedKey;\n}\n\n/** The entry stored under `key`, or `null`. */\nexport async function getEntry<T>(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<CacheEntry<T> | null> {\n return driver[GET]<T>(unscoped(key), origin);\n}\n\n/** Store `value` under `key` for `options.ttl` milliseconds. */\nexport async function setEntry<T>(\n driver: CacheDriver,\n key: string,\n value: T,\n options: CacheSetOptions,\n origin?: object\n): Promise<void> {\n return driver[SET](unscoped(key), value, options, origin);\n}\n\n/** Delete the entry under `key` and its revalidation marker. */\nexport async function deleteEntry(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"delete\", unscoped(key), origin);\n}\n\n/** Clear every entry under `prefix`; every unscoped entry without one. */\nexport async function clearEntries(\n driver: CacheDriver,\n prefix?: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"clear\", unscoped(prefix ?? \"\"), origin);\n}\n\n/**\n * Invalidate `model`'s entries (`autoInvalidate`, the default) and the keys\n * or `*` prefixes `options.invalidate` names, validated whole first.\n */\nexport async function invalidateEntries(\n driver: CacheDriver,\n model: string,\n options?: CacheInvalidationOptions,\n origin?: object\n): Promise<void> {\n return driver[INVALIDATE](`${model}:`, options, origin, unscoped);\n}\n\n/** Claim the refresh of `key`: whether this caller performs it. */\nexport async function markRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<boolean> {\n return marker(driver[BACKEND](), unscoped(key), true);\n}\n\n/** Release the claim on the refresh of `key`. */\nexport async function clearRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<void> {\n await marker(driver[BACKEND](), unscoped(key), false);\n}\n"],"mappings":"0pBAIA,SAAS,EACP,EACA,EACA,EACA,EACG,CACH,GAAI,CACF,OAAO,GAAK,OACL,EAAO,CACd,MAAM,IAAI,EAAwB,EAAS,CACzC,MAAO,aAAiB,MAAQ,EAAQ,IAAA,GACxC,KAAM,CAAE,SAAQ,YAAW,CAC5B,CAAC,EASN,SAAgB,EAAc,EAAiB,EAA6B,CAC1E,MAAO,CACL,QAAWA,EAAM,KAAK,CACtB,aACE,EACE,WACA,EACA,4EACMA,EAAM,UAAU,CACvB,CACH,YAAc,GACZ,EACE,cACA,EACA,+CACMA,EAAM,YAAY,EAAS,CAClC,CACJ,CCyEH,MAAM,EAAgB,IAAuD,CAC3E,YAAa,CACX,QAAS,EACT,OAAQ,eACR,SAAW,IAAoB,CAAE,MAAO,EAAM,EAAM,CAAE,EACvD,CACF,EAED,SAAS,EAAmB,EAAwB,CAClD,MAAM,IAAI,EAAwB,EAAQ,CAgB5C,SAAgB,EAAM,EAAuC,CAC3D,GAAM,CAAE,SAAQ,UAAS,YAAW,OAAQ,EACtC,aAAkB,GACtB,EACE,iEACD,CAED,IAAY,IAAA,IACZ,EAAE,OAAO,GAAY,UAAY,OAAO,SAAS,EAAQ,GAEzD,EACE,6EACD,CACC,IAAc,IAAA,IAAa,OAAO,GAAc,YAClD,EACE,gEACD,CAGH,IAAM,GAAe,CAAE,UAAS,eAC9B,EAA6B,CAAE,UAAS,UAAS,YAAW,CAAC,CAMzD,EAAa,MACjB,EACA,EACA,IAKkB,CAClB,GAAI,CACF,IAAM,EAAY,EAAY,EAAS,EAAO,CAAC,CAC/C,MAAM,EAAO,GAAY,GAAI,EAAS,EAAS,GAC7C,EAAU,EAAWC,EAAI,CAC1B,OACM,EAAO,CAEd,MADI,IAAS,IAAA,IAAa,aAAiB,EAAmB,EACxD,IAAI,EACR,EACI,6CAA6C,EAAK,UAAU,cAAc,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GAAG,CAE3D,MAAM,IAAI,EACR,yHACD,CAEH,OAAO,EAIT,eAAsB,EACpB,EACA,EACA,EAC+B,CAC/B,OAAO,EAAO,GAAQ,EAASA,EAAI,CAAE,EAAO,CAI9C,eAAsB,EACpB,EACA,EACA,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAK,EAASA,EAAI,CAAE,EAAO,EAAS,EAAO,CAI3D,eAAsB,EACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,SAAU,EAASA,EAAI,CAAE,EAAO,CAItD,eAAsB,EACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,QAAS,EAAS,GAAU,GAAG,CAAE,EAAO,CAO9D,eAAsB,EACpB,EACA,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAY,GAAG,EAAM,GAAI,EAAS,EAAQ,EAAS,CAInE,eAAsB,EACpB,EACA,EACkB,CAClB,OAAO,EAAO,EAAO,IAAU,CAAE,EAASA,EAAI,CAAE,GAAK,CAIvD,eAAsB,EACpB,EACA,EACe,CACf,MAAM,EAAO,EAAO,IAAU,CAAE,EAASA,EAAI,CAAE,GAAM"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as e,t}from"./base-17NSFtrA.mjs";import{p as n}from"./validation-ATmgN5RE.mjs";import{i as r,l as i,n as a}from"./coordination-BxMskOgi.mjs";import{i as o,o as s}from"./value-guards-CBVIJXlI.mjs";import{r as c}from"./extension-Dh1ddrlA.mjs";import{i as l}from"./schema-DDkAUfOb.mjs";import{s as u,t as d,u as f}from"./on-ZkOVmE4-.mjs";const p=new Set([`select`,`include`,`omit`,`_count`,`_avg`,`_sum`,`_min`,`_max`,`by`]);function m(e){let t=e.filter(e=>!e.on),n=new Map;return{n1:e,global:t,cq(r,i){if(r===void 0)return t.length>0?t:void 0;let a=l(n,`${r}.${i}`,()=>e.filter(({on:e})=>!e||e.models.has(r)&&e.operations.has(i)));return a.length>0?a:void 0}}}const h=Object.freeze({});function g({handler:r,keep:a,m9:c,watch:l},u){let d=({extension:f,args:m},g,_,v,y,b,x)=>{let S=(t,r)=>new n(`Extension "${f}" first moment for ${g===void 0?_:`${g}.${_}`} ${t}.`,{cause:e(r),meta:{model:g,operation:_}}),C;try{C=r({kind:g===void 0?`raw`:`model`,schema:u,model:g,operation:_,get args(){return v.args},values:(m&&b?.f9(x,m))??h,set(e){if(g===void 0||!s(e))throw S(`set no model call's arguments`);for(let t of Object.keys(e)){let e=p.has(t);if(e||b?.names.has(t))throw S(e?`set "${t}", which decides the result's shape`:`set argument "${t}"`)}v.args=Object.freeze({...v.args,...e})},...g===void 0?c?.(y,f):l?.r8(y,f),[i]:g===void 0?void 0:y})}catch(e){throw e instanceof t?e:S(`threw`,e)}if(s(C)&&o(C.then))throw S(`returned a promise`);if(o(C)){if(a===void 0)throw S(`returned a function: write around()`);a(y,d,C)}};return d}function _(e,t,n,r,i,a,o){let c={args:s(t)?Object.freeze({...t}):t};for(let t of n)t.handler(t,i,e,c,r,a,o);return c.args}function v(e,t,n){(e.seconds??=new Map).set(t,n)}const y=(e,t)=>({[f]({settled:n,collect:r,tell:i}){return n===void 0?!1:((e.m9??=[]).push({extension:t,listener:n,collect:r,tell:i}),!0)}}),b=e=>(t,n)=>{let r=t.call?.seconds?.get(e);return r===void 0?n():r(n)};function x({on:e,inner:t},n,{schema:r,owner:{name:i,args:a}}){let o=(e,t)=>new Set(e.map(e=>t(e)?e:c(`Extension "${i}" target names unknown model or operation "${e}".`,i)));return{extension:i,handler:n,args:a,inner:t,on:e&&{models:o(e.models??Object.keys(r),e=>Object.hasOwn(r,e)),operations:o(e.operations??[...d],e=>d.has(e))}}}function S(e,t,n){let{next:r}=e;r.call={...m([...r.call?.n1??[],x(t,n,e)]),apply:_}}function C(e){return{join(t){e.watch&&t.wh(e.watch),S(t,e,g(e,t.schema))}}}function w(e){return{join(t){let{next:n}=t;e.watch&&t.wh(e.watch);let i=g(e,t.schema);S(t,e,i);let o=x(e,b(i),t);n.around=m([...n.around?.n1??[],o].sort((e,t)=>Number(!!e.inner)-Number(!!t.inner))),r(n,a)}}}function T(e,t){if(!o(e))throw TypeError(`call() takes a function of the call`);let n=u(t);return C({handler:e,on:n,watch:n?.watch})}function E(e,t,n){if(!o(e))throw TypeError(`around() takes a function of the call`);let r=u(t);return w({handler:e,on:r,keep:v,m9:y,watch:r?.watch,inner:n?.inner})}export{T as n,E as t};
|
|
2
|
+
//# sourceMappingURL=call-0bd_B9Vp.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call-BWFI7-vU.mjs","names":["placed","call"],"sources":["../src/extensions/request.ts","../src/extensions/targeted.ts","../src/extensions/call.ts"],"sourcesContent":["/**\n * The keys of a call's arguments that decide its result's shape, and the\n * types of what a first moment reads and patches.\n */\nimport type { Operations } from \"@client/types\";\n\n/**\n * The keys of a call's arguments that decide its result's shape: the one\n * list of them. A first moment's `c.set` refuses each (`call.ts`), and the\n * types of what it reads and patches leave out those its operation has.\n */\nconst RESULT_SHAPE_KEYS = [\n \"select\",\n \"include\",\n \"omit\",\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n \"by\",\n] as const;\n\n/** What `c.set` tests a patch's keys against. */\nexport const SHAPE_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set(\n RESULT_SHAPE_KEYS\n);\n\ntype ResultShapeKey = (typeof RESULT_SHAPE_KEYS)[number];\n\n/**\n * Which of those keys each operation has: a future projection spelling\n * extends the list and this table, and the patch types follow.\n */\ninterface ResultShapeKeysByOperation\n extends Record<Operations, ResultShapeKey> {\n findFirst: \"select\" | \"include\" | \"omit\";\n findMany: \"select\" | \"include\" | \"omit\";\n findUnique: \"select\" | \"include\" | \"omit\";\n findUniqueOrThrow: \"select\" | \"include\" | \"omit\";\n findFirstOrThrow: \"select\" | \"include\" | \"omit\";\n create: \"select\" | \"include\" | \"omit\";\n update: \"select\" | \"include\" | \"omit\";\n delete: \"select\" | \"include\" | \"omit\";\n upsert: \"select\" | \"include\" | \"omit\";\n createMany: \"select\" | \"omit\";\n updateMany: \"select\" | \"omit\";\n deleteMany: \"select\" | \"omit\";\n count: \"select\";\n aggregate: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n groupBy: \"by\" | \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n exist: never;\n}\n\ntype ResultShapeKeyFor<Operation extends Operations> =\n ResultShapeKeysByOperation[Operation];\n\n/** The operation input visible to an ordinary request transform. */\nexport type RequestTransformInput<\n Operation extends Operations,\n Input extends object,\n> = Omit<Input, ResultShapeKeyFor<Operation>>;\n\n/**\n * A shallow patch over the non-projection input. The optional `never`\n * properties make protected keys fail structurally, including held values.\n */\nexport type RequestTransformPatch<\n Operation extends Operations,\n Input extends object,\n> = Partial<RequestTransformInput<Operation, Input>> & {\n readonly [Key in ResultShapeKeyFor<Operation>]?: never;\n};\n","/**\n * The handlers of `call` and `around`, in chain order, each with the calls\n * its target selects, and the handlers one call runs: found the first time\n * a (model, operation) asks, and kept for the chain.\n */\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { FirstMoment, runFirstMoments } from \"./call\";\nimport type { CallHandler } from \"./chain-state\";\n\n/** One handler of a chain, and the calls it concerns. */\nexport interface TargetedHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends CallHandler<Handler> {\n /** The models and operations a target selects; every call without one. */\n readonly on?: {\n readonly models: ReadonlySet<string>;\n readonly operations: ReadonlySet<string>;\n };\n /** Placed nearest the core, after every other handler (`around`'s `inner`). */\n readonly inner?: boolean;\n}\n\n/** A chain's handlers of one moment, and the handlers one call runs. */\nexport interface TargetedHandlers<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly placed: readonly TargetedHandler<Handler>[];\n /** The handlers without a target: the only ones a raw statement runs. */\n readonly global: readonly CallHandler<Handler>[];\n readonly handlers: (\n model: string | undefined,\n operation: string\n ) => readonly CallHandler<Handler>[] | undefined;\n}\n\n/** The first moments of `call` and `around`, and what runs them for one call. */\nexport interface CallHandlers extends TargetedHandlers<FirstMoment> {\n readonly apply: typeof runFirstMoments;\n}\n\n/** The lookup of `placed`, in its order. */\nexport function targetedHandlers<Handler extends CallableFunction>(\n placed: readonly TargetedHandler<Handler>[]\n): TargetedHandlers<Handler> {\n const global = placed.filter((entry) => !entry.on);\n const found = new Map<string, readonly TargetedHandler<Handler>[]>();\n return {\n placed,\n global,\n handlers(model, operation) {\n if (model === undefined) return global.length > 0 ? global : undefined;\n const key = `${model}.${operation}`;\n const list = memo(found, key, () =>\n placed.filter(\n ({ on }) =>\n !on || (on.models.has(model) && on.operations.has(operation))\n )\n );\n return list.length > 0 ? list : undefined;\n },\n };\n}\n","/**\n * `call(fn, target?)` and `around(fn, target?, options?)`: a function on each\n * logical call, in two moments. Every first moment runs in chain order,\n * synchronously, before the call is validated: it reads the arguments and\n * this extension's own (`c.args`, `c.values`), patches the arguments\n * (`c.set`), or refuses the call by throwing. A first moment of\n * `around` may return a second moment, which runs around the prepared\n * call once every first moment ran and the call was validated: the first\n * extension applied outermost. `run()` executes the call once; its failure\n * is the call's, whatever the second moment does after it.\n *\n * Without a target, a part concerns every model call and every raw\n * statement; `target(...)` names model operations only, so a targeted part\n * never sees a raw statement.\n */\n\nimport type { Schema } from \"@client/types\";\nimport { QueryError, VibORMError } from \"@errors\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Application, ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { CallHandler, ResolvedArgs } from \"./chain-state\";\nimport type {\n AnyTarget,\n AroundFacts,\n AroundHandler,\n EmptyFacts,\n MomentOne,\n Part,\n Selection,\n} from \"./contract\";\nimport { coordinate, QUERIES } from \"./coordination\";\nimport { MODEL_OPERATIONS, type SelectionValue, selectionOf } from \"./on\";\nimport { CALL, type CallOrigin } from \"./origin\";\nimport type { AroundRunner } from \"./query\";\nimport { SHAPE_KEYS } from \"./request\";\nimport { type TargetedHandler, targetedHandlers } from \"./targeted\";\nimport { REGISTER, type Registering, type WatchPart } from \"./watch-part\";\n\n/**\n * What a first moment is handed, beside what `contract.ts` types: where the\n * part brings what tells `watch` and `settled`, what they register through.\n */\ninterface FirstContext extends Partial<Registering> {\n readonly kind: \"model\" | \"raw\";\n readonly schema: Schema;\n readonly model: string | undefined;\n readonly operation: string;\n readonly args: Readonly<Record<string, unknown>>;\n readonly values: AdmittedArgs;\n set(patch: unknown): void;\n /** A model call itself, for the words that read it (`database`, `key`). */\n readonly [CALL]: object | undefined;\n}\n\n/**\n * One `call` or `around` part, as its builder wrote it. What only `around`\n * or a watching set needs is handed in by the builder that has it, so a\n * program building `call` alone carries none of it.\n */\ninterface CallSpec {\n readonly handler: (context: FirstContext) => unknown;\n readonly on: SelectionValue | undefined;\n /** `around` only: keeps the second moment a first returned, for the call. */\n readonly keep?: (\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n ) => void;\n /**\n * `around` only: what a raw statement's first moment registers `settled`\n * through, kept on the call, which the host tells of the outcome.\n */\n readonly told?: (call: CallOrigin, extension: string) => Registering;\n /** What registers `watch` and `settled`, where the part brings what tells them. */\n readonly watch?: WatchPart | undefined;\n /** `around` only: placed nearest the core. */\n readonly inner?: boolean;\n}\n\n/**\n * One first moment, as the request lookup holds it: run for one call by\n * `runFirstMoments`, it keeps the second moment its handler returned.\n */\nexport type FirstMoment = (\n owner: Pick<CallHandler, \"extension\" | \"args\">,\n model: string | undefined,\n operation: string,\n state: { args: Readonly<Record<string, unknown>> },\n call: CallOrigin,\n declared: ResolvedArgs | undefined,\n admitted: AdmittedArgs | undefined\n) => void;\n\ntype SecondMoment = (run: unknown) => unknown;\n\nconst NO_VALUES: AdmittedArgs = /* @__PURE__ */ Object.freeze({});\n\n/**\n * One part's first moment against one schema. What the handler throws\n * refuses the call (an error of viborm's own as it is, any other as the\n * cause of a `QueryError`); a promise is refused, and so is a function\n * returned by `call`; a second moment returned by `around` is kept for the\n * call.\n */\nfunction firstOf(\n { handler, keep, told, watch }: CallSpec,\n schema: Schema\n): FirstMoment {\n const first: FirstMoment = (\n { extension, args: own },\n model,\n operation,\n state,\n call,\n declared,\n admitted\n ) => {\n const refusal = (problem: string, cause?: unknown) =>\n new QueryError(\n `Extension \"${extension}\" first moment for ${model === undefined ? operation : `${model}.${operation}`} ${problem}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n let returned: unknown;\n try {\n returned = handler({\n kind: model === undefined ? \"raw\" : \"model\",\n schema,\n model,\n operation,\n get args() {\n return state.args;\n },\n // An extension that declares arguments brings the chain's arguments.\n values: (own && declared?.owned(admitted, own)) ?? NO_VALUES,\n set(patch: unknown) {\n if (model === undefined || !isRecord(patch))\n throw refusal(\"set no model call's arguments\");\n for (const key of Object.keys(patch)) {\n const shape = SHAPE_KEYS.has(key);\n if (shape || declared?.names.has(key))\n throw refusal(\n shape\n ? `set \"${key}\", which decides the result's shape`\n : `set argument \"${key}\"`\n );\n }\n state.args = Object.freeze({ ...state.args, ...patch });\n },\n // Only a part on a set of writes watches a model call, and a raw\n // statement never reaches such a part; an `around` hears a raw\n // statement's outcome.\n ...(model === undefined\n ? told?.(call, extension)\n : watch?.registering(call, extension)),\n [CALL]: model === undefined ? undefined : call,\n });\n } catch (cause) {\n if (cause instanceof VibORMError) throw cause;\n throw refusal(\"threw\", cause);\n }\n // A first moment runs synchronously.\n if (isRecord(returned) && isFunction(returned.then))\n throw refusal(\"returned a promise\");\n if (!isFunction<SecondMoment>(returned)) return;\n if (keep === undefined)\n throw refusal(\"returned a function: write around()\");\n keep(call, first, returned);\n };\n return first;\n}\n\n/**\n * Every first moment of one call, in chain order, over its arguments with\n * the arguments taken out: what `chain.request.apply` runs before a model\n * call is validated, and before a raw statement is sent (`raw.ts`, with no\n * model and its input for arguments). The arguments each sees are those the\n * moments before it left. `call` is the one object both moments of the call\n * are handed: what links an `around` part's second moment to its first.\n */\nexport function runFirstMoments(\n operation: string,\n input: Readonly<Record<string, unknown>>,\n handlers: readonly CallHandler<FirstMoment>[],\n call: CallOrigin,\n model?: string,\n declared?: ResolvedArgs,\n admitted?: AdmittedArgs\n): Record<string, unknown> {\n // An argument that is no object is validation's to refuse, as it is.\n const state = {\n args: isRecord(input) ? Object.freeze({ ...input }) : input,\n };\n for (const handler of handlers)\n handler.handler(handler, model, operation, state, call, declared, admitted);\n return state.args;\n}\n\n/** A call's `seconds`: the second moment each `around` part's first returned. */\nexport type Seconds = Map<FirstMoment, SecondMoment>;\n\n/** What `around` hands its first moments: the call's second moments kept. */\nfunction keepSecond(\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n): void {\n (call.seconds ??= new Map()).set(first, second);\n}\n\n/**\n * What a raw statement's first moment registers through: its `settled`\n * functions, kept on the call, which the host tells of an execute's\n * outcome. A raw statement shows no rows: a `watch` would never be told,\n * and is refused.\n */\nconst rawTold = (call: CallOrigin, extension: string): Registering => ({\n [REGISTER]({ settled, collect, tell }) {\n if (settled === undefined) return false;\n (call.told ??= []).push({ extension, listener: settled, collect, tell });\n return true;\n },\n});\n\n/** The second moment of one `around` part: the second its first returned for this call. */\nconst secondMoment =\n (first: FirstMoment): AroundRunner =>\n (prepared, run) => {\n const second = prepared.call?.seconds?.get(first);\n return second === undefined ? run() : second(run);\n };\n\n/**\n * One part's handler, placed on the calls of its target; on every call\n * without one. A name the schema or the operations do not hold is refused:\n * the types refuse it where `target` is written, and a caller without them\n * would otherwise get a part that never runs.\n */\nfunction placed<H extends CallableFunction>(\n { on, inner }: CallSpec,\n handler: H,\n { schema, owner: { name, args } }: Application\n): TargetedHandler<H> {\n const known = (names: readonly string[], holds: (name: string) => boolean) =>\n new Set(\n names.map((each) =>\n holds(each)\n ? each\n : extensionError(\n `Extension \"${name}\" target names unknown model or operation \"${each}\".`,\n name\n )\n )\n );\n return {\n extension: name,\n handler,\n args,\n inner,\n on: on && {\n models: known(on.models ?? Object.keys(schema), (model) =>\n Object.hasOwn(schema, model)\n ),\n operations: known(on.operations ?? [...MODEL_OPERATIONS], (operation) =>\n MODEL_OPERATIONS.has(operation)\n ),\n },\n };\n}\n\n/** One first moment appended to the chain's, in the order the parts join. */\nfunction appendFirst(\n application: Application,\n spec: CallSpec,\n first: FirstMoment\n): void {\n const { next } = application;\n next.call = {\n ...targetedHandlers([\n ...(next.call?.placed ?? []),\n placed(spec, first, application),\n ]),\n apply: runFirstMoments,\n };\n}\n\n/** What `call` returns: its first moment, made against the schema it joins. */\nfunction callPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n // What watches the call's writes comes with a set that names writes\n // (`target(writes)`): a call that only patches does not carry it.\n if (spec.watch) application.bring(spec.watch);\n appendFirst(application, spec, firstOf(spec, application.schema));\n },\n };\n}\n\n/**\n * What `around` returns: its first moment, and its second around the\n * prepared call, nearest the core with `inner` (after every other part,\n * whatever the chain's order: a later extension's lands before it).\n */\nfunction aroundPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n const { next } = application;\n if (spec.watch) application.bring(spec.watch);\n const first = firstOf(spec, application.schema);\n appendFirst(application, spec, first);\n const handler = placed(spec, secondMoment(first), application);\n const list = next.around?.placed ?? [];\n // A stable sort: the parts without `inner` first, each group in\n // chain order.\n next.around = targetedHandlers(\n [...list, handler].sort((a, b) => Number(!!a.inner) - Number(!!b.inner))\n );\n coordinate(next, QUERIES);\n },\n };\n}\n\n/**\n * A first moment alone: it reads, patches or refuses each call it selects,\n * before validation; without a target, every model call and raw statement.\n */\nexport function call<T extends AnyTarget, M = never, O = never>(\n handler: (c: MomentOne<T, M, O>) => void,\n selected?: Selection<T, M, O>\n): Part<T, EmptyFacts>;\nexport function call(\n handler: (context: never) => unknown,\n selected?: unknown\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"call() takes a function of the call\");\n const on = selectionOf(selected);\n return callPart({ handler, on, watch: on?.watch });\n}\n\n/**\n * Both moments: the first may return a second, `(run) => …`, which runs\n * around the prepared call. With `{ inner: true }` it sits nearest the core,\n * whatever the chain's order (a part that may answer for the core).\n */\nexport function around<T extends AnyTarget, M = never, O = never>(\n handler: AroundHandler<T, M, O>,\n selected?: Selection<T, M, O>,\n options?: { readonly inner?: true }\n): Part<T, AroundFacts<M, O>>;\nexport function around(\n handler: (context: never) => unknown,\n selected?: unknown,\n options?: { readonly inner?: true }\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"around() takes a function of the call\");\n const on = selectionOf(selected);\n return aroundPart({\n handler,\n on,\n keep: keepSecond,\n told: rawTold,\n watch: on?.watch,\n inner: options?.inner,\n });\n}\n"],"mappings":"4XAwBA,MAAa,EAAkD,IAAI,IAbzC,CACxB,SACA,UACA,OACA,SACA,OACA,OACA,OACA,OACA,KACD,CAKA,CCeD,SAAgB,iBACd,EAC2B,CAC3B,IAAM,EAASA,EAAO,OAAQ,GAAU,CAAC,EAAM,GAAG,CAC5C,EAAQ,IAAI,IAClB,MAAO,CACL,OAAA,EACA,SACA,SAAS,EAAO,EAAW,CACzB,GAAI,IAAU,IAAA,GAAW,OAAO,EAAO,OAAS,EAAI,EAAS,IAAA,GAE7D,IAAM,EAAO,EAAK,EADN,GAAG,EAAM,GAAG,QAEtBA,EAAO,QACJ,CAAE,QACD,CAAC,GAAO,EAAG,OAAO,IAAI,EAAM,EAAI,EAAG,WAAW,IAAI,EAAU,CAC/D,CACF,CACD,OAAO,EAAK,OAAS,EAAI,EAAO,IAAA,IAEnC,CCsCH,MAAM,EAA0C,OAAO,OAAO,EAAE,CAAC,CASjE,SAAS,QACP,CAAE,UAAS,OAAM,OAAM,SACvB,EACa,CACb,IAAM,OACJ,CAAE,YAAW,KAAM,GACnB,EACA,EACA,EACA,EACA,EACA,IACG,CACH,IAAM,SAAW,EAAiB,IAChC,IAAI,EACF,cAAc,EAAU,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AC7C,YAAY,EAAa,EAAM,QAAQ,EAAM,EAAY,OAAO,CAAC,EAEpE,CAQH,SAAS,WAAW,EAA+B,CACjD,MAAO,CACL,KAAK,EAAa,CAChB,GAAM,CAAE,QAAS,EACb,EAAK,OAAO,EAAY,MAAM,EAAK,MAAM,CAC7C,IAAM,EAAQ,QAAQ,EAAM,EAAY,OAAO,CAC/C,YAAY,EAAa,EAAM,EAAM,CACrC,IAAM,EAAU,OAAO,EAAM,aAAa,EAAM,CAAE,EAAY,CAI9D,EAAK,OAAS,iBACZ,CAAC,GAJU,EAAK,QAAQ,QAAU,EAAE,CAI1B,EAAQ,CAAC,MAAM,EAAG,IAAM,OAAO,CAAC,CAAC,EAAE,MAAM,CAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CACzE,CACD,EAAW,EAAM,EAAQ,EAE5B,CAWH,SAAgB,KACd,EACA,EACS,CAGT,GAAI,CAAC,EAAgC,EAAQ,CAC3C,MAAU,UAAU,sCAAsC,CAC5D,IAAM,EAAK,EAAY,EAAS,CAChC,OAAO,SAAS,CAAE,UAAS,KAAI,MAAO,GAAI,MAAO,CAAC,CAapD,SAAgB,OACd,EACA,EACA,EACS,CAGT,GAAI,CAAC,EAAgC,EAAQ,CAC3C,MAAU,UAAU,wCAAwC,CAC9D,IAAM,EAAK,EAAY,EAAS,CAChC,OAAO,WAAW,CAChB,UACA,KACA,KAAM,WACN,KAAM,QACN,MAAO,GAAI,MACX,MAAO,GAAS,MACjB,CAAC"}
|
|
1
|
+
{"version":3,"file":"call-0bd_B9Vp.mjs","names":["placed","call"],"sources":["../src/extensions/request.ts","../src/extensions/targeted.ts","../src/extensions/call.ts"],"sourcesContent":["/**\n * The keys of a call's arguments that decide its result's shape, and the\n * types of what a first moment reads and patches.\n */\nimport type { Operations } from \"@client/types\";\n\n/**\n * The keys of a call's arguments that decide its result's shape: the one\n * list of them. A first moment's `c.set` refuses each (`call.ts`), and the\n * types of what it reads and patches leave out those its operation has.\n */\nconst RESULT_SHAPE_KEYS = [\n \"select\",\n \"include\",\n \"omit\",\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n \"by\",\n] as const;\n\n/** What `c.set` tests a patch's keys against. */\nexport const SHAPE_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set(\n RESULT_SHAPE_KEYS\n);\n\ntype ResultShapeKey = (typeof RESULT_SHAPE_KEYS)[number];\n\n/**\n * Which of those keys each operation has: a future projection spelling\n * extends the list and this table, and the patch types follow.\n */\ninterface ResultShapeKeysByOperation\n extends Record<Operations, ResultShapeKey> {\n findFirst: \"select\" | \"include\" | \"omit\";\n findMany: \"select\" | \"include\" | \"omit\";\n findUnique: \"select\" | \"include\" | \"omit\";\n findUniqueOrThrow: \"select\" | \"include\" | \"omit\";\n findFirstOrThrow: \"select\" | \"include\" | \"omit\";\n create: \"select\" | \"include\" | \"omit\";\n update: \"select\" | \"include\" | \"omit\";\n delete: \"select\" | \"include\" | \"omit\";\n upsert: \"select\" | \"include\" | \"omit\";\n createMany: \"select\" | \"omit\";\n updateMany: \"select\" | \"omit\";\n deleteMany: \"select\" | \"omit\";\n count: \"select\";\n aggregate: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n groupBy: \"by\" | \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n exist: never;\n}\n\ntype ResultShapeKeyFor<Operation extends Operations> =\n ResultShapeKeysByOperation[Operation];\n\n/** The operation input visible to an ordinary request transform. */\nexport type RequestTransformInput<\n Operation extends Operations,\n Input extends object,\n> = Omit<Input, ResultShapeKeyFor<Operation>>;\n\n/**\n * A shallow patch over the non-projection input. The optional `never`\n * properties make protected keys fail structurally, including held values.\n */\nexport type RequestTransformPatch<\n Operation extends Operations,\n Input extends object,\n> = Partial<RequestTransformInput<Operation, Input>> & {\n readonly [Key in ResultShapeKeyFor<Operation>]?: never;\n};\n","/**\n * The handlers of `call` and `around`, in chain order, each with the calls\n * its target selects, and the handlers one call runs: found the first time\n * a (model, operation) asks, and kept for the chain.\n */\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { FirstMoment, runFirstMoments } from \"./call\";\nimport type { CallHandler } from \"./chain-state\";\n\n/** One handler of a chain, and the calls it concerns. */\nexport interface TargetedHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends CallHandler<Handler> {\n /** The models and operations a target selects; every call without one. */\n readonly on?: {\n readonly models: ReadonlySet<string>;\n readonly operations: ReadonlySet<string>;\n };\n /** Placed nearest the core, after every other handler (`around`'s `inner`). */\n readonly inner?: boolean;\n}\n\n/** A chain's handlers of one moment, and the handlers one call runs. */\nexport interface TargetedHandlers<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly placed: readonly TargetedHandler<Handler>[];\n /** The handlers without a target: the only ones a raw statement runs. */\n readonly global: readonly CallHandler<Handler>[];\n readonly handlers: (\n model: string | undefined,\n operation: string\n ) => readonly CallHandler<Handler>[] | undefined;\n}\n\n/** The first moments of `call` and `around`, and what runs them for one call. */\nexport interface CallHandlers extends TargetedHandlers<FirstMoment> {\n readonly apply: typeof runFirstMoments;\n}\n\n/** The lookup of `placed`, in its order. */\nexport function targetedHandlers<Handler extends CallableFunction>(\n placed: readonly TargetedHandler<Handler>[]\n): TargetedHandlers<Handler> {\n const global = placed.filter((entry) => !entry.on);\n const found = new Map<string, readonly TargetedHandler<Handler>[]>();\n return {\n placed,\n global,\n handlers(model, operation) {\n if (model === undefined) return global.length > 0 ? global : undefined;\n const key = `${model}.${operation}`;\n const list = memo(found, key, () =>\n placed.filter(\n ({ on }) =>\n !on || (on.models.has(model) && on.operations.has(operation))\n )\n );\n return list.length > 0 ? list : undefined;\n },\n };\n}\n","/**\n * `call(fn, target?)` and `around(fn, target?, options?)`: a function on each\n * logical call, in two moments. Every first moment runs in chain order,\n * synchronously, before the call is validated: it reads the arguments and\n * this extension's own (`c.args`, `c.values`), patches the arguments\n * (`c.set`), or refuses the call by throwing. A first moment of\n * `around` may return a second moment, which runs around the prepared\n * call once every first moment ran and the call was validated: the first\n * extension applied outermost. `run()` executes the call once; its failure\n * is the call's, whatever the second moment does after it.\n *\n * Without a target, a part concerns every model call and every raw\n * statement; `target(...)` names model operations only, so a targeted part\n * never sees a raw statement.\n */\n\nimport type { Schema } from \"@client/types\";\nimport { QueryError, VibORMError } from \"@errors\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Application, ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { CallHandler, ResolvedArgs } from \"./chain-state\";\nimport type {\n AnyTarget,\n AroundFacts,\n AroundHandler,\n EmptyFacts,\n MomentOne,\n Part,\n Selection,\n} from \"./contract\";\nimport { coordinate, QUERIES } from \"./coordination\";\nimport { MODEL_OPERATIONS, type SelectionValue, selectionOf } from \"./on\";\nimport { CALL, type CallOrigin } from \"./origin\";\nimport type { AroundRunner } from \"./query\";\nimport { SHAPE_KEYS } from \"./request\";\nimport { type TargetedHandler, targetedHandlers } from \"./targeted\";\nimport { REGISTER, type Registering, type WatchPart } from \"./watch-part\";\n\n/**\n * What a first moment is handed, beside what `contract.ts` types: where the\n * part brings what tells `watch` and `settled`, what they register through.\n */\ninterface FirstContext extends Partial<Registering> {\n readonly kind: \"model\" | \"raw\";\n readonly schema: Schema;\n readonly model: string | undefined;\n readonly operation: string;\n readonly args: Readonly<Record<string, unknown>>;\n readonly values: AdmittedArgs;\n set(patch: unknown): void;\n /** A model call itself, for the words that read it (`database`, `key`). */\n readonly [CALL]: object | undefined;\n}\n\n/**\n * One `call` or `around` part, as its builder wrote it. What only `around`\n * or a watching set needs is handed in by the builder that has it, so a\n * program building `call` alone carries none of it.\n */\ninterface CallSpec {\n readonly handler: (context: FirstContext) => unknown;\n readonly on: SelectionValue | undefined;\n /** `around` only: keeps the second moment a first returned, for the call. */\n readonly keep?: (\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n ) => void;\n /**\n * `around` only: what a raw statement's first moment registers `settled`\n * through, kept on the call, which the host tells of the outcome.\n */\n readonly told?: (call: CallOrigin, extension: string) => Registering;\n /** What registers `watch` and `settled`, where the part brings what tells them. */\n readonly watch?: WatchPart | undefined;\n /** `around` only: placed nearest the core. */\n readonly inner?: boolean;\n}\n\n/**\n * One first moment, as the request lookup holds it: run for one call by\n * `runFirstMoments`, it keeps the second moment its handler returned.\n */\nexport type FirstMoment = (\n owner: Pick<CallHandler, \"extension\" | \"args\">,\n model: string | undefined,\n operation: string,\n state: { args: Readonly<Record<string, unknown>> },\n call: CallOrigin,\n declared: ResolvedArgs | undefined,\n admitted: AdmittedArgs | undefined\n) => void;\n\ntype SecondMoment = (run: unknown) => unknown;\n\nconst NO_VALUES: AdmittedArgs = /* @__PURE__ */ Object.freeze({});\n\n/**\n * One part's first moment against one schema. What the handler throws\n * refuses the call (an error of viborm's own as it is, any other as the\n * cause of a `QueryError`); a promise is refused, and so is a function\n * returned by `call`; a second moment returned by `around` is kept for the\n * call.\n */\nfunction firstOf(\n { handler, keep, told, watch }: CallSpec,\n schema: Schema\n): FirstMoment {\n const first: FirstMoment = (\n { extension, args: own },\n model,\n operation,\n state,\n call,\n declared,\n admitted\n ) => {\n const refusal = (problem: string, cause?: unknown) =>\n new QueryError(\n `Extension \"${extension}\" first moment for ${model === undefined ? operation : `${model}.${operation}`} ${problem}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n let returned: unknown;\n try {\n returned = handler({\n kind: model === undefined ? \"raw\" : \"model\",\n schema,\n model,\n operation,\n get args() {\n return state.args;\n },\n // An extension that declares arguments brings the chain's arguments.\n values: (own && declared?.owned(admitted, own)) ?? NO_VALUES,\n set(patch: unknown) {\n if (model === undefined || !isRecord(patch))\n throw refusal(\"set no model call's arguments\");\n for (const key of Object.keys(patch)) {\n const shape = SHAPE_KEYS.has(key);\n if (shape || declared?.names.has(key))\n throw refusal(\n shape\n ? `set \"${key}\", which decides the result's shape`\n : `set argument \"${key}\"`\n );\n }\n state.args = Object.freeze({ ...state.args, ...patch });\n },\n // Only a part on a set of writes watches a model call, and a raw\n // statement never reaches such a part; an `around` hears a raw\n // statement's outcome.\n ...(model === undefined\n ? told?.(call, extension)\n : watch?.registering(call, extension)),\n [CALL]: model === undefined ? undefined : call,\n });\n } catch (cause) {\n if (cause instanceof VibORMError) throw cause;\n throw refusal(\"threw\", cause);\n }\n // A first moment runs synchronously.\n if (isRecord(returned) && isFunction(returned.then))\n throw refusal(\"returned a promise\");\n if (!isFunction<SecondMoment>(returned)) return;\n if (keep === undefined)\n throw refusal(\"returned a function: write around()\");\n keep(call, first, returned);\n };\n return first;\n}\n\n/**\n * Every first moment of one call, in chain order, over its arguments with\n * the arguments taken out: what `chain.request.apply` runs before a model\n * call is validated, and before a raw statement is sent (`raw.ts`, with no\n * model and its input for arguments). The arguments each sees are those the\n * moments before it left. `call` is the one object both moments of the call\n * are handed: what links an `around` part's second moment to its first.\n */\nexport function runFirstMoments(\n operation: string,\n input: Readonly<Record<string, unknown>>,\n handlers: readonly CallHandler<FirstMoment>[],\n call: CallOrigin,\n model?: string,\n declared?: ResolvedArgs,\n admitted?: AdmittedArgs\n): Record<string, unknown> {\n // An argument that is no object is validation's to refuse, as it is.\n const state = {\n args: isRecord(input) ? Object.freeze({ ...input }) : input,\n };\n for (const handler of handlers)\n handler.handler(handler, model, operation, state, call, declared, admitted);\n return state.args;\n}\n\n/** A call's `seconds`: the second moment each `around` part's first returned. */\nexport type Seconds = Map<FirstMoment, SecondMoment>;\n\n/** What `around` hands its first moments: the call's second moments kept. */\nfunction keepSecond(\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n): void {\n (call.seconds ??= new Map()).set(first, second);\n}\n\n/**\n * What a raw statement's first moment registers through: its `settled`\n * functions, kept on the call, which the host tells of an execute's\n * outcome. A raw statement shows no rows: a `watch` would never be told,\n * and is refused.\n */\nconst rawTold = (call: CallOrigin, extension: string): Registering => ({\n [REGISTER]({ settled, collect, tell }) {\n if (settled === undefined) return false;\n (call.told ??= []).push({ extension, listener: settled, collect, tell });\n return true;\n },\n});\n\n/** The second moment of one `around` part: the second its first returned for this call. */\nconst secondMoment =\n (first: FirstMoment): AroundRunner =>\n (prepared, run) => {\n const second = prepared.call?.seconds?.get(first);\n return second === undefined ? run() : second(run);\n };\n\n/**\n * One part's handler, placed on the calls of its target; on every call\n * without one. A name the schema or the operations do not hold is refused:\n * the types refuse it where `target` is written, and a caller without them\n * would otherwise get a part that never runs.\n */\nfunction placed<H extends CallableFunction>(\n { on, inner }: CallSpec,\n handler: H,\n { schema, owner: { name, args } }: Application\n): TargetedHandler<H> {\n const known = (names: readonly string[], holds: (name: string) => boolean) =>\n new Set(\n names.map((each) =>\n holds(each)\n ? each\n : extensionError(\n `Extension \"${name}\" target names unknown model or operation \"${each}\".`,\n name\n )\n )\n );\n return {\n extension: name,\n handler,\n args,\n inner,\n on: on && {\n models: known(on.models ?? Object.keys(schema), (model) =>\n Object.hasOwn(schema, model)\n ),\n operations: known(on.operations ?? [...MODEL_OPERATIONS], (operation) =>\n MODEL_OPERATIONS.has(operation)\n ),\n },\n };\n}\n\n/** One first moment appended to the chain's, in the order the parts join. */\nfunction appendFirst(\n application: Application,\n spec: CallSpec,\n first: FirstMoment\n): void {\n const { next } = application;\n next.call = {\n ...targetedHandlers([\n ...(next.call?.placed ?? []),\n placed(spec, first, application),\n ]),\n apply: runFirstMoments,\n };\n}\n\n/** What `call` returns: its first moment, made against the schema it joins. */\nfunction callPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n // What watches the call's writes comes with a set that names writes\n // (`target(writes)`): a call that only patches does not carry it.\n if (spec.watch) application.bring(spec.watch);\n appendFirst(application, spec, firstOf(spec, application.schema));\n },\n };\n}\n\n/**\n * What `around` returns: its first moment, and its second around the\n * prepared call, nearest the core with `inner` (after every other part,\n * whatever the chain's order: a later extension's lands before it).\n */\nfunction aroundPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n const { next } = application;\n if (spec.watch) application.bring(spec.watch);\n const first = firstOf(spec, application.schema);\n appendFirst(application, spec, first);\n const handler = placed(spec, secondMoment(first), application);\n const list = next.around?.placed ?? [];\n // A stable sort: the parts without `inner` first, each group in\n // chain order.\n next.around = targetedHandlers(\n [...list, handler].sort((a, b) => Number(!!a.inner) - Number(!!b.inner))\n );\n coordinate(next, QUERIES);\n },\n };\n}\n\n/**\n * A first moment alone: it reads, patches or refuses each call it selects,\n * before validation; without a target, every model call and raw statement.\n */\nexport function call<T extends AnyTarget, M = never, O = never>(\n handler: (c: MomentOne<T, M, O>) => void,\n selected?: Selection<T, M, O>\n): Part<T, EmptyFacts>;\nexport function call(\n handler: (context: never) => unknown,\n selected?: unknown\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"call() takes a function of the call\");\n const on = selectionOf(selected);\n return callPart({ handler, on, watch: on?.watch });\n}\n\n/**\n * Both moments: the first may return a second, `(run) => …`, which runs\n * around the prepared call. With `{ inner: true }` it sits nearest the core,\n * whatever the chain's order (a part that may answer for the core).\n */\nexport function around<T extends AnyTarget, M = never, O = never>(\n handler: AroundHandler<T, M, O>,\n selected?: Selection<T, M, O>,\n options?: { readonly inner?: true }\n): Part<T, AroundFacts<M, O>>;\nexport function around(\n handler: (context: never) => unknown,\n selected?: unknown,\n options?: { readonly inner?: true }\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"around() takes a function of the call\");\n const on = selectionOf(selected);\n return aroundPart({\n handler,\n on,\n keep: keepSecond,\n told: rawTold,\n watch: on?.watch,\n inner: options?.inner,\n });\n}\n"],"mappings":"wVAwBA,MAAa,EAAkD,IAAI,IAbzC,CACxB,SACA,UACA,OACA,SACA,OACA,OACA,OACA,OACA,KACD,CAKA,CCeD,SAAgB,EACd,EAC2B,CAC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AM,EAAK,EAAY,EAAS,CAChC,OAAO,EAAS,CAAE,UAAS,KAAI,MAAO,GAAI,MAAO,CAAC,CAapD,SAAgB,EACd,EACA,EACA,EACS,CAGT,GAAI,CAAC,EAAgC,EAAQ,CAC3C,MAAU,UAAU,wCAAwC,CAC9D,IAAM,EAAK,EAAY,EAAS,CAChC,OAAO,EAAW,CAChB,UACA,KACA,KAAM,EACN,KAAM,EACN,MAAO,GAAI,MACX,MAAO,GAAS,MACjB,CAAC"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`);async function
|
|
4
|
-
`)}\n`);for(let e of
|
|
2
|
+
import{N as e}from"./model-Dtd37Sky.mjs";import{c as t}from"./time-step-DJaIhpAz.mjs";import{i as n}from"./validator-DMzH5Tz0.mjs";import{t as r}from"./version-0BDwfy7C.mjs";import{b as i,i as a,n as o}from"./serializer-ettLu5xG.mjs";import{a as s}from"./identity-CJlRQA-m.mjs";import{n as c}from"./libsql-DEZ0uhK2.mjs";import{t as l}from"./mysql-BFPF8xyv.mjs";import{t as u}from"./postgres-DQQE2ys_.mjs";import{t as d}from"./every-JpbiHdMb.mjs";import{a as f,n as p,o as m,s as h,t as g}from"./client-DEfFqv4S.mjs";import{a as _,i as v,n as y,r as b}from"./utils-BHkJsduV.mjs";import{t as x}from"./fs-estate-n-QpsFqb.mjs";import{t as S}from"./introspect-q3Rf_Xv8.mjs";import{Command as C,InvalidArgumentError as ee}from"commander";import{existsSync as te,writeFileSync as ne}from"node:fs";import{resolve as w}from"node:path";import{loadEnvFile as T}from"node:process";import{writeFile as E}from"node:fs/promises";import{cancel as D,confirm as O,isCancel as k,note as A,outro as j}from"@clack/prompts";const M=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,N=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},P=t=>{let n=Object.values(t).filter(t=>e(t)!==void 0).length,r=`${Object.keys(t).length-n} models`;return n===0?r:`${r}, ${n} ${n===1?`view`:`views`}`},F=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
|
|
3
|
+
`),I={postgresql:()=>u.lx(),mysql:()=>l.lx(),sqlite:()=>c.lx(),surrealql:e=>i(e).lx()};function L(t,{models:n,driver:r}){let i=t.valid?I[r.dialect]:void 0;if(i===void 0)return t;let s=[...t.errors];for(let[t,o]of Object.entries(n))if(e(o)!==void 0)try{let e=i(r);e&&a(e,{schema:n},o)}catch(e){s.push({code:`W005`,message:e instanceof Error?e.message:String(e),severity:`error`,model:t})}let c=s.length===0&&R[r.dialect];if(c&&Object.values(n).some(t=>e(t)?.refresh===`auto`))try{o(n,{migrationDriver:c()})}catch(e){let t=e.meta;if(t?.model===void 0)throw e;s.push({code:`W005`,message:e.message,severity:`error`,model:Object.keys(n).find(e=>n[e][`~`].names.sql===t.model)??t.model??``})}return{...t,errors:s,valid:s.length===0}}const R={mysql:()=>l};async function z(e){await _({config:e.config,skipValidation:!0},e.json,async r=>{let{models:i}=r;t(i);let a=L(n(i),r),o=e.db?await h({$driver:r.driver,$schema:i}):void 0,s=o?.filter(M)??[];if(e.json)process.stdout.write(`${JSON.stringify(o?{...a,storage:o}:a,null,2)}\n`);else{for(let e of a.errors)process.stderr.write(`error ${F(e)}\n`);for(let e of a.warnings)process.stderr.write(`warning ${F(e)}\n`);for(let e of s)process.stderr.write(`error ${N(e)}\n`);process.stdout.write(a.valid?`Schema valid (${P(i)}).\n`:`Schema invalid: ${a.errors.length} error(s).\n`),o&&process.stdout.write(`Storage audited: ${o.length} column(s), ${s.length} need repair.\n`)}(!a.valid||s.length>0)&&(process.exitCode=1)})}function re(){return new C(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(z)}const B=re(),V=/^[0-9a-f]{8,63}$/;function H(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new ee(`must be a positive safe integer`);return t}function U(e){if(e)return s(e)?{id:e}:V.test(e)?{prefix:e}:{name:e}}const W=e=>e.type===`destructive`?e.proceed():void 0,G=async e=>{if(e.type!==`destructive`)return;let t=await O({message:`${e.description} — approve?`,initialValue:!1});return!k(t)&&t?e.proceed():e.reject()};function K(e,t){if(e.migrations?.resolve)return e.migrations.resolve;if(t.acceptDataLoss)return W;if(!(t.dryRun||t.json||!process.stdin.isTTY))return G}async function q(e,t,n){await _({config:e.opts().config},t.json,async e=>{let r=w(t.dir??e.migrations?.dir??`./migrations`),i=e.migrations?.storage??x(r);await n(g(e.client,{storage:i,...e.migrations?.tables===void 0?{}:{tables:e.migrations.tables}}),e,i)})}function J(){let e=new C(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--low-lock`,`PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps`).option(`--accept-data-loss`,`Approve destructive changes (drops, type changes) for this generate`).option(`--adopt <table...>`,`Adopt existing listed tables without DDL; apply proves each equals its declaration`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{let r=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:s(t.from)?t.from:(await e.show(U(t.from))).stateId,i;if(t.custom){let n=await b(w(t.custom)),a=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!a)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(r===void 0?o.leaves.length===0?[null]:[...o.leaves]:[r]);i=typeof a==`function`?await a(s):a}let a=K(n,t),o=await e.generate({name:t.name,from:r,dryRun:t.dryRun,...t.lowLock?{lowLock:!0}:{},...t.adopt?{adopt:t.adopt}:{},...a?{resolve:a}:{},...i?{manualMigration:i}:{}});if(t.json)v(o,!0);else{process.stdout.write(`${o.outcome}: ${o.name??`No schema changes`}${o.stateId?` (${o.stateId})`:``}\n`);for(let e of o.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(f).join(`
|
|
4
|
+
`)}\n`);for(let e of o.warnings??[])process.stderr.write(`warning: ${e}\n`);(o.reviewSql||o.sql)&&process.stdout.write(`${o.reviewSql||o.sql}\n`)}t.jl&&o.reviewSql&&await E(w(t.jl),o.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.check();v(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await q(e,n,async(e,r,i)=>{let a=await e.show(U(t));if(!(n.sql||n.jl)){v(a,!!n.json);return}let o=await m(i),s=o.states.get(a.stateId),c=s&&o.sql.get(s.sqlHash);if(!(s&&c))throw Error(`The authenticated state SQL is unavailable`);let l=p(s.parents,s.destinationChecks,c);n.json?v({...a,reviewSql:l},!0):(v(a,!1),process.stdout.write(l)),n.jl&&await E(w(n.jl),l,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.verify();v(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,H).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.log();v(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.apply({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,H).option(`--accept-data-loss`,`Approve destructive changes the rollback makes to populated tables`).option(`--expect-revision <n>`,`Refuse unless the marker is at this revision`,H).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);let r=K(n,t),i={dryRun:t.dryRun,...r?{resolve:r}:{},...t.expectRevision===void 0?{}:{expectRevision:t.expectRevision}},a=await e.down(t.to?{to:U(t.to),...i}:{steps:t.steps,...i});if(!a.preview||t.json)v(a,!!t.json);else{for(let e of a.edges)process.stdout.write(e.sql);a.refusal&&process.stderr.write(`down would refuse: ${a.refusal.code}: ${a.refusal.message}\n`)}a.preview&&a.refusal&&(process.exitCode=1)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.baseline({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`reanchor`).description(`After a restore left the history older than the database, move the marker to the state the live schema matches`).option(`--to <selector>`,`Adopt this state as the new baseline`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.reanchor({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;v(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);v(await e.reset({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const Y=J();function X(e){return[e.table,e.name].filter(Boolean).join(`.`)}function ie(e,t){let n=[];if(e.length>0){n.push(`Not in the document (${e.length}):`);for(let t of e)n.push(` - ${t.kind} ${X(t)}: ${t.reason}`)}if(t.length>0){n.push(`Warnings (${t.length}):`);for(let e of t)n.push(` - [${e.kind}] ${X(e)}: ${e.message}`)}return n.length===0?`The document states the whole database; a push of it plans nothing.
|
|
5
5
|
`:`${n.join(`
|
|
6
|
-
`)}\n`}async function
|
|
7
|
-
`),`Push plan`)}async function
|
|
8
|
-
`),e.dryRun){e.json?
|
|
6
|
+
`)}\n`}async function ae(e){try{if(!e.json)throw Error(`viborm pull writes a JSON schema document: pass --json. A TypeScript schema is not generated yet.`);let t=w(process.cwd(),`.env`);te(t)&&T(t);let n=e.url??process.env.DATABASE_URL;if(!n)throw Error(`viborm pull needs a connection string: pass --url or set DATABASE_URL.`);let r=await S({url:n,...e.tables===void 0?{}:{tables:e.tables},...e.light?{light:!0}:{}}),i=`${JSON.stringify(r.document,null,2)}\n`;e.out===void 0?process.stdout.write(i):ne(w(process.cwd(),e.out),i),process.stderr.write(ie(r.skipped,r.warnings))}catch(t){y(t,e.json===!0)}}function oe(){return new C(`pull`).description(`Read an existing database into a schema document (viborm/schema/json)`).option(`--json`,`Write the JSON schema document`).option(`--url <url>`,`Connection string (postgres://, mysql://, file:, libsql://); defaults to DATABASE_URL`).option(`--out <path>`,`Write the document to this file instead of stdout`).option(`--light`,`Only what a client needs (no indexes); migrations refuse the document`).option(`--tables <names...>`,`Only these tables (exact physical names, space- or comma-separated)`,(e,t)=>[...t??[],...e.split(`,`).map(e=>e.trim()).filter(Boolean)]).action(ae)}const se=oe();function Z(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);A([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
|
|
7
|
+
`),`Push plan`)}async function Q(e){await _({config:e.config},e.json,async t=>{let n=t.migrations?.tables===void 0?g(t.client):g(t.client,{tables:t.migrations.tables}),r=await n.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...t.migrations?.resolve?{resolve:t.migrations.resolve}:{}});if(!e.json&&t.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(t.driver.driverName)&&(await t.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
|
|
8
|
+
`),e.dryRun){e.json?v(r,!0):Z(r);return}if(e.json||Z(r),r.destructive&&!e.acceptDataLoss&&(e.p9||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(r.outcome!==`noop`&&!e.p9&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await O({message:r.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!r.destructive});if(k(e)||!e){D(`Push cancelled.`);return}}let i=await n.push({consent:r.consent});e.json?v(i,!0):j(i.outcome===`noop`?`Schema is up to date.`:`Push applied.`)})}function ce(){return new C(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(Q)}const le=ce();d();const $=new C;$.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(r),$.addCommand(B),$.addCommand(le),$.addCommand(Y),$.addCommand(se);try{await $.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}for(let e of[process.stdout,process.stderr])e.writableLength>0&&await new Promise(t=>e.write(``,()=>t()));process.exit();export{};
|
|
9
9
|
//# sourceMappingURL=cli.mjs.map
|