viborm 1.3.1 → 1.3.3

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.
Files changed (206) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-CWLEmon2.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DGJPz8-G.mjs.map} +1 -1
  7. package/dist/{bind-parameter-capacity-qfEejeOX.mjs → bind-parameter-capacity-DiwRmZ1h.mjs} +2 -2
  8. package/dist/{bind-parameter-capacity-qfEejeOX.mjs.map → bind-parameter-capacity-DiwRmZ1h.mjs.map} +1 -1
  9. package/dist/{builder-s1ySUuMb.mjs → builder-D6Ug-zjM.mjs} +2 -2
  10. package/dist/{builder-s1ySUuMb.mjs.map → builder-D6Ug-zjM.mjs.map} +1 -1
  11. package/dist/bun-sql.d.mts +1 -1
  12. package/dist/bun-sql.mjs +1 -1
  13. package/dist/bun-sqlite.d.mts +1 -1
  14. package/dist/bun-sqlite.mjs +1 -1
  15. package/dist/cache/cloudflare-kv.d.mts +1 -1
  16. package/dist/cache/cloudflare-kv.mjs +1 -1
  17. package/dist/cache/memory.d.mts +1 -1
  18. package/dist/cache/memory.mjs +1 -1
  19. package/dist/cache.d.mts +1 -1
  20. package/dist/cache.mjs +1 -1
  21. package/dist/cache.mjs.map +1 -1
  22. package/dist/chain-B5IbqLGi.mjs +2 -0
  23. package/dist/chain-B5IbqLGi.mjs.map +1 -0
  24. package/dist/cli.mjs +1 -1
  25. package/dist/client-BmcHzDBa.mjs +2 -0
  26. package/dist/client-BmcHzDBa.mjs.map +1 -0
  27. package/dist/{client-70MrTq1E.d.mts → client-DR0vYetv.d.mts} +2 -2
  28. package/dist/{client-BgJ7Faln.mjs → client-DjtWangN.mjs} +3 -3
  29. package/dist/{client-BgJ7Faln.mjs.map → client-DjtWangN.mjs.map} +1 -1
  30. package/dist/client.d.mts +1 -1
  31. package/dist/client.mjs +1 -1
  32. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  33. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  34. package/dist/config.d.mts +1 -1
  35. package/dist/config.mjs +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/datetime-physical-codec-qKxFtI3B.mjs +2 -0
  39. package/dist/datetime-physical-codec-qKxFtI3B.mjs.map +1 -0
  40. package/dist/{driver-vn-9CN0y.mjs → driver-BvP7eW0A.mjs} +2 -2
  41. package/dist/{driver-vn-9CN0y.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
  42. package/dist/{driver-B9fIori_.mjs → driver-Bzc0GCQ4.mjs} +2 -2
  43. package/dist/{driver-B9fIori_.mjs.map → driver-Bzc0GCQ4.mjs.map} +1 -1
  44. package/dist/driver.d.mts +1 -1
  45. package/dist/driver.mjs +1 -1
  46. package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
  47. package/dist/error-mapping-6op318w6.mjs.map +1 -0
  48. package/dist/every-WUr3mlvg.mjs +2 -0
  49. package/dist/{every-CcpKWCVo.mjs.map → every-WUr3mlvg.mjs.map} +1 -1
  50. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  51. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  52. package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
  53. package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
  54. package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
  55. package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
  56. package/dist/{hydration-BsPZI4jE.mjs → hydration-BflrXEIQ.mjs} +2 -2
  57. package/dist/{hydration-BsPZI4jE.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
  58. package/dist/{identifier-conversion-BneQiLxQ.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
  59. package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
  60. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  61. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  62. package/dist/{index-VsM29vYN.d.mts → index-B_jh2oaQ.d.mts} +38 -11
  63. package/dist/index.d.mts +2 -2
  64. package/dist/index.mjs +1 -1
  65. package/dist/instrumentation.d.mts +1 -1
  66. package/dist/instrumentation.mjs +1 -1
  67. package/dist/{key-D9LtHxVK.mjs → key-B89Z4vxn.mjs} +2 -2
  68. package/dist/{key-D9LtHxVK.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
  69. package/dist/{libsql-BlSBYwd_.mjs → libsql-C8dn4id0.mjs} +2 -2
  70. package/dist/{libsql-BlSBYwd_.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
  71. package/dist/libsql.d.mts +1 -1
  72. package/dist/libsql.mjs +1 -1
  73. package/dist/{memory-C0k-_S_n.mjs → memory-B7CcHS6I.mjs} +2 -2
  74. package/dist/{memory-C0k-_S_n.mjs.map → memory-B7CcHS6I.mjs.map} +1 -1
  75. package/dist/migrations/mysql.d.mts +4 -4
  76. package/dist/migrations/mysql.mjs +1 -1
  77. package/dist/migrations/postgres.d.mts +4 -4
  78. package/dist/migrations/postgres.mjs +1 -1
  79. package/dist/migrations/sqlite.d.mts +4 -4
  80. package/dist/migrations/sqlite.mjs +1 -1
  81. package/dist/migrations/storage/durable-object.mjs +1 -1
  82. package/dist/migrations/storage/fs.mjs +1 -1
  83. package/dist/migrations/storage/r2.mjs +1 -1
  84. package/dist/migrations/tenant.d.mts +2 -2
  85. package/dist/migrations/tenant.mjs +1 -1
  86. package/dist/migrations.d.mts +4 -4
  87. package/dist/migrations.mjs +1 -1
  88. package/dist/mysql-adapter-ABpgFB2N.mjs +2 -0
  89. package/dist/mysql-adapter-ABpgFB2N.mjs.map +1 -0
  90. package/dist/{mysql-DOLHwIM_.mjs → mysql-mUmhH9Cf.mjs} +2 -2
  91. package/dist/{mysql-DOLHwIM_.mjs.map → mysql-mUmhH9Cf.mjs.map} +1 -1
  92. package/dist/mysql2.d.mts +1 -1
  93. package/dist/mysql2.mjs +1 -1
  94. package/dist/neon-http.d.mts +1 -1
  95. package/dist/neon-http.mjs +1 -1
  96. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  97. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  98. package/dist/{object-store-D9mvOHP4.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
  99. package/dist/permissions.d.mts +2 -2
  100. package/dist/permissions.mjs +1 -1
  101. package/dist/permissions.mjs.map +1 -1
  102. package/dist/pg.d.mts +1 -1
  103. package/dist/pg.mjs +1 -1
  104. package/dist/pglite.d.mts +1 -1
  105. package/dist/pglite.mjs +1 -1
  106. package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
  107. package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
  108. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-C79aDzOg.mjs} +2 -2
  109. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-C79aDzOg.mjs.map} +1 -1
  110. package/dist/planetscale.d.mts +1 -1
  111. package/dist/planetscale.mjs +1 -1
  112. package/dist/{planner-C1NzLBge.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
  113. package/dist/{postgres-DQVSTqVm.mjs → postgres-BACQ_wqF.mjs} +2 -2
  114. package/dist/{postgres-DQVSTqVm.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
  115. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
  116. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-Ci07rgh_.mjs.map} +1 -1
  117. package/dist/postgres-adapter-DaMvNOkx.mjs +2 -0
  118. package/dist/postgres-adapter-DaMvNOkx.mjs.map +1 -0
  119. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-D403cLyA.mjs} +2 -2
  120. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-D403cLyA.mjs.map} +1 -1
  121. package/dist/postgres.d.mts +1 -1
  122. package/dist/postgres.mjs +1 -1
  123. package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-DSv2tYFr.mjs} +2 -2
  124. package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-DSv2tYFr.mjs.map} +1 -1
  125. package/dist/result-shape-BKydBCsR.mjs +2 -0
  126. package/dist/result-shape-BKydBCsR.mjs.map +1 -0
  127. package/dist/rows-v1VuwOTa.mjs +2 -0
  128. package/dist/rows-v1VuwOTa.mjs.map +1 -0
  129. package/dist/{scalar-CpEwuJvn.mjs → scalar-Cm7nMFmO.mjs} +2 -2
  130. package/dist/{scalar-CpEwuJvn.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
  131. package/dist/schema/json.d.mts +1 -1
  132. package/dist/schema/json.mjs +1 -1
  133. package/dist/{schema-BnzGHn7k.mjs → schema-D3-ScVH6.mjs} +2 -2
  134. package/dist/{schema-BnzGHn7k.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
  135. package/dist/{schema-introspection-DZsdP6bi.mjs → schema-introspection-TdJrSaKd.mjs} +3 -3
  136. package/dist/{schema-introspection-DZsdP6bi.mjs.map → schema-introspection-TdJrSaKd.mjs.map} +1 -1
  137. package/dist/schema.d.mts +1 -1
  138. package/dist/schema.mjs +1 -1
  139. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
  140. package/dist/select-assembly-uZfvbYjz.mjs.map +1 -0
  141. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  142. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  143. package/dist/sha256-CEYo7k7R.mjs +2 -0
  144. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  145. package/dist/soft-delete.d.mts +1 -1
  146. package/dist/sql-BvHwL73I.mjs +2 -0
  147. package/dist/sql-BvHwL73I.mjs.map +1 -0
  148. package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
  149. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  150. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  151. package/dist/sql.d.mts +1 -1
  152. package/dist/sql.mjs +1 -1
  153. package/dist/sqlite-adapter-DPc9T6Lh.mjs +2 -0
  154. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +1 -0
  155. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
  156. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-BvSlEs5W.mjs.map} +1 -1
  157. package/dist/sqlite3.d.mts +1 -1
  158. package/dist/sqlite3.mjs +1 -1
  159. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
  160. package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
  161. package/dist/{to-many-C5RMZl05.mjs → to-many-Btc9X5Ga.mjs} +2 -2
  162. package/dist/{to-many-C5RMZl05.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
  163. package/dist/{utils-C3r4gO3Y.mjs → utils-Qr8ug94X.mjs} +2 -2
  164. package/dist/{utils-C3r4gO3Y.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
  165. package/dist/v-514RME2X.mjs +2 -0
  166. package/dist/v-514RME2X.mjs.map +1 -0
  167. package/dist/{validation-BQtO6srU.mjs → validation-CPnrLcjW.mjs} +2 -2
  168. package/dist/{validation-BQtO6srU.mjs.map → validation-CPnrLcjW.mjs.map} +1 -1
  169. package/dist/validation-gwZYm3Yn.mjs +2 -0
  170. package/dist/validation-gwZYm3Yn.mjs.map +1 -0
  171. package/dist/validation.d.mts +1 -1
  172. package/dist/validation.mjs +1 -1
  173. package/dist/{validator-CVSrhn0u.mjs → validator-CQOw7G3q.mjs} +2 -2
  174. package/dist/{validator-CVSrhn0u.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
  175. package/dist/version-0RVYpih5.mjs +2 -0
  176. package/dist/{version-C8QLCt1n.mjs.map → version-0RVYpih5.mjs.map} +1 -1
  177. package/package.json +15 -15
  178. package/dist/chain-7qiFSE8J.mjs +0 -2
  179. package/dist/chain-7qiFSE8J.mjs.map +0 -1
  180. package/dist/client-6YgGlXzN.mjs +0 -2
  181. package/dist/client-6YgGlXzN.mjs.map +0 -1
  182. package/dist/controls-KQ85SWfT.mjs +0 -2
  183. package/dist/controls-KQ85SWfT.mjs.map +0 -1
  184. package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
  185. package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
  186. package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
  187. package/dist/every-CcpKWCVo.mjs +0 -2
  188. package/dist/identity-oQvIe7u8.mjs +0 -2
  189. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  190. package/dist/mysql-adapter-C6c5govr.mjs +0 -2
  191. package/dist/mysql-adapter-C6c5govr.mjs.map +0 -1
  192. package/dist/postgres-adapter-CxEit2-v.mjs +0 -2
  193. package/dist/postgres-adapter-CxEit2-v.mjs.map +0 -1
  194. package/dist/result-shape-B6yWtnx_.mjs +0 -2
  195. package/dist/result-shape-B6yWtnx_.mjs.map +0 -1
  196. package/dist/select-assembly-CkGe2ABs.mjs.map +0 -1
  197. package/dist/sql-Bhxq9arK.mjs +0 -2
  198. package/dist/sql-Bhxq9arK.mjs.map +0 -1
  199. package/dist/sqlite-adapter-BXAJy3mI.mjs +0 -2
  200. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +0 -1
  201. package/dist/standard-sql-CoGqv-iX.mjs.map +0 -1
  202. package/dist/v-DtLdBQYg.mjs +0 -2
  203. package/dist/v-DtLdBQYg.mjs.map +0 -1
  204. package/dist/validation-BamBwne9.mjs +0 -2
  205. package/dist/validation-BamBwne9.mjs.map +0 -1
  206. package/dist/version-C8QLCt1n.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as Schema, Bt as CountResultType, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Ht as InferSelectInclude, I as Links, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Qt as StatementHandler, Rt as AggregateResultType, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Ut as defaultOmit, Vt as GroupByResultType, Wn as IndexDefinition, Xt as defineExtension, Y as VibSchema, Yt as ClientExtension, Zt as StatementContext, _ as ObservationCompletion, _n as UnwrapPendingOperation, dr as ObjectSchema, gn as PendingOperation, in as ExtensionResultConsumerState, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as ExtensionCacheState, on as RawOperation, qt as PlacedControl, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation, zt as BatchPayload } from "./index-VsM29vYN.mjs";
1
+ import { A as Schema, Bt as CountResultType, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Ht as InferSelectInclude, I as Links, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Qt as StatementHandler, Rt as AggregateResultType, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Ut as defaultOmit, Vt as GroupByResultType, Wn as IndexDefinition, Xt as defineExtension, Y as VibSchema, Yt as ClientExtension, Zt as StatementContext, _ as ObservationCompletion, _n as UnwrapPendingOperation, dr as ObjectSchema, gn as PendingOperation, in as ExtensionResultConsumerState, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as ExtensionCacheState, on as RawOperation, qt as PlacedControl, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation, zt as BatchPayload } from "./index-B_jh2oaQ.mjs";
2
2
  export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type ClientTypeState, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- import{d as e,o as t}from"./chain-7qiFSE8J.mjs";import{d as n,m as r}from"./result-shape-B6yWtnx_.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-DZsdP6bi.mjs";export{n as PendingOperation,e as defaultOmit,t as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
1
+ import{a as e,s as t}from"./chain-B5IbqLGi.mjs";import{d as n,m as r}from"./result-shape-BKydBCsR.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-TdJrSaKd.mjs";export{n as PendingOperation,t as defaultOmit,e as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";const t={now:()=>Date.now(),setTimeout(e,t){let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>{typeof n.unref==`function`&&n.unref()}}}};export{t};
2
- //# sourceMappingURL=clock-C24RcpwO.mjs.map
2
+ //# sourceMappingURL=clock-YTLtjLFS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"clock-C24RcpwO.mjs","names":[],"sources":["../src/clock.ts"],"sourcesContent":["/**\n * The time seam.\n *\n * Two subsystems decide things by reading the wall clock and arming timers:\n * cache freshness (TTL, and the stale window SWR serves from) and the\n * transaction `timeout` / `maxWait` bounds. Both are behavior worth testing,\n * and testing either through the host clock means sleeping — which buys a slow\n * suite and a timing race, not a proof.\n *\n * So both take their time from a `Clock`. The default is the host's own, and\n * nothing here is public API: the override exists so a test can advance time\n * instead of waiting for it. Driver-internal timers are deliberately out of\n * scope — they belong to the database client, not to us.\n */\n\n/**\n * A timer armed by a `Clock`. The handle owns its own cancellation, so a call\n * site never reaches for a host timer function to undo what a clock started.\n */\nexport interface ClockTimer {\n /** Cancel the pending callback. Safe to call after it has already fired. */\n cancel(): void;\n /**\n * Release the host's hold on the event loop, where the host has one to\n * release. Node timers do; a virtual clock has nothing to release and says\n * so by omitting this.\n */\n unref?(): void;\n}\n\n/** The reading of time and the arming of timers, as one injectable thing. */\nexport interface Clock {\n /** Milliseconds since the epoch, exactly as `Date.now()` reports them. */\n now(): number;\n /** Arm `callback` to run `ms` from now. Cancel through the returned handle. */\n setTimeout(callback: () => void, ms: number): ClockTimer;\n}\n\n/** The host clock: `Date.now` and the global timer functions. The default. */\nexport const systemClock: Clock = {\n now: () => Date.now(),\n setTimeout(callback: () => void, ms: number): ClockTimer {\n const timer = setTimeout(callback, ms);\n return {\n cancel: () => clearTimeout(timer),\n // Hosts that are not Node (browsers, some edge runtimes) hand back a\n // number with no `unref`. Asking is cheaper than assuming.\n unref: () => {\n if (typeof timer.unref === \"function\") timer.unref();\n },\n };\n },\n};\n"],"mappings":"yCAuCA,MAAa,EAAqB,CAChC,QAAW,KAAK,KAAK,CACrB,WAAW,EAAsB,EAAwB,CACvD,IAAM,EAAQ,WAAW,EAAU,EAAG,CACtC,MAAO,CACL,WAAc,aAAa,EAAM,CAGjC,UAAa,CACP,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,EAEvD,EAEJ"}
1
+ {"version":3,"file":"clock-YTLtjLFS.mjs","names":[],"sources":["../src/clock.ts"],"sourcesContent":["/**\n * The time seam.\n *\n * Two subsystems decide things by reading the wall clock and arming timers:\n * cache freshness (TTL, and the stale window SWR serves from) and the\n * transaction `timeout` / `maxWait` bounds. Both are behavior worth testing,\n * and testing either through the host clock means sleeping — which buys a slow\n * suite and a timing race, not a proof.\n *\n * So both take their time from a `Clock`. The default is the host's own, and\n * nothing here is public API: the override exists so a test can advance time\n * instead of waiting for it. Driver-internal timers are deliberately out of\n * scope — they belong to the database client, not to us.\n */\n\n/**\n * A timer armed by a `Clock`. The handle owns its own cancellation, so a call\n * site never reaches for a host timer function to undo what a clock started.\n */\nexport interface ClockTimer {\n /** Cancel the pending callback. Safe to call after it has already fired. */\n cancel(): void;\n /**\n * Release the host's hold on the event loop, where the host has one to\n * release. Node timers do; a virtual clock has nothing to release and says\n * so by omitting this.\n */\n unref?(): void;\n}\n\n/** The reading of time and the arming of timers, as one injectable thing. */\nexport interface Clock {\n /** Milliseconds since the epoch, exactly as `Date.now()` reports them. */\n now(): number;\n /** Arm `callback` to run `ms` from now. Cancel through the returned handle. */\n setTimeout(callback: () => void, ms: number): ClockTimer;\n}\n\n/** The host clock: `Date.now` and the global timer functions. The default. */\nexport const systemClock: Clock = {\n now: () => Date.now(),\n setTimeout(callback: () => void, ms: number): ClockTimer {\n const timer = setTimeout(callback, ms);\n return {\n cancel: () => clearTimeout(timer),\n // Hosts that are not Node (browsers, some edge runtimes) hand back a\n // number with no `unref`. Asking is cheaper than assuming.\n unref: () => {\n if (typeof timer.unref === \"function\") timer.unref();\n },\n };\n },\n};\n"],"mappings":"yCAuCA,MAAa,EAAqB,CAChC,QAAW,KAAK,KAAK,CACrB,WAAW,EAAsB,EAAwB,CACvD,IAAM,EAAQ,WAAW,EAAU,EAAG,CACtC,MAAO,CACL,WAAc,aAAa,EAAM,CAGjC,UAAa,CACP,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,EAEvD,EAEJ"}
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-C1NzLBge.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-DHZG9Vy7.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-Dw0FR78e.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/config.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./utils-C3r4gO3Y.mjs";export{e as defineConfig};
1
+ import{t as e}from"./utils-Qr8ug94X.mjs";export{e as defineConfig};
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
1
+ import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-B_jh2oaQ.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/d1.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-qfEejeOX.mjs";import{m as r}from"./error-mapping-C9WgitPi.mjs";import{p as i}from"./validation-BamBwne9.mjs";import{a,n as o,r as s}from"./client-6YgGlXzN.mjs";import{c,t as l}from"./driver-B9fIori_.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-D_cypcyW.mjs";import{t as p}from"./sql-statement-tokens-CFi1y3bK.mjs";import{t as m}from"./sqlite-adapter-BXAJy3mI.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-DiwRmZ1h.mjs";import{m as r}from"./error-mapping-6op318w6.mjs";import{p as i}from"./validation-gwZYm3Yn.mjs";import{a,n as o,r as s}from"./client-BmcHzDBa.mjs";import{c,t as l}from"./driver-Bzc0GCQ4.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-BvSlEs5W.mjs";import{t as p}from"./sql-statement-tokens-BW7Q-rF-.mjs";import{t as m}from"./sqlite-adapter-DPc9T6Lh.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
2
2
  //# sourceMappingURL=d1.mjs.map
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-D95uXgDF.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function digitsAt(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function decodeCanonicalTimestamp(e){if(e.length!==24||e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||e.charCodeAt(10)!==84||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58||e.charCodeAt(19)!==46||e.charCodeAt(23)!==90)return!1;let t=digitsAt(e,0,4),n=digitsAt(e,5,2),o=digitsAt(e,8,2),s=digitsAt(e,11,2),c=digitsAt(e,14,2),l=digitsAt(e,17,2),u=digitsAt(e,20,3);if(t<100||n<0||o<0||s<0||c<0||l<0||u<0)return!1;if(!(a(t,n,o)&&r(s,c,l)))return;let d=Date.UTC(t,n-1,o,s,c,l,u);return i(d)?new Date(d):void 0}function decodeProviderTimestamp(e){let t=decodeCanonicalTimestamp(e);if(t!==!1)return t;let n=c.exec(e);if(!n)return;let o=n[13]?1-Number(n[1]):Number(n[1]),s=Number(n[2]),l=Number(n[3]),u=Number(n[4]),d=Number(n[5]),f=Number(n[6]),p=Number(n[10]??0),m=Number(n[11]??0),h=Number(n[12]??0);if(!(a(o,s,l)&&r(u,d,f))||p>23||m>59||h>59)return;let g=new Date(0);g.setUTCFullYear(o,s-1,l),g.setUTCHours(u,d,f,Number((n[7]??``).padEnd(3,`0`).slice(0,3)));let _=(p*3600+m*60+h)*1e3,v=g.getTime()-(n[9]===`-`?-_:_);return i(v)?new Date(v):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
+ //# sourceMappingURL=datetime-physical-codec-qKxFtI3B.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datetime-physical-codec-qKxFtI3B.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OA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AQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-DtLdBQYg.mjs";import{n as i,r as a,t as o}from"./key-D9LtHxVK.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{o as u}from"./execution-context-rJXTRVrJ.mjs";import{t as d}from"./clock-C24RcpwO.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
- //# sourceMappingURL=driver-vn-9CN0y.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-514RME2X.mjs";import{n as i,r as a,t as o}from"./key-B89Z4vxn.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{o as u}from"./execution-context-rJXTRVrJ.mjs";import{t as d}from"./clock-YTLtjLFS.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
+ //# sourceMappingURL=driver-BvP7eW0A.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"driver-vn-9CN0y.mjs","names":["v","#executeCached","#invalidateScoped","#fillRevision","result","#setResultInBackground","#getCachedResult","#revalidateInBackground","#getScoped","#setInBackground","#setScoped","#markRevalidatingScoped","#clearRevalidatingScoped","#prefixKey","#observe","#deletePrefixed","#clearPrefixed"],"sources":["../src/cache/cache-background.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/driver.ts"],"sourcesContent":["import type { WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nexport const REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/**\n * Time unit multipliers in milliseconds\n */\nconst TIME_UNITS: Record<string, number> = {\n ms: 1,\n millisecond: 1,\n milliseconds: 1,\n s: 1000,\n sec: 1000,\n second: 1000,\n seconds: 1000,\n m: 60 * 1000,\n min: 60 * 1000,\n minute: 60 * 1000,\n minutes: 60 * 1000,\n h: 60 * 60 * 1000,\n hr: 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n hours: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n days: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000,\n weeks: 7 * 24 * 60 * 60 * 1000,\n month: 30 * 24 * 60 * 60 * 1000,\n months: 30 * 24 * 60 * 60 * 1000,\n};\n\nconst VALID_UNITS = Object.keys(TIME_UNITS).join(\", \");\n\n/**\n * Parse a TTL string into milliseconds\n *\n * @example\n * parseTTL(\"1 hour\") // 3600000\n * parseTTL(\"20 seconds\") // 20000\n * parseTTL(\"5m\") // 300000\n * parseTTL(\"2.5 hours\") // 9000000\n * parseTTL(3000) // 3000 (passthrough)\n *\n * @throws CacheInvalidTTLError if format is invalid\n */\nconst TTL_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/;\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const normalized = ttl.trim().toLowerCase();\n\n // Match patterns like \"1 hour\", \"20seconds\", \"2.5 h\"\n const match = normalized.match(TTL_PATTERN);\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\")`\n );\n }\n\n const valueStr = match[1] as string;\n const unit = match[2] as string;\n const value = Number.parseFloat(valueStr);\n const multiplier = TIME_UNITS[unit];\n\n if (multiplier === undefined) {\n throw new CacheInvalidTTLError(\n `Unknown time unit: \"${unit}\". Valid units: ${VALID_UNITS}`\n );\n }\n\n const result = Math.floor(value * multiplier);\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\nexport type CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nexport const cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options?.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nexport const DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\nexport type WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nexport const withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n (value: string | number) => {\n return parseTTL(value);\n }\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) => {\n if (value === undefined || typeof value === \"boolean\") {\n return value;\n }\n return parseTTL(value);\n }\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport type { DriverIdentity } from \"@drivers/driver-identity\";\nimport { getExecutionExtensionChain } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport { CacheInvalidKeyError } from \"@errors\";\nimport {\n getOfficialInstrumentationChainCapability,\n runProtectedObservers,\n selectTrustedObservers,\n} from \"@extensions/observation\";\nimport type {\n CacheCompletionFacts,\n CacheOutcome,\n CacheUnitFacts,\n} from \"@extensions/official-facts\";\nimport { type Clock, systemClock } from \"../clock\";\nimport {\n REVALIDATING_SUFFIX,\n REVALIDATING_TTL_MS,\n scheduleBackground,\n} from \"./cache-background\";\nimport {\n CACHE_PREFIX,\n cacheLookupOf,\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n} from \"./key\";\nimport {\n type CacheInvalidationOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/** Parsed options for one cached ORM execution. */\nexport interface CacheExecutionOptions {\n ttlMs: number;\n swr: number | false;\n bypass: boolean;\n key?: string;\n waitUntil?: WaitUntilFn;\n /**\n * The database driver's identity, read once at `$withCache`; absent when\n * that read throws, and the revalidation root is presented without it.\n */\n driverIdentity?: DriverIdentity | undefined;\n executionContext?: QueryExecutionContext;\n}\n\nexport interface DetachedCacheResultCodec<T> {\n snapshot(value: T): unknown;\n materialize(snapshot: unknown): T;\n}\n\ninterface ObservedRevalidationFailure {\n failed: boolean;\n error: unknown;\n}\n\ntype ExecuteCachedWithResultCodec = <T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n) => Promise<T>;\n\nlet executeCachedWithResultCodecFriend: ExecuteCachedWithResultCodec;\n\ntype InvalidateOfficialCache = (\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n) => Promise<void>;\n\nlet invalidateOfficialCacheFriend: InvalidateOfficialCache;\n\nconst officialCacheNamespaces = new WeakMap<object, string>();\n\ninterface CacheOutcomeList {\n readonly outcomes: CacheOutcome[];\n /** Set once the operation completion has read the list. */\n completed: boolean;\n}\n\n/** One outcome list per logical cache execution, keyed by its context. */\nconst executionOutcomes = new WeakMap<\n QueryExecutionContext,\n CacheOutcomeList\n>();\n\nconst completeWithoutFacts = (): undefined => undefined;\n\nfunction createCacheOutcome(\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): CacheOutcome {\n return { event, status, at: Date.now(), error };\n}\n\n/** Record one decision of this execution when its capability wants outcomes. */\nfunction recordCacheOutcome(\n context: QueryExecutionContext | undefined,\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): void {\n if (\n context === undefined ||\n getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n )?.wants(\"cache-outcomes\") !== true\n ) {\n return;\n }\n let list = executionOutcomes.get(context);\n if (list === undefined) {\n list = { outcomes: [], completed: false };\n executionOutcomes.set(context, list);\n }\n list.outcomes.push(createCacheOutcome(event, status, error));\n}\n\n/**\n * A background set failure joins its execution's list while that list is still\n * open, so it presents after the logical miss; otherwise it completes the set\n * unit itself.\n */\nfunction placeCacheSetFailure(\n context: QueryExecutionContext,\n failure: unknown\n): CacheCompletionFacts | undefined {\n const outcome = createCacheOutcome(\"miss\", \"cache-set-failed\", failure);\n const list = executionOutcomes.get(context);\n if (list !== undefined && !list.completed) {\n list.outcomes.push(outcome);\n return undefined;\n }\n return Object.freeze({ kind: \"cache\", outcomes: [outcome] });\n}\n\n/** Close and read one execution's outcome list at its operation completion. */\nexport function readCacheExecutionOutcomes(\n context: QueryExecutionContext\n): (() => readonly CacheOutcome[]) | undefined {\n const list = executionOutcomes.get(context);\n if (list === undefined) return undefined;\n return () => {\n list.completed = true;\n return Object.freeze([...list.outcomes]);\n };\n}\n\n/** Create one opaque scope recognized only by this module's private namespace map. */\nexport function createOfficialCacheScope(namespace: string): object {\n const scope = Object.freeze({});\n officialCacheNamespaces.set(scope, namespace);\n return scope;\n}\n\nfunction readOfficialCacheNamespace(scope: object): string {\n const namespace = officialCacheNamespaces.get(scope);\n if (namespace === undefined) {\n throw new CacheInvalidKeyError(\n \"Official cache scope is not authentic for this cache execution.\"\n );\n }\n return namespace;\n}\n\nfunction refuseExternalScope(scope: unknown): void {\n if (scope === undefined) return;\n throw new CacheInvalidKeyError(\n \"Cache driver methods do not accept an external cache scope.\"\n );\n}\n\ninterface PreparedInvalidationTarget {\n readonly kind: \"clear\" | \"delete\";\n readonly prefixedKey: string;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Public underscored methods handle key prefixing, instrumentation, and delegation\n * - Instrumentation support\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: Clock;\n\n static {\n executeCachedWithResultCodecFriend = (\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n ) => {\n const namespace = readOfficialCacheNamespace(scope);\n return cache.#executeCached(\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n namespace\n );\n };\n invalidateOfficialCacheFriend = (\n cache,\n modelName,\n options,\n context,\n scope\n ) =>\n cache.#invalidateScoped(\n modelName,\n options,\n context,\n readOfficialCacheNamespace(scope)\n );\n }\n\n constructor(driverName: string, clock: Clock = systemClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async #executeCached<T>(\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string\n ): Promise<T> {\n const lookup = cacheLookupOf(modelName, operation, args);\n const cacheKey = `${lookup.key}${options.key === undefined ? \"\" : `:${options.key}`}`;\n const identity = JSON.stringify([lookup.identity, options.key]);\n const revision = this.#fillRevision;\n\n // Core execution logic\n const executeCore = async (): Promise<T> => {\n // Bypass cache read if requested\n if (options.bypass) {\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"bypass\");\n return result;\n }\n\n // Try to get from cache\n const cached = await this.#getCachedResult<T>(\n cacheKey,\n options.executionContext,\n namespace,\n codec,\n identity\n );\n\n if (cached) {\n const age = this.clock.now() - cached.createdAt;\n const isStale = age >= cached.ttl;\n\n if (!isStale) {\n // Fresh cache hit\n recordCacheOutcome(options.executionContext, \"hit\");\n return cached.value;\n }\n\n const swrTtl = options.swr;\n if (\n swrTtl !== false &&\n age < swrTtl &&\n (cached.expiresAt === undefined ||\n this.clock.now() < cached.expiresAt)\n ) {\n // Stale but SWR enabled - return stale and revalidate in background\n scheduleBackground(\n this.#revalidateInBackground(\n modelName,\n operation,\n cacheKey,\n executor,\n options,\n swrTtl,\n codec,\n namespace,\n identity,\n revision\n ),\n options.waitUntil\n );\n recordCacheOutcome(options.executionContext, \"hit\", \"stale\");\n return cached.value;\n }\n\n // Stale and no SWR - fall through to fetch fresh\n }\n\n // Cache miss or stale without SWR - execute query\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"miss\");\n return result;\n };\n\n return executeCore();\n }\n\n async #getCachedResult<T>(\n key: string,\n context: QueryExecutionContext | undefined,\n namespace: string,\n codec: DetachedCacheResultCodec<T>,\n identity: string\n ): Promise<CacheEntry<T> | null> {\n const cached = await this.#getScoped<unknown>(key, context, namespace);\n return cached === null ||\n cached.identity !== identity ||\n !Number.isFinite(cached.createdAt) ||\n !Number.isFinite(cached.ttl) ||\n cached.ttl <= 0 ||\n cached.expiresAt === undefined ||\n !Number.isFinite(cached.expiresAt) ||\n cached.expiresAt < cached.createdAt\n ? null\n : {\n createdAt: cached.createdAt,\n ttl: cached.ttl,\n expiresAt: cached.expiresAt,\n value: codec.materialize(cached.value),\n };\n }\n\n #setResultInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n if (revision !== this.#fillRevision) return;\n let stored: unknown;\n try {\n stored = codec.snapshot(value);\n } catch (error) {\n recordCacheOutcome(\n options.executionContext,\n \"miss\",\n \"cache-set-failed\",\n error\n );\n return;\n }\n this.#setInBackground(key, stored, options, namespace, identity, revision);\n }\n\n /**\n * Set cache value in background (non-blocking)\n */\n #setInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n // The observed set unit presents a failure; without the catch it would\n // become an unhandled rejection.\n const cachePromise = this.#setScoped(\n key,\n value,\n {\n ttl: options.ttlMs,\n swrTtl: options.swr !== false ? options.swr : undefined,\n },\n options.executionContext,\n namespace,\n options.executionContext,\n identity,\n revision\n ).catch(() => undefined);\n\n scheduleBackground(cachePromise, options.waitUntil);\n }\n\n /**\n * Revalidate cache entry in background (for SWR)\n * Uses the backing cache marker for best-effort duplicate suppression.\n */\n async #revalidateInBackground<T>(\n modelName: string,\n operation: string,\n cacheKey: string,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n swrTtl: number,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): Promise<void> {\n // Check whether another request has already published this marker.\n let shouldRevalidate: boolean;\n try {\n shouldRevalidate = await this.#markRevalidatingScoped(\n cacheKey,\n namespace\n );\n } catch {\n // If marking fails, skip revalidation to avoid request failure\n return;\n }\n if (!shouldRevalidate) {\n // Another request is handling revalidation, skip\n return;\n }\n\n const observers = getExecutionExtensionChain(\n options.executionContext\n )?.observe;\n const observedFailure: ObservedRevalidationFailure | undefined =\n observers === undefined || observers.length === 0\n ? undefined\n : { failed: false, error: undefined };\n // The observed child stores its terminal outcome before it settles, and the\n // rail reads completion facts only after that.\n let completion: CacheCompletionFacts | undefined;\n\n const doRevalidate = async (): Promise<CacheOutcome> => {\n let terminal: CacheOutcome;\n try {\n const result = await executor();\n const stored = codec.snapshot(result);\n await this.#setScoped(\n cacheKey,\n stored,\n {\n ttl: options.ttlMs,\n swrTtl,\n },\n options.executionContext,\n namespace,\n undefined,\n identity,\n revision\n );\n terminal = createCacheOutcome(\"revalidate\", \"success\");\n } catch (error) {\n // Log error but don't throw - this is background operation\n if (observedFailure !== undefined) {\n observedFailure.failed = true;\n observedFailure.error = error;\n }\n terminal = createCacheOutcome(\"revalidate\", \"error\", error);\n } finally {\n if (observedFailure === undefined) {\n await this.#clearRevalidatingScoped(cacheKey, namespace).catch(\n () => undefined\n );\n } else {\n try {\n await this.#clearRevalidatingScoped(cacheKey, namespace);\n } catch (cleanupFailure) {\n if (observedFailure.failed) {\n const workerFailure = observedFailure.error;\n observedFailure.error = new AggregateError(\n [workerFailure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: workerFailure }\n );\n } else {\n observedFailure.failed = true;\n observedFailure.error = cleanupFailure;\n }\n }\n }\n }\n return terminal;\n };\n\n const revalidationPromise =\n observedFailure === undefined\n ? doRevalidate()\n : runProtectedObservers(\n { kind: \"cache\", operation: \"revalidate\" },\n observers,\n async () => {\n completion = Object.freeze({\n kind: \"cache\",\n outcomes: [await doRevalidate()],\n });\n if (observedFailure.failed) throw observedFailure.error;\n },\n undefined,\n (): CacheUnitFacts =>\n Object.freeze({\n kind: \"cache\",\n context: options.executionContext,\n read: Object.freeze({\n model: modelName,\n operation,\n identity: options.driverIdentity,\n }),\n complete: () => completion,\n })\n );\n\n await revalidationPromise;\n }\n\n // ============================================================\n // PUBLIC API - Storage operations\n // ============================================================\n\n /**\n * Run one cache step inside its exact chain's observers. A backend delete or\n * clear has no public unit and reaches only the trusted observer.\n */\n #observe<T>(\n step: \"clear\" | \"delete\" | \"get\" | \"invalidate\" | \"set\",\n context: QueryExecutionContext | undefined,\n execute: () => Promise<T>,\n complete: CacheUnitFacts[\"complete\"] = completeWithoutFacts,\n ttl?: number\n ): Promise<T> {\n const observers = getExecutionExtensionChain(context)?.observe;\n // An unobserved step builds no unit and no facts closure, as the\n // revalidation above does. Measured on a no-op backend: without this, a get\n // allocates about 330 B more and takes about 16 ns longer.\n if (observers === undefined || observers.length === 0) return execute();\n const backend = step === \"clear\" || step === \"delete\";\n return runProtectedObservers(\n { kind: \"cache\", operation: backend ? \"invalidate\" : step },\n backend ? selectTrustedObservers(observers) : observers,\n execute,\n undefined,\n () =>\n Object.freeze(\n backend\n ? {\n kind: \"cache-backend\",\n boundary: step,\n driverName: this.driverName,\n complete: completeWithoutFacts,\n }\n : {\n kind: \"cache\",\n context,\n driverName: this.driverName,\n ...(ttl === undefined ? {} : { ttl }),\n complete,\n }\n )\n );\n }\n\n /**\n * Get a value from cache\n * @param key - Cache key (will be prefixed automatically)\n */\n _get<T>(\n key: string,\n context?: QueryExecutionContext\n ): Promise<CacheEntry<T> | null>;\n async _get<T>(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<CacheEntry<T> | null> {\n refuseExternalScope(externalScope);\n return this.#getScoped<T>(key, context);\n }\n\n async #getScoped<T>(\n key: string,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<CacheEntry<T> | null> {\n const prefixedKey = this.#prefixKey(key, namespace);\n let cacheResult: \"hit\" | \"miss\" | \"stale\" | undefined;\n\n return this.#observe(\n \"get\",\n context,\n async () => {\n const entry = await this.get<T>(prefixedKey);\n if (entry) {\n const isStale = this.clock.now() - entry.createdAt > entry.ttl;\n cacheResult = isStale ? \"stale\" : \"hit\";\n } else {\n cacheResult = \"miss\";\n }\n return entry;\n },\n () =>\n cacheResult === undefined\n ? undefined\n : Object.freeze({ kind: \"cache\", result: cacheResult })\n );\n }\n\n /**\n * Set a value in cache\n * @param key - Cache key (will be prefixed automatically)\n * @param value - Value to cache\n * @param options - Cache options including TTL\n */\n _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#setScoped(key, value, options, context);\n }\n\n async #setScoped<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n namespace?: string,\n /** The logical execution a background set belongs to, which a failure joins. */\n backgroundOf?: QueryExecutionContext,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n const prefixedKey = this.#prefixKey(key, namespace);\n const entry: CacheEntry<T> = {\n value,\n createdAt: this.clock.now(),\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : {\n identity,\n expiresAt: this.clock.now() + (options.swrTtl ?? options.ttl),\n }),\n };\n\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n\n return this.#observe(\n \"set\",\n context,\n async () => {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n },\n backgroundOf === undefined\n ? undefined\n : (outcome) =>\n outcome.status === \"failure\"\n ? placeCacheSetFailure(backgroundOf, outcome.failure)\n : undefined,\n options.ttl\n );\n }\n\n /**\n * Delete a specific key (and its revalidating key)\n * @param key - Cache key (will be prefixed automatically)\n */\n _delete(key: string, context?: QueryExecutionContext): Promise<void>;\n async _delete(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedKey = this.#prefixKey(key);\n return this.#deletePrefixed(prefixedKey, context);\n }\n\n /**\n * Clear cache by prefix or all within the public unscoped namespace.\n * @param prefix - Optional prefix to clear (will be prefixed automatically)\n */\n _clear(prefix?: string, context?: QueryExecutionContext): Promise<void>;\n async _clear(\n prefix?: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedPrefix = this.#prefixKey(prefix ?? \"\");\n return this.#clearPrefixed(prefixedPrefix, context);\n }\n\n /**\n * Mark entry as revalidating (for SWR coordination)\n * Returns true if this caller should perform revalidation\n * @param key - Cache key (will be prefixed automatically)\n */\n _markRevalidating(key: string): Promise<boolean>;\n async _markRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<boolean> {\n refuseExternalScope(externalScope);\n return this.#markRevalidatingScoped(key);\n }\n\n async #markRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<boolean> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n\n // Check if already revalidating\n const existing = await this.get(revalidatingKey);\n if (existing && this.clock.now() - existing.createdAt < existing.ttl)\n return false;\n\n // Set revalidating flag with short TTL\n const entry: CacheEntry<boolean> = {\n value: true,\n createdAt: this.clock.now(),\n ttl: REVALIDATING_TTL_MS,\n };\n await this.set(revalidatingKey, REVALIDATING_TTL_MS, entry);\n\n return true;\n }\n\n /**\n * Clear revalidating flag\n * @param key - Cache key (will be prefixed automatically)\n */\n _clearRevalidating(key: string): Promise<void>;\n async _clearRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#clearRevalidatingScoped(key);\n }\n\n async #clearRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<void> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n await this.delete([revalidatingKey]);\n }\n\n /**\n * Invalidate cache entries after a mutation\n * @param modelName - The model name for auto-invalidation\n * @param options - Cache invalidation options\n */\n _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#invalidateScoped(modelName, options, context);\n }\n\n async #invalidateScoped(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n const targets: PreparedInvalidationTarget[] = [];\n if (options === undefined || options.autoInvalidate === true) {\n targets.push({\n kind: \"clear\",\n prefixedKey: this.#prefixKey(\n namespace === undefined ? `${modelName}:` : \"\",\n namespace\n ),\n });\n }\n if (options?.invalidate) {\n for (const entry of options.invalidate) {\n const isPrefix = entry.endsWith(\"*\");\n const key = isPrefix ? entry.slice(0, -1) : entry;\n targets.push({\n kind: isPrefix ? \"clear\" : \"delete\",\n prefixedKey: this.#prefixKey(key, namespace),\n });\n }\n }\n return this.#observe(\"invalidate\", context, async () => {\n const promises: Promise<void>[] = [];\n for (const target of targets) {\n promises.push(\n target.kind === \"clear\"\n ? this.#clearPrefixed(target.prefixedKey, context)\n : this.#deletePrefixed(target.prefixedKey, context)\n );\n }\n await Promise.all(promises);\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n // ============================================================\n // INTERNAL HELPERS\n // ============================================================\n\n #deletePrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n const keys = [prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`];\n return this.#observe(\"delete\", context, () => this.delete(keys));\n }\n\n #clearPrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n return this.#observe(\"clear\", context, () => this.clear(prefixedKey));\n }\n\n /**\n * Prefix a public storage key, or rebase an official relative key into its\n * authenticated extension namespace.\n *\n * An EMPTY relative key is the whole scope — `$invalidate(\"*\")` — and it\n * rebases to `<scope>:`, WITH the separator, because the storage backends\n * clear by `startsWith`. A bare `<scope>` would also match every sibling scope\n * whose namespace string merely extends this one, and one axis of the scope\n * grammar can do that: the cache `version` is the last component and its `s:`\n * body is variable-length, so `version: \"a\"` is a strict prefix of\n * `version: \"ab\"` at the same dialect and namespace. That axis is exactly what\n * §7.1 leaves users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's entries.\n *\n * Adding the separator loses nothing: every key this scope can hold is written\n * through `#executeCached`, whose relative key is always\n * `<model>:<operation>:<hash>`, so no stored key is ever equal to the bare\n * scope. The unscoped arm below deliberately keeps its bare `viborm` root — a\n * public caller CAN store at exactly that key, there is only one such root,\n * and no sibling exists for a clear to cross into.\n */\n #prefixKey(key: string, namespace?: string): string {\n if (namespace !== undefined) {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n }\n\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace requires an authenticated cache extension.\"\n );\n }\n return prefixedKey;\n }\n}\n\n/** Internal cache-result seam; absent from the package cache barrel. */\nexport function executeCachedWithResultCodec<T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n): Promise<T> {\n return executeCachedWithResultCodecFriend(\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n );\n}\n\n/** Internal official invalidation seam; absent from the package cache barrel. */\nexport function invalidateOfficialCache(\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n): Promise<void> {\n return invalidateOfficialCacheFriend(\n cache,\n modelName,\n options,\n context,\n scope\n );\n}\n"],"mappings":"8UAEA,MAAa,EAAsB,SACtB,EAAsB,IAEnC,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GCFV,MAAM,EAAqC,CACzC,GAAI,EACJ,YAAa,EACb,aAAc,EACd,EAAG,IACH,IAAK,IACL,OAAQ,IACR,QAAS,IACT,EAAG,GAAK,IACR,IAAK,GAAK,IACV,OAAQ,GAAK,IACb,QAAS,GAAK,IACd,EAAG,KAAU,IACb,GAAI,KAAU,IACd,KAAM,KAAU,IAChB,MAAO,KAAU,IACjB,EAAG,KAAU,GAAK,IAClB,IAAK,KAAU,GAAK,IACpB,KAAM,KAAU,GAAK,IACrB,EAAG,MAAc,GAAK,IACtB,KAAM,MAAc,GAAK,IACzB,MAAO,MAAc,GAAK,IAC1B,MAAO,IAAU,GAAK,GAAK,IAC3B,OAAQ,IAAU,GAAK,GAAK,IAC7B,CAEK,EAAc,OAAO,KAAK,EAAW,CAAC,KAAK,KAAK,CAchD,EAAc,+BAEpB,SAAgB,SAAS,EAA8B,CACrD,GAAI,OAAO,GAAQ,SAAU,CAC3B,GAAI,CAAC,OAAO,SAAS,EAAI,EAAI,GAAO,GAAK,UACvC,MAAM,IAAI,EAAqB,8BAA8B,IAAM,CAErE,OAAO,EAMT,IAAM,EAHa,EAAI,MAAM,CAAC,aAAa,CAGlB,MAAM,EAAY,CAE3C,GAAI,CAAC,EACH,MAAM,IAAI,EACR,wBAAwB,EAAI,sEAC7B,CAGH,IAAM,EAAW,EAAM,GACjB,EAAO,EAAM,GACb,EAAQ,OAAO,WAAW,EA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,IAAA,GAAW,CAC3B,GAAI,EAAI,WAAW,GAAG,EAAa,GAAG,CACpC,MAAM,IAAI,EACR,qFACD,CAEH,MAAO,GAAG,EAAU,GAAG,IAGzB,IAAM,EAAc,EAAI,WAAW,GAAG,EAAa,GAAG,CAClD,EACA,EACE,GAAG,EAAa,GAAG,IACnB,EACN,GACE,IAAgB,GAChB,EAAY,WAAW,GAAG,EAA8B,GAAG,CAE3D,MAAM,IAAI,EACR,0EACD,CAEH,OAAO,IAKX,SAAgB,6BACd,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACY,CACZ,OAAO,mCACL,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACD,CAIH,SAAgB,wBACd,EACA,EACA,EACA,EACA,EACe,CACf,OAAO,8BACL,EACA,EACA,EACA,EACA,EACD"}
1
+ {"version":3,"file":"driver-BvP7eW0A.mjs","names":["v","#executeCached","#invalidateScoped","#fillRevision","result","#setResultInBackground","#getCachedResult","#revalidateInBackground","#getScoped","#setInBackground","#setScoped","#markRevalidatingScoped","#clearRevalidatingScoped","#prefixKey","#observe","#deletePrefixed","#clearPrefixed"],"sources":["../src/cache/cache-background.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/driver.ts"],"sourcesContent":["import type { WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nexport const REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/**\n * Time unit multipliers in milliseconds\n */\nconst TIME_UNITS: Record<string, number> = {\n ms: 1,\n millisecond: 1,\n milliseconds: 1,\n s: 1000,\n sec: 1000,\n second: 1000,\n seconds: 1000,\n m: 60 * 1000,\n min: 60 * 1000,\n minute: 60 * 1000,\n minutes: 60 * 1000,\n h: 60 * 60 * 1000,\n hr: 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n hours: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n days: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000,\n weeks: 7 * 24 * 60 * 60 * 1000,\n month: 30 * 24 * 60 * 60 * 1000,\n months: 30 * 24 * 60 * 60 * 1000,\n};\n\nconst VALID_UNITS = Object.keys(TIME_UNITS).join(\", \");\n\n/**\n * Parse a TTL string into milliseconds\n *\n * @example\n * parseTTL(\"1 hour\") // 3600000\n * parseTTL(\"20 seconds\") // 20000\n * parseTTL(\"5m\") // 300000\n * parseTTL(\"2.5 hours\") // 9000000\n * parseTTL(3000) // 3000 (passthrough)\n *\n * @throws CacheInvalidTTLError if format is invalid\n */\nconst TTL_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/;\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const normalized = ttl.trim().toLowerCase();\n\n // Match patterns like \"1 hour\", \"20seconds\", \"2.5 h\"\n const match = normalized.match(TTL_PATTERN);\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\")`\n );\n }\n\n const valueStr = match[1] as string;\n const unit = match[2] as string;\n const value = Number.parseFloat(valueStr);\n const multiplier = TIME_UNITS[unit];\n\n if (multiplier === undefined) {\n throw new CacheInvalidTTLError(\n `Unknown time unit: \"${unit}\". Valid units: ${VALID_UNITS}`\n );\n }\n\n const result = Math.floor(value * multiplier);\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\nexport type CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nexport const cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options?.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nexport const DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\nexport type WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nexport const withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n (value: string | number) => {\n return parseTTL(value);\n }\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) => {\n if (value === undefined || typeof value === \"boolean\") {\n return value;\n }\n return parseTTL(value);\n }\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport type { DriverIdentity } from \"@drivers/driver-identity\";\nimport { getExecutionExtensionChain } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport { CacheInvalidKeyError } from \"@errors\";\nimport {\n getOfficialInstrumentationChainCapability,\n runProtectedObservers,\n selectTrustedObservers,\n} from \"@extensions/observation\";\nimport type {\n CacheCompletionFacts,\n CacheOutcome,\n CacheUnitFacts,\n} from \"@extensions/official-facts\";\nimport { type Clock, systemClock } from \"../clock\";\nimport {\n REVALIDATING_SUFFIX,\n REVALIDATING_TTL_MS,\n scheduleBackground,\n} from \"./cache-background\";\nimport {\n CACHE_PREFIX,\n cacheLookupOf,\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n} from \"./key\";\nimport {\n type CacheInvalidationOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/** Parsed options for one cached ORM execution. */\nexport interface CacheExecutionOptions {\n ttlMs: number;\n swr: number | false;\n bypass: boolean;\n key?: string;\n waitUntil?: WaitUntilFn;\n /**\n * The database driver's identity, read once at `$withCache`; absent when\n * that read throws, and the revalidation root is presented without it.\n */\n driverIdentity?: DriverIdentity | undefined;\n executionContext?: QueryExecutionContext;\n}\n\nexport interface DetachedCacheResultCodec<T> {\n snapshot(value: T): unknown;\n materialize(snapshot: unknown): T;\n}\n\ninterface ObservedRevalidationFailure {\n failed: boolean;\n error: unknown;\n}\n\ntype ExecuteCachedWithResultCodec = <T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n) => Promise<T>;\n\nlet executeCachedWithResultCodecFriend: ExecuteCachedWithResultCodec;\n\ntype InvalidateOfficialCache = (\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n) => Promise<void>;\n\nlet invalidateOfficialCacheFriend: InvalidateOfficialCache;\n\nconst officialCacheNamespaces = new WeakMap<object, string>();\n\ninterface CacheOutcomeList {\n readonly outcomes: CacheOutcome[];\n /** Set once the operation completion has read the list. */\n completed: boolean;\n}\n\n/** One outcome list per logical cache execution, keyed by its context. */\nconst executionOutcomes = new WeakMap<\n QueryExecutionContext,\n CacheOutcomeList\n>();\n\nconst completeWithoutFacts = (): undefined => undefined;\n\nfunction createCacheOutcome(\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): CacheOutcome {\n return { event, status, at: Date.now(), error };\n}\n\n/** Record one decision of this execution when its capability wants outcomes. */\nfunction recordCacheOutcome(\n context: QueryExecutionContext | undefined,\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): void {\n if (\n context === undefined ||\n getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n )?.wants(\"cache-outcomes\") !== true\n ) {\n return;\n }\n let list = executionOutcomes.get(context);\n if (list === undefined) {\n list = { outcomes: [], completed: false };\n executionOutcomes.set(context, list);\n }\n list.outcomes.push(createCacheOutcome(event, status, error));\n}\n\n/**\n * A background set failure joins its execution's list while that list is still\n * open, so it presents after the logical miss; otherwise it completes the set\n * unit itself.\n */\nfunction placeCacheSetFailure(\n context: QueryExecutionContext,\n failure: unknown\n): CacheCompletionFacts | undefined {\n const outcome = createCacheOutcome(\"miss\", \"cache-set-failed\", failure);\n const list = executionOutcomes.get(context);\n if (list !== undefined && !list.completed) {\n list.outcomes.push(outcome);\n return undefined;\n }\n return Object.freeze({ kind: \"cache\", outcomes: [outcome] });\n}\n\n/** Close and read one execution's outcome list at its operation completion. */\nexport function readCacheExecutionOutcomes(\n context: QueryExecutionContext\n): (() => readonly CacheOutcome[]) | undefined {\n const list = executionOutcomes.get(context);\n if (list === undefined) return undefined;\n return () => {\n list.completed = true;\n return Object.freeze([...list.outcomes]);\n };\n}\n\n/** Create one opaque scope recognized only by this module's private namespace map. */\nexport function createOfficialCacheScope(namespace: string): object {\n const scope = Object.freeze({});\n officialCacheNamespaces.set(scope, namespace);\n return scope;\n}\n\nfunction readOfficialCacheNamespace(scope: object): string {\n const namespace = officialCacheNamespaces.get(scope);\n if (namespace === undefined) {\n throw new CacheInvalidKeyError(\n \"Official cache scope is not authentic for this cache execution.\"\n );\n }\n return namespace;\n}\n\nfunction refuseExternalScope(scope: unknown): void {\n if (scope === undefined) return;\n throw new CacheInvalidKeyError(\n \"Cache driver methods do not accept an external cache scope.\"\n );\n}\n\ninterface PreparedInvalidationTarget {\n readonly kind: \"clear\" | \"delete\";\n readonly prefixedKey: string;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Public underscored methods handle key prefixing, instrumentation, and delegation\n * - Instrumentation support\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: Clock;\n\n static {\n executeCachedWithResultCodecFriend = (\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n ) => {\n const namespace = readOfficialCacheNamespace(scope);\n return cache.#executeCached(\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n namespace\n );\n };\n invalidateOfficialCacheFriend = (\n cache,\n modelName,\n options,\n context,\n scope\n ) =>\n cache.#invalidateScoped(\n modelName,\n options,\n context,\n readOfficialCacheNamespace(scope)\n );\n }\n\n constructor(driverName: string, clock: Clock = systemClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async #executeCached<T>(\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string\n ): Promise<T> {\n const lookup = cacheLookupOf(modelName, operation, args);\n const cacheKey = `${lookup.key}${options.key === undefined ? \"\" : `:${options.key}`}`;\n const identity = JSON.stringify([lookup.identity, options.key]);\n const revision = this.#fillRevision;\n\n // Core execution logic\n const executeCore = async (): Promise<T> => {\n // Bypass cache read if requested\n if (options.bypass) {\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"bypass\");\n return result;\n }\n\n // Try to get from cache\n const cached = await this.#getCachedResult<T>(\n cacheKey,\n options.executionContext,\n namespace,\n codec,\n identity\n );\n\n if (cached) {\n const age = this.clock.now() - cached.createdAt;\n const isStale = age >= cached.ttl;\n\n if (!isStale) {\n // Fresh cache hit\n recordCacheOutcome(options.executionContext, \"hit\");\n return cached.value;\n }\n\n const swrTtl = options.swr;\n if (\n swrTtl !== false &&\n age < swrTtl &&\n (cached.expiresAt === undefined ||\n this.clock.now() < cached.expiresAt)\n ) {\n // Stale but SWR enabled - return stale and revalidate in background\n scheduleBackground(\n this.#revalidateInBackground(\n modelName,\n operation,\n cacheKey,\n executor,\n options,\n swrTtl,\n codec,\n namespace,\n identity,\n revision\n ),\n options.waitUntil\n );\n recordCacheOutcome(options.executionContext, \"hit\", \"stale\");\n return cached.value;\n }\n\n // Stale and no SWR - fall through to fetch fresh\n }\n\n // Cache miss or stale without SWR - execute query\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"miss\");\n return result;\n };\n\n return executeCore();\n }\n\n async #getCachedResult<T>(\n key: string,\n context: QueryExecutionContext | undefined,\n namespace: string,\n codec: DetachedCacheResultCodec<T>,\n identity: string\n ): Promise<CacheEntry<T> | null> {\n const cached = await this.#getScoped<unknown>(key, context, namespace);\n return cached === null ||\n cached.identity !== identity ||\n !Number.isFinite(cached.createdAt) ||\n !Number.isFinite(cached.ttl) ||\n cached.ttl <= 0 ||\n cached.expiresAt === undefined ||\n !Number.isFinite(cached.expiresAt) ||\n cached.expiresAt < cached.createdAt\n ? null\n : {\n createdAt: cached.createdAt,\n ttl: cached.ttl,\n expiresAt: cached.expiresAt,\n value: codec.materialize(cached.value),\n };\n }\n\n #setResultInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n if (revision !== this.#fillRevision) return;\n let stored: unknown;\n try {\n stored = codec.snapshot(value);\n } catch (error) {\n recordCacheOutcome(\n options.executionContext,\n \"miss\",\n \"cache-set-failed\",\n error\n );\n return;\n }\n this.#setInBackground(key, stored, options, namespace, identity, revision);\n }\n\n /**\n * Set cache value in background (non-blocking)\n */\n #setInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n // The observed set unit presents a failure; without the catch it would\n // become an unhandled rejection.\n const cachePromise = this.#setScoped(\n key,\n value,\n {\n ttl: options.ttlMs,\n swrTtl: options.swr !== false ? options.swr : undefined,\n },\n options.executionContext,\n namespace,\n options.executionContext,\n identity,\n revision\n ).catch(() => undefined);\n\n scheduleBackground(cachePromise, options.waitUntil);\n }\n\n /**\n * Revalidate cache entry in background (for SWR)\n * Uses the backing cache marker for best-effort duplicate suppression.\n */\n async #revalidateInBackground<T>(\n modelName: string,\n operation: string,\n cacheKey: string,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n swrTtl: number,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): Promise<void> {\n // Check whether another request has already published this marker.\n let shouldRevalidate: boolean;\n try {\n shouldRevalidate = await this.#markRevalidatingScoped(\n cacheKey,\n namespace\n );\n } catch {\n // If marking fails, skip revalidation to avoid request failure\n return;\n }\n if (!shouldRevalidate) {\n // Another request is handling revalidation, skip\n return;\n }\n\n const observers = getExecutionExtensionChain(\n options.executionContext\n )?.observe;\n const observedFailure: ObservedRevalidationFailure | undefined =\n observers === undefined || observers.length === 0\n ? undefined\n : { failed: false, error: undefined };\n // The observed child stores its terminal outcome before it settles, and the\n // rail reads completion facts only after that.\n let completion: CacheCompletionFacts | undefined;\n\n const doRevalidate = async (): Promise<CacheOutcome> => {\n let terminal: CacheOutcome;\n try {\n const result = await executor();\n const stored = codec.snapshot(result);\n await this.#setScoped(\n cacheKey,\n stored,\n {\n ttl: options.ttlMs,\n swrTtl,\n },\n options.executionContext,\n namespace,\n undefined,\n identity,\n revision\n );\n terminal = createCacheOutcome(\"revalidate\", \"success\");\n } catch (error) {\n // Log error but don't throw - this is background operation\n if (observedFailure !== undefined) {\n observedFailure.failed = true;\n observedFailure.error = error;\n }\n terminal = createCacheOutcome(\"revalidate\", \"error\", error);\n } finally {\n if (observedFailure === undefined) {\n await this.#clearRevalidatingScoped(cacheKey, namespace).catch(\n () => undefined\n );\n } else {\n try {\n await this.#clearRevalidatingScoped(cacheKey, namespace);\n } catch (cleanupFailure) {\n if (observedFailure.failed) {\n const workerFailure = observedFailure.error;\n observedFailure.error = new AggregateError(\n [workerFailure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: workerFailure }\n );\n } else {\n observedFailure.failed = true;\n observedFailure.error = cleanupFailure;\n }\n }\n }\n }\n return terminal;\n };\n\n const revalidationPromise =\n observedFailure === undefined\n ? doRevalidate()\n : runProtectedObservers(\n { kind: \"cache\", operation: \"revalidate\" },\n observers,\n async () => {\n completion = Object.freeze({\n kind: \"cache\",\n outcomes: [await doRevalidate()],\n });\n if (observedFailure.failed) throw observedFailure.error;\n },\n undefined,\n (): CacheUnitFacts =>\n Object.freeze({\n kind: \"cache\",\n context: options.executionContext,\n read: Object.freeze({\n model: modelName,\n operation,\n identity: options.driverIdentity,\n }),\n complete: () => completion,\n })\n );\n\n await revalidationPromise;\n }\n\n // ============================================================\n // PUBLIC API - Storage operations\n // ============================================================\n\n /**\n * Run one cache step inside its exact chain's observers. A backend delete or\n * clear has no public unit and reaches only the trusted observer.\n */\n #observe<T>(\n step: \"clear\" | \"delete\" | \"get\" | \"invalidate\" | \"set\",\n context: QueryExecutionContext | undefined,\n execute: () => Promise<T>,\n complete: CacheUnitFacts[\"complete\"] = completeWithoutFacts,\n ttl?: number\n ): Promise<T> {\n const observers = getExecutionExtensionChain(context)?.observe;\n // An unobserved step builds no unit and no facts closure, as the\n // revalidation above does. Measured on a no-op backend: without this, a get\n // allocates about 330 B more and takes about 16 ns longer.\n if (observers === undefined || observers.length === 0) return execute();\n const backend = step === \"clear\" || step === \"delete\";\n return runProtectedObservers(\n { kind: \"cache\", operation: backend ? \"invalidate\" : step },\n backend ? selectTrustedObservers(observers) : observers,\n execute,\n undefined,\n () =>\n Object.freeze(\n backend\n ? {\n kind: \"cache-backend\",\n boundary: step,\n driverName: this.driverName,\n complete: completeWithoutFacts,\n }\n : {\n kind: \"cache\",\n context,\n driverName: this.driverName,\n ...(ttl === undefined ? {} : { ttl }),\n complete,\n }\n )\n );\n }\n\n /**\n * Get a value from cache\n * @param key - Cache key (will be prefixed automatically)\n */\n _get<T>(\n key: string,\n context?: QueryExecutionContext\n ): Promise<CacheEntry<T> | null>;\n async _get<T>(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<CacheEntry<T> | null> {\n refuseExternalScope(externalScope);\n return this.#getScoped<T>(key, context);\n }\n\n async #getScoped<T>(\n key: string,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<CacheEntry<T> | null> {\n const prefixedKey = this.#prefixKey(key, namespace);\n let cacheResult: \"hit\" | \"miss\" | \"stale\" | undefined;\n\n return this.#observe(\n \"get\",\n context,\n async () => {\n const entry = await this.get<T>(prefixedKey);\n if (entry) {\n const isStale = this.clock.now() - entry.createdAt > entry.ttl;\n cacheResult = isStale ? \"stale\" : \"hit\";\n } else {\n cacheResult = \"miss\";\n }\n return entry;\n },\n () =>\n cacheResult === undefined\n ? undefined\n : Object.freeze({ kind: \"cache\", result: cacheResult })\n );\n }\n\n /**\n * Set a value in cache\n * @param key - Cache key (will be prefixed automatically)\n * @param value - Value to cache\n * @param options - Cache options including TTL\n */\n _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#setScoped(key, value, options, context);\n }\n\n async #setScoped<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n namespace?: string,\n /** The logical execution a background set belongs to, which a failure joins. */\n backgroundOf?: QueryExecutionContext,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n const prefixedKey = this.#prefixKey(key, namespace);\n const entry: CacheEntry<T> = {\n value,\n createdAt: this.clock.now(),\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : {\n identity,\n expiresAt: this.clock.now() + (options.swrTtl ?? options.ttl),\n }),\n };\n\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n\n return this.#observe(\n \"set\",\n context,\n async () => {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n },\n backgroundOf === undefined\n ? undefined\n : (outcome) =>\n outcome.status === \"failure\"\n ? placeCacheSetFailure(backgroundOf, outcome.failure)\n : undefined,\n options.ttl\n );\n }\n\n /**\n * Delete a specific key (and its revalidating key)\n * @param key - Cache key (will be prefixed automatically)\n */\n _delete(key: string, context?: QueryExecutionContext): Promise<void>;\n async _delete(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedKey = this.#prefixKey(key);\n return this.#deletePrefixed(prefixedKey, context);\n }\n\n /**\n * Clear cache by prefix or all within the public unscoped namespace.\n * @param prefix - Optional prefix to clear (will be prefixed automatically)\n */\n _clear(prefix?: string, context?: QueryExecutionContext): Promise<void>;\n async _clear(\n prefix?: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedPrefix = this.#prefixKey(prefix ?? \"\");\n return this.#clearPrefixed(prefixedPrefix, context);\n }\n\n /**\n * Mark entry as revalidating (for SWR coordination)\n * Returns true if this caller should perform revalidation\n * @param key - Cache key (will be prefixed automatically)\n */\n _markRevalidating(key: string): Promise<boolean>;\n async _markRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<boolean> {\n refuseExternalScope(externalScope);\n return this.#markRevalidatingScoped(key);\n }\n\n async #markRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<boolean> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n\n // Check if already revalidating\n const existing = await this.get(revalidatingKey);\n if (existing && this.clock.now() - existing.createdAt < existing.ttl)\n return false;\n\n // Set revalidating flag with short TTL\n const entry: CacheEntry<boolean> = {\n value: true,\n createdAt: this.clock.now(),\n ttl: REVALIDATING_TTL_MS,\n };\n await this.set(revalidatingKey, REVALIDATING_TTL_MS, entry);\n\n return true;\n }\n\n /**\n * Clear revalidating flag\n * @param key - Cache key (will be prefixed automatically)\n */\n _clearRevalidating(key: string): Promise<void>;\n async _clearRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#clearRevalidatingScoped(key);\n }\n\n async #clearRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<void> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n await this.delete([revalidatingKey]);\n }\n\n /**\n * Invalidate cache entries after a mutation\n * @param modelName - The model name for auto-invalidation\n * @param options - Cache invalidation options\n */\n _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#invalidateScoped(modelName, options, context);\n }\n\n async #invalidateScoped(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n const targets: PreparedInvalidationTarget[] = [];\n if (options === undefined || options.autoInvalidate === true) {\n targets.push({\n kind: \"clear\",\n prefixedKey: this.#prefixKey(\n namespace === undefined ? `${modelName}:` : \"\",\n namespace\n ),\n });\n }\n if (options?.invalidate) {\n for (const entry of options.invalidate) {\n const isPrefix = entry.endsWith(\"*\");\n const key = isPrefix ? entry.slice(0, -1) : entry;\n targets.push({\n kind: isPrefix ? \"clear\" : \"delete\",\n prefixedKey: this.#prefixKey(key, namespace),\n });\n }\n }\n return this.#observe(\"invalidate\", context, async () => {\n const promises: Promise<void>[] = [];\n for (const target of targets) {\n promises.push(\n target.kind === \"clear\"\n ? this.#clearPrefixed(target.prefixedKey, context)\n : this.#deletePrefixed(target.prefixedKey, context)\n );\n }\n await Promise.all(promises);\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n // ============================================================\n // INTERNAL HELPERS\n // ============================================================\n\n #deletePrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n const keys = [prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`];\n return this.#observe(\"delete\", context, () => this.delete(keys));\n }\n\n #clearPrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n return this.#observe(\"clear\", context, () => this.clear(prefixedKey));\n }\n\n /**\n * Prefix a public storage key, or rebase an official relative key into its\n * authenticated extension namespace.\n *\n * An EMPTY relative key is the whole scope — `$invalidate(\"*\")` — and it\n * rebases to `<scope>:`, WITH the separator, because the storage backends\n * clear by `startsWith`. A bare `<scope>` would also match every sibling scope\n * whose namespace string merely extends this one, and one axis of the scope\n * grammar can do that: the cache `version` is the last component and its `s:`\n * body is variable-length, so `version: \"a\"` is a strict prefix of\n * `version: \"ab\"` at the same dialect and namespace. That axis is exactly what\n * §7.1 leaves users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's entries.\n *\n * Adding the separator loses nothing: every key this scope can hold is written\n * through `#executeCached`, whose relative key is always\n * `<model>:<operation>:<hash>`, so no stored key is ever equal to the bare\n * scope. The unscoped arm below deliberately keeps its bare `viborm` root — a\n * public caller CAN store at exactly that key, there is only one such root,\n * and no sibling exists for a clear to cross into.\n */\n #prefixKey(key: string, namespace?: string): string {\n if (namespace !== undefined) {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n }\n\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace requires an authenticated cache extension.\"\n );\n }\n return prefixedKey;\n }\n}\n\n/** Internal cache-result seam; absent from the package cache barrel. */\nexport function executeCachedWithResultCodec<T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n): Promise<T> {\n return executeCachedWithResultCodecFriend(\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n );\n}\n\n/** Internal official invalidation seam; absent from the package cache barrel. */\nexport function invalidateOfficialCache(\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n): Promise<void> {\n return invalidateOfficialCacheFriend(\n cache,\n modelName,\n options,\n context,\n scope\n );\n}\n"],"mappings":"8UAEA,MAAa,EAAsB,SACtB,EAAsB,IAEnC,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GCFV,MAAM,EAAqC,CACzC,GAAI,EACJ,YAAa,EACb,aAAc,EACd,EAAG,IACH,IAAK,IACL,OAAQ,IACR,QAAS,IACT,EAAG,GAAK,IACR,IAAK,GAAK,IACV,OAAQ,GAAK,IACb,QAAS,GAAK,IACd,EAAG,KAAU,IACb,GAAI,KAAU,IACd,KAAM,KAAU,IAChB,MAAO,KAAU,IACjB,EAAG,KAAU,GAAK,IAClB,IAAK,KAAU,GAAK,IACpB,KAAM,KAAU,GAAK,IACr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