viborm 1.1.0 → 1.2.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-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- 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/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
- package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
- package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-BbcE-gyl.d.mts → index-C_XLSTy2.d.mts} +624 -351
- package/dist/index.d.mts +2 -2
- 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/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -561
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- 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/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.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-Bbw8W81b.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
- package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
- package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-De1l_ZMF.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -33
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
- package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-C8gXvWIA.mjs +0 -2
- package/dist/client-C8gXvWIA.mjs.map +0 -1
- package/dist/client-z9mcpRtA.mjs +0 -435
- package/dist/client-z9mcpRtA.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs.map +0 -1
- package/dist/driver-ZIbkciaz.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
- package/dist/error-mapping-LKqxnw-b.mjs +0 -2
- package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BLqNdigQ.mjs +0 -2
- package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
- package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
- package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-CKLOBSKl.mjs +0 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
- package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
- package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-CRFUUfNn.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-De1l_ZMF.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
package/dist/bun-sql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, d as MigrationSessionAttestation, h as DriverResultParser, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/drivers/bun-sql/index.d.ts
|
|
4
4
|
|
|
@@ -12,8 +12,16 @@ interface BunSQL {
|
|
|
12
12
|
readonly serializedValues: string;
|
|
13
13
|
};
|
|
14
14
|
begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;
|
|
15
|
-
|
|
15
|
+
/** `timeout` in seconds: past it, open connections are closed anyway. */
|
|
16
|
+
close(options?: {
|
|
17
|
+
readonly timeout?: number;
|
|
18
|
+
}): Promise<void>;
|
|
16
19
|
reserve(): Promise<BunSQLReservedConnection>;
|
|
20
|
+
/** Bun's resolved client options; migration admission reads its host. */
|
|
21
|
+
readonly options?: {
|
|
22
|
+
readonly hostname?: unknown;
|
|
23
|
+
readonly url?: unknown;
|
|
24
|
+
};
|
|
17
25
|
}
|
|
18
26
|
interface BunSQLTransaction {
|
|
19
27
|
(strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;
|
|
@@ -53,6 +61,13 @@ interface BunSQLDriverOptions {
|
|
|
53
61
|
postgis?: boolean;
|
|
54
62
|
/** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */
|
|
55
63
|
namespace?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Your claim, at your risk, that every connection this client opens is one
|
|
66
|
+
* server session for its whole life. It lifts migrations' refusal of
|
|
67
|
+
* Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never
|
|
68
|
+
* need it.
|
|
69
|
+
*/
|
|
70
|
+
migrationSessionAttestation?: MigrationSessionAttestation;
|
|
56
71
|
}
|
|
57
72
|
type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions & C;
|
|
58
73
|
declare class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {
|
|
@@ -69,6 +84,8 @@ declare class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {
|
|
|
69
84
|
*/
|
|
70
85
|
private readonly suppliedClient;
|
|
71
86
|
constructor(options?: BunSQLDriverOptions);
|
|
87
|
+
/** Every host or URL this driver's client connects through, for migration admission. */
|
|
88
|
+
protected migrationSessionEndpoints(): readonly unknown[];
|
|
72
89
|
/**
|
|
73
90
|
* The transport this driver connects through.
|
|
74
91
|
*
|
package/dist/bun-sql.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{d as n,l as r}from"./error-mapping-CnPCv1dm.mjs";import{s as i}from"./execution-context-BKR3bgES.mjs";import{n as a}from"./client-BLiBmykn.mjs";import{i as o,t as s}from"./pinned-session-CLxj5M5e.mjs";import{c,d as l,o as u,t as d,u as f}from"./driver-BlnKXPFF.mjs";import{t as p}from"./postgres-adapter-CQD2oGuD.mjs";function normalizeBunSQLParams(e,t){let n;for(let r=0;r<t.length;r+=1){let i=t[r];Array.isArray(i)&&(n??=[...t],n[r]=e.array(i,`TEXT`).serializedValues)}return n??t}const m={parseField:(e,t,n)=>t===`int`&&e instanceof Int32Array?n(Array.from(e),t):n(e,t)},h={client:!0,databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,namespace:!0,migrationSessionAttestation:!0};var BunSQLDriver=class extends d{result=m;maxBindParametersPerStatement=65535;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`bun-sql`);let t=l(e);this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient&&(this.client=this.suppliedClient),p(this,t,e),u(this,`migrationSessionAttestation`,f(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions,n=this.suppliedClient?.options;return[e,t?.hostname,n?.hostname,n?.url]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{SQL:e}=await import(`bun`);return this.driverOptions.databaseUrl?new e({...this.driverOptions.options,url:this.driverOptions.databaseUrl}):new e(this.driverOptions.options??{})}async closeClient(e){e!==this.suppliedClient&&await e.close()}async execute(e,n,r,i){let a=i?.operation??`execute`,o=await e.unsafe(n,normalizeBunSQLParams(e,r));return{rows:o,rowCount:t(o.count,{provider:`bun-sql`,operation:a})}}async executeRaw(e,n,r,i){let a=i?.operation??`executeRaw`,o=await e.unsafe(n,r);return{rows:o,rowCount:t(o.count,{provider:`bun-sql`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,t,a){if(`savepoint`in e)throw r(this.driverName);return n({run:t=>e.begin(t),callback:t,phases:i(a),close:async()=>void 0})}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(`savepoint`in e)throw r(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>o({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.close({timeout:s/1e3})}})}}};function createClient(e){c(e,`bun-sql`,h);let{client:t,databaseUrl:n,options:r,pgvector:i,postgis:o}=e;return a(e,new BunSQLDriver({client:t,databaseUrl:n,options:r,pgvector:i,postgis:o,namespace:l(e),migrationSessionAttestation:f(e)}))}export{BunSQLDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=bun-sql.mjs.map
|
package/dist/bun-sql.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bun-sql.mjs","names":[],"sources":["../src/drivers/bun-sql/index.ts"],"sourcesContent":["/**\n * Bun SQL Driver\n *\n * Driver implementation for Bun's built-in PostgreSQL client.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { unsupportedVector } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN SQL\n// ============================================================\n\n// Bun's SQL type - we define inline to avoid requiring bun types at compile time\n// Every result is an array carrying its required provider row count.\ntype BunSQLResult<T> = T[] & { count: number };\n\ninterface BunSQL {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n close(): Promise<void>;\n reserve(): Promise<BunSQLReservedConnection>;\n}\n\ninterface BunSQLTransaction {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n}\n\n/**\n * Bun's `unsafe()` path does not invoke its array helper: a plain JavaScript\n * array is bound as `Array#toString()`, which is not PostgreSQL array input\n * syntax. The adapter has already validated ORM list members, so let Bun's own\n * PostgreSQL encoder escape their flat scalar text and leave the statement's\n * column context to infer the concrete array type.\n *\n * Verbatim raw execution deliberately bypasses this conversion. A verbatim\n * caller owns the provider representation and receives Bun's ordinary\n * `unsafe()` semantics; a tagged safe-raw fragment stays on typed execution.\n */\nfunction normalizeBunSQLParams(\n client: BunSQL | BunSQLTransaction,\n params: unknown[]\n): unknown[] {\n let normalized: unknown[] | undefined;\n for (let index = 0; index < params.length; index += 1) {\n const param = params[index];\n if (!Array.isArray(param)) continue;\n normalized ??= [...params];\n normalized[index] = client.array(param, \"TEXT\").serializedValues;\n }\n return normalized ?? params;\n}\n\n/** Bun decodes PostgreSQL `integer[]` as `Int32Array`, not `Array`. */\nconst bunSQLResultParser: DriverResultParser = {\n parseField: (value, scalarType, next) => {\n if (scalarType === \"int\" && value instanceof Int32Array) {\n return next(Array.from(value), scalarType);\n }\n return next(value, scalarType);\n },\n};\n\n/**\n * Bun's `ReservedSQL` is an `SQL` bound to one connection, plus `release()` —\n * not a reduced surface. Declaring it that way is both faithful and load-\n * bearing: a reserved connection is what {@link BunSQLDriver.pinnedSession}\n * hands to the pinned view as its client, and the view's transaction control\n * runs `BEGIN`/`COMMIT` on it through the same `unsafe` path every statement\n * uses.\n */\ninterface BunSQLReservedConnection extends BunSQL {\n release(): void;\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLOptions {\n hostname?: string;\n port?: number;\n username?: string;\n password?: string;\n database?: string;\n tls?: boolean | object;\n max?: number;\n idleTimeout?: number;\n maxLifetime?: number;\n}\n\nexport interface BunSQLDriverOptions {\n client?: BunSQL;\n databaseUrl?: string;\n options?: BunSQLOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions &\n C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly result: DriverResultParser = bunSQLResultParser;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly driverOptions: BunSQLDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: BunSQL | undefined;\n\n constructor(options: BunSQLDriverOptions = {}) {\n super(\"postgresql\", \"bun-sql\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n }\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<BunSQL> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const { SQL } = await import(\"bun\");\n\n if (this.driverOptions.databaseUrl) {\n return new SQL({\n ...this.driverOptions.options,\n url: this.driverOptions.databaseUrl,\n }) as unknown as BunSQL;\n }\n\n return new SQL(this.driverOptions.options ?? {}) as unknown as BunSQL;\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to close it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: BunSQL): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.close();\n }\n\n protected async execute<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.unsafe<T>(\n sql,\n normalizeBunSQLParams(client, params)\n );\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n protected async executeRaw<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n /**\n * Bun's `sql.begin()` owns BEGIN and connection acquisition, so the isolation\n * level goes in as the transaction's first statement and there is no\n * acquisition step VibORM can bound.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQL | BunSQLTransaction,\n fn: (tx: BunSQLTransaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: (callback) => client.begin(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for Bun SQL, and the\n * producer its transaction control uses too, because the pinned view opens\n * `BEGIN`/`COMMIT` on this exact connection.\n *\n * Bun exposes only `release()` for a reserved connection — the same shape\n * postgres.js has — so a condemned session takes the same rule: reset with\n * `pg_advisory_unlock_all()`, and when that reset fails, abandoned rather\n * than returned to a pool with a lock state nobody can account for.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<BunSQL | BunSQLTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Settled at construction, never re-read: see `suppliedClient`.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it: see the\n // postgres.js driver, which has the same shape and the same\n // reason — a rejecting `close()` used to leave this condemned\n // transport installed for the next ordinary query.\n this.client = null;\n this.initPromise = null;\n await client.close();\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLDriver }>[P];\n}> {\n const { client, databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new BunSQLDriver({\n client,\n databaseUrl,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, BunSQLDriver>(config, driver);\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"bun-sql.mjs","names":[],"sources":["../src/drivers/bun-sql/index.ts"],"sourcesContent":["/**\n * Bun SQL Driver\n *\n * Driver implementation for Bun's built-in PostgreSQL client.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n Driver,\n type DriverResultParser,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN SQL\n// ============================================================\n\n// Bun's SQL type - we define inline to avoid requiring bun types at compile time\n// Every result is an array carrying its required provider row count.\ntype BunSQLResult<T> = T[] & { count: number };\n\ninterface BunSQL {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n begin<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n /** `timeout` in seconds: past it, open connections are closed anyway. */\n close(options?: { readonly timeout?: number }): Promise<void>;\n reserve(): Promise<BunSQLReservedConnection>;\n /** Bun's resolved client options; migration admission reads its host. */\n readonly options?: { readonly hostname?: unknown; readonly url?: unknown };\n}\n\ninterface BunSQLTransaction {\n (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown[]>;\n unsafe<T = unknown>(\n sql: string,\n params?: unknown[]\n ): Promise<BunSQLResult<T>>;\n array(\n values: unknown[],\n typeNameOrTypeID?: string\n ): { readonly serializedValues: string };\n savepoint<T>(fn: (sql: BunSQLTransaction) => Promise<T>): Promise<T>;\n}\n\n/**\n * Bun's `unsafe()` path does not invoke its array helper: a plain JavaScript\n * array is bound as `Array#toString()`, which is not PostgreSQL array input\n * syntax. The adapter has already validated ORM list members, so let Bun's own\n * PostgreSQL encoder escape their flat scalar text and leave the statement's\n * column context to infer the concrete array type.\n *\n * Verbatim raw execution deliberately bypasses this conversion. A verbatim\n * caller owns the provider representation and receives Bun's ordinary\n * `unsafe()` semantics; a tagged safe-raw fragment stays on typed execution.\n */\nfunction normalizeBunSQLParams(\n client: BunSQL | BunSQLTransaction,\n params: unknown[]\n): unknown[] {\n let normalized: unknown[] | undefined;\n for (let index = 0; index < params.length; index += 1) {\n const param = params[index];\n if (!Array.isArray(param)) continue;\n normalized ??= [...params];\n normalized[index] = client.array(param, \"TEXT\").serializedValues;\n }\n return normalized ?? params;\n}\n\n/** Bun decodes PostgreSQL `integer[]` as `Int32Array`, not `Array`. */\nconst bunSQLResultParser: DriverResultParser = {\n parseField: (value, scalarType, next) => {\n if (scalarType === \"int\" && value instanceof Int32Array) {\n return next(Array.from(value), scalarType);\n }\n return next(value, scalarType);\n },\n};\n\n/**\n * Bun's `ReservedSQL` is an `SQL` bound to one connection, plus `release()` —\n * not a reduced surface. Declaring it that way is both faithful and load-\n * bearing: a reserved connection is what {@link BunSQLDriver.pinnedSession}\n * hands to the pinned view as its client, and the view's transaction control\n * runs `BEGIN`/`COMMIT` on it through the same `unsafe` path every statement\n * uses.\n */\ninterface BunSQLReservedConnection extends BunSQL {\n release(): void;\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLOptions {\n hostname?: string;\n port?: number;\n username?: string;\n password?: string;\n database?: string;\n tls?: boolean | object;\n max?: number;\n idleTimeout?: number;\n maxLifetime?: number;\n}\n\nexport interface BunSQLDriverOptions {\n client?: BunSQL;\n databaseUrl?: string;\n options?: BunSQLOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport type BunSQLClientConfig<C extends DriverConfig> = BunSQLDriverOptions &\n C;\n\nconst BUN_SQL_CONFIG_KEYS: Record<keyof BunSQLDriverOptions, true> = {\n client: true,\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLDriver extends Driver<BunSQL, BunSQLTransaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly result: DriverResultParser = bunSQLResultParser;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n private readonly driverOptions: BunSQLDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: BunSQL | undefined;\n\n constructor(options: BunSQLDriverOptions = {}) {\n super(\"postgresql\", \"bun-sql\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n const supplied = this.suppliedClient?.options;\n return [databaseUrl, options?.hostname, supplied?.hostname, supplied?.url];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<BunSQL> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const { SQL } = await import(\"bun\");\n\n if (this.driverOptions.databaseUrl) {\n return new SQL({\n ...this.driverOptions.options,\n url: this.driverOptions.databaseUrl,\n }) as unknown as BunSQL;\n }\n\n return new SQL(this.driverOptions.options ?? {}) as unknown as BunSQL;\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to close it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: BunSQL): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.close();\n }\n\n protected async execute<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.unsafe<T>(\n sql,\n normalizeBunSQLParams(client, params)\n );\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n protected async executeRaw<T>(\n client: BunSQL | BunSQLTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.unsafe<T>(sql, params);\n return {\n rows: result,\n rowCount: normalizeProviderRowCount(result.count, {\n provider: \"bun-sql\",\n operation,\n }),\n };\n }\n\n /**\n * Bun's `sql.begin()` owns BEGIN and connection acquisition, so the isolation\n * level goes in as the transaction's first statement and there is no\n * acquisition step VibORM can bound.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Bun SQL acquires the connection inside sql.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQL | BunSQLTransaction,\n fn: (tx: BunSQLTransaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: (callback) => client.begin(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for Bun SQL, and the\n * producer its transaction control uses too, because the pinned view opens\n * `BEGIN`/`COMMIT` on this exact connection.\n *\n * Bun exposes only `release()` for a reserved connection — the same shape\n * postgres.js has — so a condemned session takes the same rule: reset with\n * `pg_advisory_unlock_all()`, and when that reset fails, abandoned rather\n * than returned to a pool with a lock state nobody can account for.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<BunSQL | BunSQLTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (\"savepoint\" in client) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Settled at construction, never re-read: see `suppliedClient`.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it: see the\n // postgres.js driver, which has the same shape and the same\n // reason — a rejecting `close()` used to leave this condemned\n // transport installed for the next ordinary query.\n this.client = null;\n this.initPromise = null;\n await client.close({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sql\", BUN_SQL_CONFIG_KEYS);\n const { client, databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new BunSQLDriver({\n client,\n databaseUrl,\n options,\n pgvector,\n postgis,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, BunSQLDriver>(config, driver);\n}\n"],"mappings":"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"}
|
package/dist/bun-sqlite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, p as SqliteMigrationCapability, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/drivers/bun-sqlite/index.d.ts
|
|
4
4
|
|
|
@@ -32,6 +32,11 @@ interface BunSQLiteOptions {
|
|
|
32
32
|
create?: boolean;
|
|
33
33
|
readwrite?: boolean;
|
|
34
34
|
strict?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM
|
|
37
|
+
* option: `bun:sqlite` has none of its own. Defaults to 5000.
|
|
38
|
+
*/
|
|
39
|
+
timeout?: number;
|
|
35
40
|
}
|
|
36
41
|
interface BunSQLiteDriverOptions {
|
|
37
42
|
client?: BunSQLiteDatabase;
|
|
@@ -43,22 +48,18 @@ declare class BunSQLiteDriver extends Driver<BunSQLiteDatabase, BunSQLiteDatabas
|
|
|
43
48
|
readonly adapter: DatabaseAdapter;
|
|
44
49
|
readonly maxBindParametersPerStatement: number | undefined;
|
|
45
50
|
readonly result: DriverResultParser;
|
|
51
|
+
readonly sqliteMigrationCapability: SqliteMigrationCapability;
|
|
46
52
|
protected readonly serializeTransactions = true;
|
|
47
53
|
private readonly driverOptions;
|
|
48
54
|
private readonly suppliedClient;
|
|
55
|
+
/** Interpolated into a PRAGMA, so it is admitted here as an integer. */
|
|
56
|
+
private readonly busyTimeout;
|
|
49
57
|
constructor(options?: BunSQLiteDriverOptions);
|
|
50
58
|
protected initClient(): Promise<BunSQLiteDatabase>;
|
|
51
59
|
protected closeClient(db: BunSQLiteDatabase): Promise<void>;
|
|
52
60
|
protected execute<T>(client: BunSQLiteDatabase, sql: string, params: unknown[], context?: QueryExecutionContext): Promise<QueryResult<T>>;
|
|
53
61
|
protected executeRaw<T>(client: BunSQLiteDatabase, sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
|
54
62
|
private runStatement;
|
|
55
|
-
/**
|
|
56
|
-
* SQLite has no isolation-level statement: one writer at a time on one
|
|
57
|
-
* connection makes every transaction serializable already. `Serializable` is
|
|
58
|
-
* therefore honored by construction, with no SQL to emit; the three weaker
|
|
59
|
-
* levels are refused because pretending to relax isolation we cannot relax
|
|
60
|
-
* would misreport what the transaction actually guarantees.
|
|
61
|
-
*/
|
|
62
63
|
protected transactionOptionSupport(): TransactionOptionSupport;
|
|
63
64
|
protected transaction<T>(client: BunSQLiteDatabase, fn: (tx: BunSQLiteDatabase) => Promise<T>, context?: QueryExecutionContext): Promise<T>;
|
|
64
65
|
}
|
package/dist/bun-sqlite.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,r as n}from"./validation-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,r as n}from"./validation-Dk9Q_-C7.mjs";import{n as r}from"./client-BLiBmykn.mjs";import{c as i,n as a,r as o,t as s}from"./driver-BlnKXPFF.mjs";import{a as c,c as l,i as u,l as d,n as f,s as p,t as m}from"./sqlite-utils-DlgokMJN.mjs";import{t as h}from"./sqlite-adapter-CW_3l6ea.mjs";function requireSafeIntegers(e){if(typeof e.safeIntegers!=`function`)throw new t(`bun:sqlite`,`Statement.safeIntegers`,`This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.`);return e}function reusesStatements(e){let t;for(let n=Object.getPrototypeOf(e);n;n=Object.getPrototypeOf(n))Object.hasOwn(n,`prepare`)&&(t=n.prepare);return e.prepare===t}const g=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function convertValuesForBunSQLite(e){return e.map(e=>{let t=f(e);if(typeof t==`string`&&g.test(t))throw TypeError(`bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.`);return t instanceof Uint8Array||!u(t)?t:l(t)})}const _={client:!0,dataDir:!0,options:!0};var BunSQLiteDriver=class extends s{adapter=new h;maxBindParametersPerStatement=32766;result=d;sqliteMigrationCapability=a;serializeTransactions=!0;driverOptions;suppliedClient;busyTimeout;constructor(e={}){if(super(`sqlite`,`bun-sqlite`),this.driverOptions=e,this.busyTimeout=e.options?.timeout??5e3,!Number.isSafeInteger(this.busyTimeout)||this.busyTimeout<0)throw new n(`The bun-sqlite "timeout" option must be a non-negative integer number of milliseconds.`,{meta:{driver:`bun-sqlite`,operation:`configuration`}});if(this.suppliedClient=e.client,this.suppliedClient){let e=this.suppliedClient.query(`PRAGMA foreign_keys`).get();if(!e||typeof e!=`object`||Reflect.get(e,`foreign_keys`)!==1)throw new n(`A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.`,{meta:{driver:`bun-sqlite`}});this.client=this.suppliedClient,Object.defineProperty(this,`connectionQueue`,{value:o(this.suppliedClient)})}}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{Database:e}=await import(`bun:sqlite`),t=this.driverOptions.dataDir??`:memory:`,{timeout:n,...r}=this.driverOptions.options??{},i=Object.keys(r).length===0?new e(t):new e(t,r);return i.exec(`PRAGMA foreign_keys = ON`),i.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`),i}async closeClient(e){e!==this.suppliedClient&&e.close()}async execute(e,t,n,r){let i=convertValuesForBunSQLite(n);return this.runStatement(e,t,i,r?.model!==`$raw`)}async executeRaw(e,t,n){let r=n?convertValuesForBunSQLite(n):void 0;return this.runStatement(e,t,r,!1)}runStatement(e,t,n,r){let i=r&&reusesStatements(e)?e.query(t):e.prepare(t);if(i.columnNames.length>0){requireSafeIntegers(i).safeIntegers(!0);let e=n?i.all(...n):i.all();return{rows:r?e:c(e),rowCount:e.length}}return{rows:[],rowCount:(n?i.run(...n):i.run()).changes}}transactionOptionSupport(){return m}async transaction(e,t,n){return p(e,t,n)}};function createClient(e){i(e,`bun-sqlite`,_,{databaseUrl:`pass the database file as dataDir`});let{client:t,dataDir:n,options:a}=e;return r(e,new BunSQLiteDriver({client:t,dataDir:n,options:a}))}export{BunSQLiteDriver,createClient};
|
|
2
2
|
//# sourceMappingURL=bun-sqlite.mjs.map
|
package/dist/bun-sqlite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { normalizeSQLiteRawRows } from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n runTransactionLifecycle,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n const options = this.driverOptions.options;\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (options === undefined || Object.keys(options).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, options)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(\"PRAGMA busy_timeout = 5000\");\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n /**\n * SQLite has no isolation-level statement: one writer at a time on one\n * connection makes every transaction serializable already. `Serializable` is\n * therefore honored by construction, with no SQL to emit; the three weaker\n * levels are refused because pretending to relax isolation we cannot relax\n * would misreport what the transaction actually guarantees.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"serializable-only\",\n isolationLevelReason:\n \"SQLite serializes transactions on a single connection and has no statement to weaken isolation, so only Serializable can be honored truthfully\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runTransactionLifecycle({\n begin: () => client.exec(\"BEGIN IMMEDIATE\"),\n callback: () => fn(client),\n commit: () => client.exec(\"COMMIT\"),\n // A failed BEGIN never grants rollback ownership. After a failed COMMIT,\n // successful rollback restores this same database, including :memory:.\n rollback: () => {\n if (client.inTransaction) client.exec(\"ROLLBACK\");\n },\n phases: getExecutionTransactionPhases(context),\n });\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n /**\n * Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM\n * option: `bun:sqlite` has none of its own. Defaults to 5000.\n */\n timeout?: number;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\nconst BUN_SQLITE_CONFIG_KEYS: Record<keyof BunSQLiteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n /** Interpolated into a PRAGMA, so it is admitted here as an integer. */\n private readonly busyTimeout: number;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n this.busyTimeout = options.options?.timeout ?? 5000;\n if (!Number.isSafeInteger(this.busyTimeout) || this.busyTimeout < 0) {\n throw new ClientInitializationError(\n 'The bun-sqlite \"timeout\" option must be a non-negative integer number of milliseconds.',\n { meta: { driver: \"bun-sqlite\", operation: \"configuration\" } }\n );\n }\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n // `timeout` is VibORM's own key, not one of bun:sqlite's open flags.\n const { timeout: _timeout, ...openFlags } =\n this.driverOptions.options ?? {};\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (Object.keys(openFlags).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, openFlags)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sqlite\", BUN_SQLITE_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../driver-
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../driver-B19QlFqn.mjs";var CloudflareKVCache=class extends t{#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{CloudflareKVCache};
|
|
2
2
|
//# sourceMappingURL=cloudflare-kv.mjs.map
|
package/dist/cache/memory.d.mts
CHANGED
package/dist/cache/memory.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../cache-BO57X0TT.mjs";import{t as n}from"../driver-B19QlFqn.mjs";var MemoryCache=class extends n{#e=new Map;#t;#n;constructor(e,...n){if(super(`memory`),n.length)throw new t(`MemoryCache received extra construction arguments.`);let r=1024;if(e!==void 0){let n;try{n=Object.getOwnPropertyDescriptors(e)}catch{throw new t(`MemoryCache options could not be inspected.`)}let i=n.maxEntries,a=i&&`value`in i?i.value:void 0;if(Reflect.ownKeys(n).length!==1||!i||!(`value`in i)||typeof a!=`number`||!Number.isSafeInteger(a)||a<1)throw new t(`MemoryCache options must contain a positive safe-integer maxEntries only.`);r=a}this.#t=r}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;){let e=this.#e.keys().next().value;e!==void 0&&this.#e.delete(e)}this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{MemoryCache};
|
|
2
2
|
//# sourceMappingURL=memory.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.mjs","names":["#store","#maxEntries","#idle","#schedule","#timer"],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport type { ClockTimer } from \"../../clock\";\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: ClockTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>,\n ...extra: never[]\n ) {\n super(\"memory\");\n if (extra.length)\n throw new CacheConfigurationError(\n \"MemoryCache received extra construction arguments.\"\n );\n let maxEntries = 1024;\n if (options !== undefined) {\n let descriptors: PropertyDescriptorMap;\n try {\n descriptors = Object.getOwnPropertyDescriptors(options);\n } catch {\n throw new CacheConfigurationError(\n \"MemoryCache options could not be inspected.\"\n );\n }\n const limit = descriptors.maxEntries;\n const supplied: unknown =\n limit && \"value\" in limit ? limit.value : undefined;\n if (\n Reflect.ownKeys(descriptors).length !== 1 ||\n !limit ||\n !(\"value\" in limit) ||\n typeof supplied !== \"number\" ||\n !Number.isSafeInteger(supplied) ||\n supplied < 1\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n maxEntries = supplied;\n }\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n while (this.#store.size > this.#maxEntries) {\n const oldest = this.#store.keys().next().value;\n if (oldest !== undefined) this.#store.delete(oldest);\n }\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"memory.mjs","names":["#store","#maxEntries","#idle","#schedule","#timer"],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport type { ClockTimer } from \"../../clock\";\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: ClockTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>,\n ...extra: never[]\n ) {\n super(\"memory\");\n if (extra.length)\n throw new CacheConfigurationError(\n \"MemoryCache received extra construction arguments.\"\n );\n let maxEntries = 1024;\n if (options !== undefined) {\n let descriptors: PropertyDescriptorMap;\n try {\n descriptors = Object.getOwnPropertyDescriptors(options);\n } catch {\n throw new CacheConfigurationError(\n \"MemoryCache options could not be inspected.\"\n );\n }\n const limit = descriptors.maxEntries;\n const supplied: unknown =\n limit && \"value\" in limit ? limit.value : undefined;\n if (\n Reflect.ownKeys(descriptors).length !== 1 ||\n !limit ||\n !(\"value\" in limit) ||\n typeof supplied !== \"number\" ||\n !Number.isSafeInteger(supplied) ||\n supplied < 1\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n maxEntries = supplied;\n }\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n while (this.#store.size > this.#maxEntries) {\n const oldest = this.#store.keys().next().value;\n if (oldest !== undefined) this.#store.delete(oldest);\n }\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"0HASA,IAAa,YAAb,cAEU,CAAY,CACpB,GAAkB,IAAI,IACtB,GACA,GAEA,YACE,EAEA,GAAG,EACH,CAEA,GADA,MAAM,SAAS,CACX,EAAM,OACR,MAAM,IAAI,EACR,qDACD,CACH,IAAI,EAAa,KACjB,GAAI,IAAY,IAAA,GAAW,CACzB,IAAI,EACJ,GAAI,CACF,EAAc,OAAO,0BAA0B,EAAQ,MACjD,CACN,MAAM,IAAI,EACR,8CACD,CAEH,IAAM,EAAQ,EAAY,WACpB,EACJ,GAAS,UAAW,EAAQ,EAAM,MAAQ,IAAA,GAC5C,GACE,QAAQ,QAAQ,EAAY,CAAC,SAAW,GACxC,CAAC,GACD,EAAE,UAAW,IACb,OAAO,GAAa,UACpB,CAAC,OAAO,cAAc,EAAS,EAC/B,EAAW,EAEX,MAAM,IAAI,EACR,4EACD,CACH,EAAa,EAEf,MAAA,EAAmB,EAGrB,MAAgB,IAAO,EAA4C,CACjE,IAAM,EAAS,MAAA,EAAY,IAAI,EAAI,CAQnC,OAPK,GACL,MAAA,EAAY,OAAO,EAAI,CACnB,KAAK,MAAM,KAAK,EAAI,EAAO,WAC7B,MAAA,GAAY,CACL,OAET,MAAA,EAAY,IAAI,EAAK,EAAO,CACrB,EAAO,QAPM,KAUtB,MAAgB,IACd,EACA,EACA,EACe,CAGf,IAFA,MAAA,EAAY,OAAO,EAAI,CACvB,MAAA,EAAY,IAAI,EAAK,CAAE,QAAO,UAAW,KAAK,MAAM,KAAK,CAAG,EAAY,CAAC,CAClE,MAAA,EAAY,KAAO,MAAA,GAAkB,CAC1C,IAAM,EAAS,MAAA,EAAY,MAAM,CAAC,MAAM,CAAC,MACrC,IAAW,IAAA,IAAW,MAAA,EAAY,OAAO,EAAO,CAEtD,MAAA,EAAe,EAAW,CAG5B,MAAgB,OAAO,EAA+B,CACpD,IAAK,IAAM,KAAO,EAAM,MAAA,EAAY,OAAO,EAAI,CAC/C,MAAA,GAAY,CAGd,MAAgB,MAAM,EAA+B,CACnD,IAAK,IAAM,KAAO,MAAA,EAAY,MAAM,CAC9B,EAAI,WAAW,EAAO,EAAE,MAAA,EAAY,OAAO,EAAI,CACrD,MAAA,GAAY,CAGd,IAAc,CACR,MAAA,EAAY,OAChB,MAAA,GAAa,QAAQ,CACrB,MAAA,EAAc,IAAA,IAGhB,GAAU,EAAQ,IAAc,CAC1B,MAAA,GAAe,CAAC,MAAA,EAAY,OAChC,MAAA,EAAc,KAAK,MAAM,eACjB,CACJ,MAAA,EAAc,IAAA,GACd,IAAM,EAAM,KAAK,MAAM,KAAK,CAC5B,IAAK,GAAM,CAAC,EAAK,KAAW,MAAA,EACtB,GAAO,EAAO,WAAW,MAAA,EAAY,OAAO,EAAI,CACtD,MAAA,GAAgB,EAElB,KAAK,IAAI,EAAO,IAAO,CACxB,CACD,MAAA,EAAY,SAAS,EAGvB,MAAe,YAA4B,CACzC,MAAA,EAAY,OAAO,CACnB,MAAA,GAAY"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-AdXAoy6l.mjs";var CacheInvalidTTLError=class extends n{static diagnosticName=`CacheInvalidTTLError`;constructor(e,n){super(e,t.CACHE_INVALID_TTL,n)}},CacheInvalidKeyError=class extends n{static diagnosticName=`CacheInvalidKeyError`;constructor(e,n){super(e,t.CACHE_INVALID_KEY,n)}},CacheOperationNotCacheableError=class extends n{static diagnosticName=`CacheOperationNotCacheableError`;constructor(e,n,r){super(`Operation "${e}" is not cacheable. Only read operations can be cached: ${n.join(`, `)}`,t.CACHE_OPERATION_NOT_CACHEABLE,{meta:{...r?.meta,operation:e}})}},CacheConfigurationError=class extends n{static diagnosticName=`CacheConfigurationError`;constructor(e,n){super(e,t.CACHE_CONFIGURATION,n)}};export{CacheOperationNotCacheableError as i,CacheInvalidKeyError as n,CacheInvalidTTLError as r,CacheConfigurationError as t};
|
|
2
|
+
//# sourceMappingURL=cache-BO57X0TT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-BO57X0TT.mjs","names":[],"sources":["../src/errors/cache.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorMeta } from \"./base\";\n\n/**\n * Invalid TTL format or value\n */\nexport class CacheInvalidTTLError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidTTLError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_TTL`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_TTL;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_TTL, options);\n }\n}\n\n/**\n * Invalid cache key (circular reference, uncacheable type)\n */\nexport class CacheInvalidKeyError extends VibORMError {\n static override readonly diagnosticName = \"CacheInvalidKeyError\";\n\n /** Literal discriminant: this class always carries `CACHE_INVALID_KEY`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_INVALID_KEY;\n\n constructor(message: string, options?: { meta?: VibORMErrorMeta }) {\n super(message, VibORMErrorCode.CACHE_INVALID_KEY, options);\n }\n}\n\n/**\n * Operation cannot be cached (e.g., mutation operations)\n */\nexport class CacheOperationNotCacheableError extends VibORMError {\n static override readonly diagnosticName = \"CacheOperationNotCacheableError\";\n\n /** Literal discriminant: this class always carries `CACHE_OPERATION_NOT_CACHEABLE`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE;\n\n constructor(\n operation: string,\n cacheableOperations: string[],\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `Operation \"${operation}\" is not cacheable. Only read operations can be cached: ${cacheableOperations.join(\", \")}`,\n VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE,\n {\n meta: { ...options?.meta, operation },\n }\n );\n }\n}\n\n/**\n * Invalid or missing cache configuration (options or driver)\n */\nexport class CacheConfigurationError extends VibORMError {\n static override readonly diagnosticName = \"CacheConfigurationError\";\n\n /** Literal discriminant: this class always carries `CACHE_CONFIGURATION`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_CONFIGURATION;\n\n constructor(\n message: string,\n options?: { cause?: Error | undefined; meta?: VibORMErrorMeta }\n ) {\n super(message, VibORMErrorCode.CACHE_CONFIGURATION, options);\n }\n}\n"],"mappings":"wFAKA,IAAa,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,qBAAb,cAA0C,CAAY,CACpD,OAAyB,eAAiB,uBAK1C,YAAY,EAAiB,EAAsC,CACjE,MAAM,EAAS,EAAgB,kBAAmB,EAAQ,GAOjD,gCAAb,cAAqD,CAAY,CAC/D,OAAyB,eAAiB,kCAK1C,YACE,EACA,EACA,EACA,CACA,MACE,cAAc,EAAU,0DAA0D,EAAoB,KAAK,KAAK,GAChH,EAAgB,8BAChB,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,YAAW,CACtC,CACF,GAOQ,wBAAb,cAA6C,CAAY,CACvD,OAAyB,eAAiB,0BAK1C,YACE,EACA,EACA,CACA,MAAM,EAAS,EAAgB,oBAAqB,EAAQ"}
|
package/dist/cache.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cn as WithCacheOptions, Sn as CacheInvalidationOptions, Ut as OfficialCacheExtension, bn as CacheSetOptions, vn as CacheDriver, xn as WaitUntilFn, yn as CacheEntry } from "./index-
|
|
1
|
+
import { Cn as WithCacheOptions, Sn as CacheInvalidationOptions, Ut as OfficialCacheExtension, bn as CacheSetOptions, vn as CacheDriver, xn as WaitUntilFn, yn as CacheEntry } from "./index-C_XLSTy2.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/cache/extension.d.ts
|
|
4
4
|
interface CacheExtensionConfig {
|
package/dist/cache.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,E as n,T as r,w as i}from"./validation-Du6j0Q38.mjs";import{b as a,c as o,f as s,g as c,l,m as u,r as d,y as f}from"./controls-BhxRnPYS.mjs";import{b as p}from"./base-vfur-DaU.mjs";import{g as m,p as h}from"./observation-CLp8ylmL.mjs";import{i as g}from"./key-DKaqPb8w.mjs";import{t as _}from"./invariant-DCsftyml.mjs";import{r as v}from"./builder-DkWfNHEV.mjs";import{F as y,St as b,T as x,_ as S,r as C,x as w}from"./geo-point-codec-DUTTtlav.mjs";import{t as T}from"./validation-tgjL_9n8.mjs";import{a as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./driver-ZIbkciaz.mjs";const N=new Set([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),P=new WeakMap;function admitMutationCacheOptions(e){let t=T(k,e);if(t.issues)throw new h(`Invalid mutation cache options: ${t.issues.map(e=>e.message).join(`, `)}`,{cause:b(t)});let n=t.value.invalidate===void 0?void 0:[...t.value.invalidate];n&&Object.freeze(n);let r=Object.freeze({autoInvalidate:t.value.autoInvalidate,...n===void 0?{}:{invalidate:n}});return P.set(r,r),r}function readMutationCacheOptions(e){let t=e?.cache;return r(t)?P.get(t):void 0}function cacheKeyOf(e,t,n){if(t===void 0)return e;if(Object.values(t).every(d))return n===void 0?[e,t]:[e,t,n]}function prepareMutationCacheWriteOutcome(e,t,n,r,i,a){if(o(n))return Object.freeze({extension:`viborm.cache`,failurePolicy:`boundary-owned`,listener:async o=>{try{await D(e,t,r,i,a)}catch(e){throw new h(`Cache invalidation failed after mutation '${n}' on model '${t}'.`,{cause:p(e)?e:Error(`A non-Error value was thrown.`,{cause:e}),meta:{method:`invalidate`,model:t,operation:n,commitCertainty:o.certainty}})}}})}function validateCacheableOperation(e){if(!N.has(e))throw new m(e,[...N])}function createCacheExecutionOptions(e,t,n){let r=T(j,e);if(r.issues)throw new h(`Invalid cache options: ${r.issues.map(e=>e.message).join(`, `)}`,{cause:b(r)});let{bypass:i,key:a,ttl:o,swr:s}=r.value;return{ttlMs:o,swr:resolveSwr(s,o),bypass:i,key:a,waitUntil:t,driverIdentity:n}}function executeCachedResultOperation(e,t,n,r,i,a,o,s){return A(e,t,n,r,i,a,o,s)}async function invalidateManualCache(e,t,n,r){let i=[...t];await D(e,`manual`,Object.freeze({invalidate:i}),n,r)}function resolveSwr(e,t){return e===void 0||e===!1?!1:e===!0?t*2:t+e}var CacheSnapshotFailure=class extends Error{};function failCacheSnapshot(){throw new CacheSnapshotFailure}function readSnapshotArray(e){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return failCacheSnapshot();let t=Reflect.ownKeys(e),n=Reflect.getOwnPropertyDescriptor(e,`length`)?.value;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0||t.length!==n+1||t[n]!==`length`)return failCacheSnapshot();let r=Array(n);for(let i=0;i<n;i+=1){let n=String(i);if(t[i]!==n)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();r[i]=a.value}return r}function readSnapshotRecord(e,t=!1){if(typeof e!=`object`||!e||Array.isArray(e))return failCacheSnapshot();let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!(t&&n===null))return failCacheSnapshot();let r=Reflect.ownKeys(e),i=Array(r.length);for(let t=0;t<r.length;t+=1){let n=r[t];if(typeof n!=`string`)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();i[t]=[n,a.value]}return i}function defineSnapshotProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function enterSnapshotObject(e,t){e.has(t)&&failCacheSnapshot(),e.add(t)}function withSnapshotObject(e,t,n){enterSnapshotObject(e,t);try{return n()}finally{e.delete(t)}}function encodeSnapshotNumber(e){return typeof e!=`number`||!Number.isFinite(e)?failCacheSnapshot():Object.is(e,-0)?`-0`:String(e)}function decodeSnapshotNumber(e){if(typeof e!=`string`)return failCacheSnapshot();let t=Number(e);return!Number.isFinite(t)||encodeSnapshotNumber(t)!==e?failCacheSnapshot():t}function encodeSnapshotCount(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<0?failCacheSnapshot():String(e)}function decodeSnapshotCount(e){let t=decodeSnapshotNumber(e);return!Number.isSafeInteger(t)||t<0?failCacheSnapshot():t}const F=`null`,I=`string`,L=`boolean`,R=`number`,z=`array`,B=`object`;function snapshotJsonValue(e,t){return e===null?[F]:typeof e==`string`?[I,e]:typeof e==`boolean`?[L,e]:typeof e==`number`?[R,encodeSnapshotNumber(e)]:Array.isArray(e)?withSnapshotObject(t,e,()=>[z,readSnapshotArray(e).map(e=>snapshotJsonValue(e,t))]):typeof e==`object`&&e?withSnapshotObject(t,e,()=>[B,readSnapshotRecord(e,!0).map(([e,n])=>[e,snapshotJsonValue(n,t)])]):failCacheSnapshot()}function materializeJsonValue(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r=n[0];return r===F&&n.length===1?null:r===I&&n.length===2&&typeof n[1]==`string`||r===L&&n.length===2&&typeof n[1]==`boolean`?n[1]:r===R&&n.length===2?decodeSnapshotNumber(n[1]):r===z&&n.length===2?materializeJsonArray(n[1],t):r===B&&n.length===2?materializeJsonObject(n[1],t):failCacheSnapshot()})}function materializeJsonArray(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>readSnapshotArray(e).map(e=>materializeJsonValue(e,t)))}function materializeJsonObject(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r={},i=new Set;for(let e of n){if(typeof e!=`object`||!e)return failCacheSnapshot();let n=withSnapshotObject(t,e,()=>readSnapshotArray(e)),a=n[0];if(n.length!==2||typeof a!=`string`||i.has(a))return failCacheSnapshot();i.add(a),defineSnapshotProperty(r,a,materializeJsonValue(n[1],t))}return r})}const V=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?$/;function compileScalarCodec(e,t=!0){let n;if(`enumValues`in e)n=enumCodec(new Set(e.enumValues));else{let t=e[`~`].state;switch(t.type){case`string`:n=stringCodec();break;case`time`:n=timeCodec();break;case`int`:n=integerCodec();break;case`number`:n=numberCodec();break;case`decimal`:n=decimalCodec(t.decimal);break;case`boolean`:n=booleanCodec();break;case`bigint`:n=bigintCodec();break;case`datetime`:n=dateCodec(!1);break;case`date`:n=dateCodec(!0);break;case`json`:n=jsonCodec();break;case`vector`:n=vectorCodec(t.dimension);break;case`blob`:n=bytesCodec();break;case`point`:n=pointCodec();break}}let r=e[`~`].state,i=r.array?arrayCodec(n):n;return t&&r.nullable?nullableCodec(i):i}function taggedRelationCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==2)return failCacheSnapshot();let i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);return!o||a==null?failCacheSnapshot():r.map(([e,t])=>[e,e===`type`?i:o.snapshot(t,n)])})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==2)return failCacheSnapshot();let r=readEncodedEntries(t,n),i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);if(!o||a==null)return failCacheSnapshot();let s={};for(let[e]of r)defineSnapshotProperty(s,e,e===`type`?i:o.materialize(a,n));return s})}}}function recordCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==e.size)return failCacheSnapshot();let i=new Set;return r.map(([t,r])=>{let a=e.get(t);return!a||i.has(t)?failCacheSnapshot():(i.add(t),[t,a.snapshot(r,n)])})})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==e.size)return failCacheSnapshot();let r=readEncodedEntries(t,n),i=new Set,a={};for(let[t,o]of r){let r=e.get(t);if(!r||i.has(t))return failCacheSnapshot();i.add(t),defineSnapshotProperty(a,t,r.materialize(o,n))}return a})}}}function arrayCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>readSnapshotArray(t).map(t=>e.snapshot(t,n))):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>t.map(t=>e.materialize(t,n)))}}}function nullableCodec(e){return{snapshot(t,n){return t===null?null:e.snapshot(t,n)},materialize(t,n){return t===null?null:e.materialize(t,n)}}}function recursiveRelationCodec(e,t){return{snapshot:(n,r)=>walkRecursiveSlot(n,r,e,{read(n){let i={},a=[];for(let[t,r]of readSnapshotRecord(n))t===e.relation?a.push(r):defineSnapshotProperty(i,t,r);return[t.snapshot(i,r),a]},write:(e,t)=>[e,...t]}),materialize:(n,r)=>walkRecursiveSlot(n,r,e,{read(e){let[n,...i]=readSnapshotArray(e);return[t.materialize(n,r),i]},write(t,n){return n.length>0&&defineSnapshotProperty(t,e.relation,n[0]),t}})}}function walkRecursiveSlot(e,t,n,r){let open=(e,t,r,i)=>{let a;return a=n.many?readSnapshotArray(e):e===null?n.optional?[]:failCacheSnapshot():[e],{level:t,occurrences:a,outputs:[],owner:r,node:i,next:0}},i=[open(e,1)],a;for(;i.length>0;){let e=i.at(-1);if(e.next<e.occurrences.length){let a=e.occurrences[e.next];if(e.next+=1,typeof a!=`object`||!a)return failCacheSnapshot();enterSnapshotObject(t,a);let o=v(n.depth,e.level),[s,c]=r.read(a);if(c.length!==(o?1:0))return failCacheSnapshot();if(o){i.push(open(c[0],e.level+1,a,s));continue}t.delete(a),e.outputs.push(r.write(s,c));continue}i.pop();let o=n.many?e.outputs:e.outputs[0]??null;if(e.owner===void 0){a=o;continue}let s=i.at(-1);t.delete(e.owner),s.outputs.push(r.write(e.node,[o]))}return a}function booleanCodec(){return primitiveCodec(e=>typeof e==`boolean`?e:failCacheSnapshot(),e=>typeof e==`boolean`?e:failCacheSnapshot())}function numberCodec(){return primitiveCodec(encodeSnapshotNumber,decodeSnapshotNumber)}function countCodec(){return primitiveCodec(encodeSnapshotCount,decodeSnapshotCount)}function readEncodedEntries(e,t){let n=Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=materializeArray(e[r],t,e=>e.length!==2||typeof e[0]!=`string`?failCacheSnapshot():[e[0],e[1]]);return n}function stringCodec(){return primitiveCodec(e=>typeof e==`string`?e:failCacheSnapshot(),e=>typeof e==`string`?e:failCacheSnapshot())}function timeCodec(){return primitiveCodec(e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot(),e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot())}function enumCodec(e){return primitiveCodec(t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot(),t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot())}function integerCodec(){return primitiveCodec(e=>typeof e!=`number`||!Number.isSafeInteger(e)?failCacheSnapshot():encodeSnapshotNumber(e),e=>{let t=decodeSnapshotNumber(e);return Number.isSafeInteger(t)?t:failCacheSnapshot()})}function decimalCodec(e){return primitiveCodec(t=>e?w(S(t),e)??failCacheSnapshot():failCacheSnapshot(),t=>{if(!e)return failCacheSnapshot();let n=w(t,e);return n!==void 0&&n===t?y(n):failCacheSnapshot()})}function compileWidenedSumCodec(e){let t=e[`~`].state.decimal;return primitiveCodec(e=>t?x(S(e),t.scale)??failCacheSnapshot():failCacheSnapshot(),e=>{if(!t)return failCacheSnapshot();let n=x(e,t.scale);return n!==void 0&&n===e?y(n):failCacheSnapshot()})}function bigintCodec(){return primitiveCodec(e=>typeof e==`bigint`?e.toString():failCacheSnapshot(),e=>{if(typeof e!=`string`)return failCacheSnapshot();try{let t=BigInt(e);return t.toString()===e?t:failCacheSnapshot()}catch{return failCacheSnapshot()}})}function dateCodec(e){return primitiveCodec(t=>{if(!(t instanceof Date)||Object.getPrototypeOf(t)!==Date.prototype||Reflect.ownKeys(t).length!==0)return failCacheSnapshot();let n=Date.prototype.getTime.call(t);if(!Number.isFinite(n))return failCacheSnapshot();let r=Date.prototype.toISOString.call(t);return e&&!r.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():r},t=>{if(typeof t!=`string`)return failCacheSnapshot();let n=new Date(t);return!Number.isFinite(n.getTime())||n.toISOString()!==t||e&&!t.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():n})}function jsonCodec(){return{snapshot:snapshotJsonValue,materialize:materializeJsonValue}}function vectorCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>{let n=readSnapshotArray(t);return e!==void 0&&n.length!==e?failCacheSnapshot():n.map(encodeSnapshotNumber)}):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>e!==void 0&&t.length!==e?failCacheSnapshot():t.map(decodeSnapshotNumber))}}}function bytesCodec(){return{snapshot(e){if(!(e instanceof Uint8Array)||Object.getPrototypeOf(e)!==Uint8Array.prototype||Reflect.ownKeys(e).length!==e.byteLength)return failCacheSnapshot();let t=Array(e.byteLength);for(let n=0;n<e.byteLength;n+=1)t[n]=e[n];return t},materialize(e){let t=readSnapshotArray(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1){let r=t[e];if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)return failCacheSnapshot();n[e]=r}return n}}}function pointCodec(){let e=recordCodec(new Map([[`longitude`,numberCodec()],[`latitude`,numberCodec()]]));return{snapshot(t,n){let r=C(t);return r.issues?failCacheSnapshot():e.snapshot(r.value,n)},materialize(t,n){let r=C(e.materialize(t,n));return r.issues?failCacheSnapshot():r.value}}}function primitiveCodec(e,t){return{snapshot:e,materialize:t}}function materializeArray(e,t,n){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>n(readSnapshotArray(e)))}function cacheCodec(e,t){let n=shapeCodec(e.value,t),r=e.empty===null?nullableCodec(n):n;return Object.freeze({snapshot(e){try{return r.snapshot(e,new WeakSet)}catch(e){throw new h(`The operation result cannot be represented by the cache result codec.`,{cause:e instanceof Error?e:void 0,meta:{method:`snapshot`,operation:t}})}},materialize(e){try{return r.materialize(e,new WeakSet)}catch(e){throw new h(`The cached result snapshot is malformed.`,{cause:e instanceof Error?e:void 0,meta:{method:`materialize`,operation:t}})}}})}function shapeCodec(e,t){switch(e.kind){case`scalar`:return leafCodec(e,t);case`object`:{let n=new Map;for(let[r,i]of Object.entries(e.fields))n.set(r,shapeCodec(i,t));let r=recordCodec(n);return e.nullable===!1?r:nullableCodec(r)}case`collection`:return arrayCodec(shapeCodec(e.row,t));case`variants`:{let n=new Map;for(let[r,i]of Object.entries(e.arms))n.set(r,shapeCodec(e.many&&i.kind===`collection`?i.row:i,t));let r=taggedRelationCodec(n);return e.many?arrayCodec(r):nullableCodec(r)}case`recursive`:return recursiveRelationCodec({relation:e.relation,many:e.many,optional:e.optional,depth:e.recurrence.depth},shapeCodec(e.row,t))}}function leafCodec(e,t){let n=e.scalar,r;if(n)r=e.widened?compileWidenedSumCodec(n):compileScalarCodec(n,!1);else if(e.type===`boolean`)r=booleanCodec();else if(e.type===`int`)r=countCodec();else if(e.type===`number`)r=numberCodec();else throw new _(`Cannot cache a '${e.type}' result for '${t}': its scalar declaration is missing.`);return e.nullable?nullableCodec(r):r}function bindChain(e,t){let n=s(e);n!==void 0&&a(e,Object.freeze({driver:n.driver,version:n.version,waitUntil:n.waitUntil,scope:O(g({version:n.version,dialect:t.dialect,namespace:t.adapter.namespace}))}))}const H=Object.freeze({admitMutationCacheOptions,bindChain,cacheCodec,cacheKeyOf,createCacheExecutionOptions,executeCachedResultOperation,invalidateManualCache,prepareMutationCacheWriteOutcome,readCacheExecutionOutcomes:E,readMutationCacheOptions,validateCacheableOperation});u(H);function configurationCause(e){return p(e)?e:Error(`A non-Error value was thrown.`,{cause:e})}function configurationError(e,t){throw new h(e,{cause:t===void 0?void 0:configurationCause(t)})}function isCacheDriver(e){try{return e instanceof M}catch(e){configurationError(`Cache extension driver capability could not be inspected.`,e)}}function snapshotConfig(e){r(e)||configurationError(`Cache extension configuration must be an object.`);let a;try{a=Reflect.ownKeys(e)}catch(e){configurationError(`Cache extension configuration could not be inspected.`,e)}for(let e of a)(typeof e!=`string`||e!==`driver`&&e!==`version`&&e!==`waitUntil`)&&configurationError(`Cache extension configuration has unknown member "${String(e)}".`);let read=t=>{if(a.includes(t))try{return e[t]}catch(e){configurationError(`Cache extension configuration member "${t}" could not be read.`,e)}},o=read(`driver`),s=read(`version`),c=read(`waitUntil`);return isCacheDriver(o)||configurationError(`Cache extension configuration requires a CacheDriver instance.`),s!==void 0&&!(n(s)||i(s)&&Number.isFinite(s))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),c!==void 0&&!t(c)&&configurationError(`Cache extension configuration "waitUntil" must be a function.`),Object.freeze({driver:o,version:s,waitUntil:c})}function cache(e){let t=snapshotConfig(e),query=({proceed:e})=>e();return f(query,t,H),Object.freeze({name:l,query,controls:c})}export{M as CacheDriver,cache};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r,s as i}from"./value-guards-CK9guf2Z.mjs";import{_ as a,b as o,h as s,l as c,p as l,r as u,u as d,x as f}from"./controls-DXgIn4zh.mjs";import{b as p}from"./base-AdXAoy6l.mjs";import{i as m,t as h}from"./cache-BO57X0TT.mjs";import{i as g}from"./key-BeoOwGr3.mjs";import{i as _}from"./builder-Ycvq3ETg.mjs";import{F as v,T as y,X as b,_ as x,r as S,x as C}from"./geo-point-codec-lhxH42SK.mjs";import{t as w}from"./invariant-BnLYqsHO.mjs";import{t as T}from"./validation-PF9-_nKd.mjs";import{a as E,i as D,n as O,o as k,r as A,s as j,t as M}from"./driver-B19QlFqn.mjs";const N=new Set([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),P=new WeakMap;function admitMutationCacheOptions(e){let t=T(k,e);if(t.issues)throw new h(`Invalid mutation cache options: ${t.issues.map(e=>e.message).join(`, `)}`,{cause:b(t)});let n=t.value.invalidate===void 0?void 0:[...t.value.invalidate];n&&Object.freeze(n);let r=Object.freeze({autoInvalidate:t.value.autoInvalidate,...n===void 0?{}:{invalidate:n}});return P.set(r,r),r}function readMutationCacheOptions(e){let t=e?.cache;return r(t)?P.get(t):void 0}function cacheKeyOf(e,t,n){if(t===void 0)return e;if(Object.values(t).every(u))return n===void 0?[e,t]:[e,t,n]}function prepareMutationCacheWriteOutcome(e,t,n,r,i,a){if(c(n))return Object.freeze({extension:`viborm.cache`,failurePolicy:`boundary-owned`,listener:async o=>{try{await D(e,t,r,i,a)}catch(e){throw new h(`Cache invalidation failed after mutation '${n}' on model '${t}'.`,{cause:p(e),meta:{method:`invalidate`,model:t,operation:n,commitCertainty:o.certainty}})}}})}function validateCacheableOperation(e){if(!N.has(e))throw new m(e,[...N])}function createCacheExecutionOptions(e,t,n){let r=T(j,e);if(r.issues)throw new h(`Invalid cache options: ${r.issues.map(e=>e.message).join(`, `)}`,{cause:b(r)});let{bypass:i,key:a,ttl:o,swr:s}=r.value;return{ttlMs:o,swr:resolveSwr(s,o),bypass:i,key:a,waitUntil:t,driverIdentity:n}}function executeCachedResultOperation(e,t,n,r,i,a,o,s){return A(e,t,n,r,i,a,o,s)}async function invalidateManualCache(e,t,n,r){let i=[...t];await D(e,`manual`,Object.freeze({invalidate:i}),n,r)}function resolveSwr(e,t){return e===void 0||e===!1?!1:e===!0?t*2:t+e}var CacheSnapshotFailure=class extends Error{};function failCacheSnapshot(){throw new CacheSnapshotFailure}function readSnapshotArray(e){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return failCacheSnapshot();let t=Reflect.ownKeys(e),n=Reflect.getOwnPropertyDescriptor(e,`length`)?.value;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0||t.length!==n+1||t[n]!==`length`)return failCacheSnapshot();let r=Array(n);for(let i=0;i<n;i+=1){let n=String(i);if(t[i]!==n)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();r[i]=a.value}return r}function readSnapshotRecord(e,t=!1){if(typeof e!=`object`||!e||Array.isArray(e))return failCacheSnapshot();let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!(t&&n===null))return failCacheSnapshot();let r=Reflect.ownKeys(e),i=Array(r.length);for(let t=0;t<r.length;t+=1){let n=r[t];if(typeof n!=`string`)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();i[t]=[n,a.value]}return i}function defineSnapshotProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function enterSnapshotObject(e,t){e.has(t)&&failCacheSnapshot(),e.add(t)}function withSnapshotObject(e,t,n){enterSnapshotObject(e,t);try{return n()}finally{e.delete(t)}}function encodeSnapshotNumber(e){return typeof e!=`number`||!Number.isFinite(e)?failCacheSnapshot():Object.is(e,-0)?`-0`:String(e)}function decodeSnapshotNumber(e){if(typeof e!=`string`)return failCacheSnapshot();let t=Number(e);return!Number.isFinite(t)||encodeSnapshotNumber(t)!==e?failCacheSnapshot():t}function encodeSnapshotCount(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<0?failCacheSnapshot():String(e)}function decodeSnapshotCount(e){let t=decodeSnapshotNumber(e);return!Number.isSafeInteger(t)||t<0?failCacheSnapshot():t}const F=`null`,I=`string`,L=`boolean`,R=`number`,z=`array`,B=`object`;function snapshotJsonValue(e,t){return e===null?[F]:typeof e==`string`?[I,e]:typeof e==`boolean`?[L,e]:typeof e==`number`?[R,encodeSnapshotNumber(e)]:Array.isArray(e)?withSnapshotObject(t,e,()=>[z,readSnapshotArray(e).map(e=>snapshotJsonValue(e,t))]):typeof e==`object`&&e?withSnapshotObject(t,e,()=>[B,readSnapshotRecord(e,!0).map(([e,n])=>[e,snapshotJsonValue(n,t)])]):failCacheSnapshot()}function materializeJsonValue(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r=n[0];return r===F&&n.length===1?null:r===I&&n.length===2&&typeof n[1]==`string`||r===L&&n.length===2&&typeof n[1]==`boolean`?n[1]:r===R&&n.length===2?decodeSnapshotNumber(n[1]):r===z&&n.length===2?materializeJsonArray(n[1],t):r===B&&n.length===2?materializeJsonObject(n[1],t):failCacheSnapshot()})}function materializeJsonArray(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>readSnapshotArray(e).map(e=>materializeJsonValue(e,t)))}function materializeJsonObject(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r={},i=new Set;for(let e of n){if(typeof e!=`object`||!e)return failCacheSnapshot();let n=withSnapshotObject(t,e,()=>readSnapshotArray(e)),a=n[0];if(n.length!==2||typeof a!=`string`||i.has(a))return failCacheSnapshot();i.add(a),defineSnapshotProperty(r,a,materializeJsonValue(n[1],t))}return r})}const V=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?$/;function compileScalarCodec(e,t=!0){let n;if(`enumValues`in e)n=enumCodec(new Set(e.enumValues));else{let t=e[`~`].state;switch(t.type){case`string`:n=stringCodec();break;case`time`:n=timeCodec();break;case`int`:n=integerCodec();break;case`number`:n=numberCodec();break;case`decimal`:n=decimalCodec(t.decimal);break;case`boolean`:n=booleanCodec();break;case`bigint`:n=bigintCodec();break;case`datetime`:n=dateCodec(!1);break;case`date`:n=dateCodec(!0);break;case`json`:n=jsonCodec();break;case`vector`:n=vectorCodec(t.dimension);break;case`blob`:n=bytesCodec();break;case`point`:n=pointCodec();break}}let r=e[`~`].state,i=r.array?arrayCodec(n):n;return t&&r.nullable?nullableCodec(i):i}function taggedRelationCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==2)return failCacheSnapshot();let i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);return!o||a==null?failCacheSnapshot():r.map(([e,t])=>[e,e===`type`?i:o.snapshot(t,n)])})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==2)return failCacheSnapshot();let r=readEncodedEntries(t,n),i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);if(!o||a==null)return failCacheSnapshot();let s={};for(let[e]of r)defineSnapshotProperty(s,e,e===`type`?i:o.materialize(a,n));return s})}}}function recordCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==e.size)return failCacheSnapshot();let i=new Set;return r.map(([t,r])=>{let a=e.get(t);return!a||i.has(t)?failCacheSnapshot():(i.add(t),[t,a.snapshot(r,n)])})})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==e.size)return failCacheSnapshot();let r=readEncodedEntries(t,n),i=new Set,a={};for(let[t,o]of r){let r=e.get(t);if(!r||i.has(t))return failCacheSnapshot();i.add(t),defineSnapshotProperty(a,t,r.materialize(o,n))}return a})}}}function arrayCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>readSnapshotArray(t).map(t=>e.snapshot(t,n))):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>t.map(t=>e.materialize(t,n)))}}}function nullableCodec(e){return{snapshot(t,n){return t===null?null:e.snapshot(t,n)},materialize(t,n){return t===null?null:e.materialize(t,n)}}}function recursiveRelationCodec(e,t){return{snapshot:(n,r)=>walkRecursiveSlot(n,r,e,{read(n){let i={},a=[];for(let[t,r]of readSnapshotRecord(n))t===e.relation?a.push(r):defineSnapshotProperty(i,t,r);return[t.snapshot(i,r),a]},write:(e,t)=>[e,...t]}),materialize:(n,r)=>walkRecursiveSlot(n,r,e,{read(e){let[n,...i]=readSnapshotArray(e);return[t.materialize(n,r),i]},write(t,n){return n.length>0&&defineSnapshotProperty(t,e.relation,n[0]),t}})}}function walkRecursiveSlot(e,t,n,r){let open=(e,t,r,i)=>{let a;return a=n.many?readSnapshotArray(e):e===null?n.optional?[]:failCacheSnapshot():[e],{level:t,occurrences:a,outputs:[],owner:r,node:i,next:0}},i=[open(e,1)],a;for(;i.length>0;){let e=i.at(-1);if(e.next<e.occurrences.length){let a=e.occurrences[e.next];if(e.next+=1,typeof a!=`object`||!a)return failCacheSnapshot();enterSnapshotObject(t,a);let o=_(n.depth,e.level),[s,c]=r.read(a);if(c.length!==(o?1:0))return failCacheSnapshot();if(o){i.push(open(c[0],e.level+1,a,s));continue}t.delete(a),e.outputs.push(r.write(s,c));continue}i.pop();let o=n.many?e.outputs:e.outputs[0]??null;if(e.owner===void 0){a=o;continue}let s=i.at(-1);t.delete(e.owner),s.outputs.push(r.write(e.node,[o]))}return a}function booleanCodec(){return primitiveCodec(e=>typeof e==`boolean`?e:failCacheSnapshot(),e=>typeof e==`boolean`?e:failCacheSnapshot())}function numberCodec(){return primitiveCodec(encodeSnapshotNumber,decodeSnapshotNumber)}function countCodec(){return primitiveCodec(encodeSnapshotCount,decodeSnapshotCount)}function readEncodedEntries(e,t){let n=Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=materializeArray(e[r],t,e=>e.length!==2||typeof e[0]!=`string`?failCacheSnapshot():[e[0],e[1]]);return n}function stringCodec(){return primitiveCodec(e=>typeof e==`string`?e:failCacheSnapshot(),e=>typeof e==`string`?e:failCacheSnapshot())}function timeCodec(){return primitiveCodec(e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot(),e=>typeof e==`string`&&V.test(e)?e:failCacheSnapshot())}function enumCodec(e){return primitiveCodec(t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot(),t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot())}function integerCodec(){return primitiveCodec(e=>typeof e!=`number`||!Number.isSafeInteger(e)?failCacheSnapshot():encodeSnapshotNumber(e),e=>{let t=decodeSnapshotNumber(e);return Number.isSafeInteger(t)?t:failCacheSnapshot()})}function decimalCodec(e){return primitiveCodec(t=>e?C(x(t),e)??failCacheSnapshot():failCacheSnapshot(),t=>{if(!e)return failCacheSnapshot();let n=C(t,e);return n!==void 0&&n===t?v(n):failCacheSnapshot()})}const H=new Map([[`Infinity`,1/0],[`-Infinity`,-1/0]]);function compileWidenedSumCodec(e){let{type:t}=e[`~`].state;if(t===`bigint`)return bigintCodec();if(t===`number`||t===`int`)return primitiveCodec(e=>e===1/0||e===-1/0?String(e):encodeSnapshotNumber(e),e=>H.get(e)??decodeSnapshotNumber(e));let n=e[`~`].state.decimal;return primitiveCodec(e=>n?y(x(e),n.scale)??failCacheSnapshot():failCacheSnapshot(),e=>{if(!n)return failCacheSnapshot();let t=y(e,n.scale);return t!==void 0&&t===e?v(t):failCacheSnapshot()})}function bigintCodec(){return primitiveCodec(e=>typeof e==`bigint`?e.toString():failCacheSnapshot(),e=>{if(typeof e!=`string`)return failCacheSnapshot();try{let t=BigInt(e);return t.toString()===e?t:failCacheSnapshot()}catch{return failCacheSnapshot()}})}function dateCodec(e){return primitiveCodec(t=>{if(!(t instanceof Date)||Object.getPrototypeOf(t)!==Date.prototype||Reflect.ownKeys(t).length!==0)return failCacheSnapshot();let n=Date.prototype.getTime.call(t);if(!Number.isFinite(n))return failCacheSnapshot();let r=Date.prototype.toISOString.call(t);return e&&!r.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():r},t=>{if(typeof t!=`string`)return failCacheSnapshot();let n=new Date(t);return!Number.isFinite(n.getTime())||n.toISOString()!==t||e&&!t.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():n})}function jsonCodec(){return{snapshot:snapshotJsonValue,materialize:materializeJsonValue}}function vectorCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>{let n=readSnapshotArray(t);return e!==void 0&&n.length!==e?failCacheSnapshot():n.map(encodeSnapshotNumber)}):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>e!==void 0&&t.length!==e?failCacheSnapshot():t.map(decodeSnapshotNumber))}}}function bytesCodec(){return{snapshot(e){if(!(e instanceof Uint8Array)||Object.getPrototypeOf(e)!==Uint8Array.prototype||Reflect.ownKeys(e).length!==e.byteLength)return failCacheSnapshot();let t=Array(e.byteLength);for(let n=0;n<e.byteLength;n+=1)t[n]=e[n];return t},materialize(e){let t=readSnapshotArray(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1){let r=t[e];if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)return failCacheSnapshot();n[e]=r}return n}}}function pointCodec(){let e=recordCodec(new Map([[`longitude`,numberCodec()],[`latitude`,numberCodec()]]));return{snapshot(t,n){let r=S(t);return r.issues?failCacheSnapshot():e.snapshot(r.value,n)},materialize(t,n){let r=S(e.materialize(t,n));return r.issues?failCacheSnapshot():r.value}}}function primitiveCodec(e,t){return{snapshot:e,materialize:t}}function materializeArray(e,t,n){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>n(readSnapshotArray(e)))}function cacheCodec(e,t){let n=shapeCodec(e.value,t),r=e.empty===null?nullableCodec(n):n;return Object.freeze({snapshot(e){try{return r.snapshot(e,new WeakSet)}catch(e){throw new h(`The operation result cannot be represented by the cache result codec.`,{cause:e instanceof Error?e:void 0,meta:{method:`snapshot`,operation:t}})}},materialize(e){try{return r.materialize(e,new WeakSet)}catch(e){throw new h(`The cached result snapshot is malformed.`,{cause:e instanceof Error?e:void 0,meta:{method:`materialize`,operation:t}})}}})}function shapeCodec(e,t){switch(e.kind){case`scalar`:return leafCodec(e,t);case`object`:{let n=new Map;for(let[r,i]of Object.entries(e.fields))n.set(r,shapeCodec(i,t));let r=recordCodec(n);return e.nullable===!1?r:nullableCodec(r)}case`collection`:return arrayCodec(shapeCodec(e.row,t));case`variants`:{let n=new Map;for(let[r,i]of Object.entries(e.arms))n.set(r,shapeCodec(e.many&&i.kind===`collection`?i.row:i,t));let r=taggedRelationCodec(n);return e.many?arrayCodec(r):nullableCodec(r)}case`recursive`:return recursiveRelationCodec({relation:e.relation,many:e.many,optional:e.optional,depth:e.recurrence.depth},shapeCodec(e.row,t))}}function leafCodec(e,t){let n=e.scalar,r;if(n)r=e.widened?compileWidenedSumCodec(n):compileScalarCodec(n,!1);else if(e.type===`boolean`)r=booleanCodec();else if(e.type===`int`)r=countCodec();else if(e.type===`number`)r=numberCodec();else throw new w(`Cannot cache a '${e.type}' result for '${t}': its scalar declaration is missing.`);return e.nullable?nullableCodec(r):r}function bindChain(e,t){let n=l(e);n!==void 0&&f(e,Object.freeze({driver:n.driver,version:n.version,waitUntil:n.waitUntil,scope:O(g({version:n.version,dialect:t.dialect,namespace:t.adapter.namespace}))}))}const U=Object.freeze({admitMutationCacheOptions,bindChain,cacheCodec,cacheKeyOf,createCacheExecutionOptions,executeCachedResultOperation,invalidateManualCache,prepareMutationCacheWriteOutcome,readCacheExecutionOutcomes:E,readMutationCacheOptions,validateCacheableOperation});s(U);function configurationError(e,t){throw new h(e,{cause:t===void 0?void 0:p(t)})}function isCacheDriver(e){try{return e instanceof M}catch(e){configurationError(`Cache extension driver capability could not be inspected.`,e)}}function snapshotConfig(e){r(e)||configurationError(`Cache extension configuration must be an object.`);let a;try{a=Reflect.ownKeys(e)}catch(e){configurationError(`Cache extension configuration could not be inspected.`,e)}for(let e of a)(typeof e!=`string`||e!==`driver`&&e!==`version`&&e!==`waitUntil`)&&configurationError(`Cache extension configuration has unknown member "${String(e)}".`);let read=t=>{if(a.includes(t))try{return e[t]}catch(e){configurationError(`Cache extension configuration member "${t}" could not be read.`,e)}},o=read(`driver`),s=read(`version`),c=read(`waitUntil`);return isCacheDriver(o)||configurationError(`Cache extension configuration requires a CacheDriver instance.`),s!==void 0&&!(i(s)||t(s)&&Number.isFinite(s))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),c!==void 0&&!n(c)&&configurationError(`Cache extension configuration "waitUntil" must be a function.`),Object.freeze({driver:o,version:s,waitUntil:c})}function cache(e){let t=snapshotConfig(e),query=({proceed:e})=>e();return o(query,t,U),Object.freeze({name:d,query,controls:a})}export{M as CacheDriver,cache};
|
|
2
2
|
//# sourceMappingURL=cache.mjs.map
|