@rocicorp/zero 1.11.0-canary.7 → 1.11.0-canary.9

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 (258) hide show
  1. package/out/replicache/src/dag/gc.d.ts.map +1 -1
  2. package/out/replicache/src/dag/gc.js +2 -1
  3. package/out/replicache/src/dag/gc.js.map +1 -1
  4. package/out/replicache/src/dag/invalid-ref-count-error.d.ts +12 -0
  5. package/out/replicache/src/dag/invalid-ref-count-error.d.ts.map +1 -0
  6. package/out/replicache/src/dag/invalid-ref-count-error.js +19 -0
  7. package/out/replicache/src/dag/invalid-ref-count-error.js.map +1 -0
  8. package/out/replicache/src/dag/store-impl.d.ts +12 -2
  9. package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
  10. package/out/replicache/src/dag/store-impl.js +22 -8
  11. package/out/replicache/src/dag/store-impl.js.map +1 -1
  12. package/out/replicache/src/db/rebase.d.ts +14 -2
  13. package/out/replicache/src/db/rebase.d.ts.map +1 -1
  14. package/out/replicache/src/db/rebase.js +27 -5
  15. package/out/replicache/src/db/rebase.js.map +1 -1
  16. package/out/replicache/src/persist/collect-idb-databases.d.ts +10 -5
  17. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  18. package/out/replicache/src/persist/collect-idb-databases.js +16 -9
  19. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  20. package/out/replicache/src/persist/persist.d.ts.map +1 -1
  21. package/out/replicache/src/persist/persist.js +12 -5
  22. package/out/replicache/src/persist/persist.js.map +1 -1
  23. package/out/replicache/src/persist/refresh.js +6 -2
  24. package/out/replicache/src/persist/refresh.js.map +1 -1
  25. package/out/replicache/src/replicache-impl.d.ts +7 -3
  26. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  27. package/out/replicache/src/replicache-impl.js +98 -11
  28. package/out/replicache/src/replicache-impl.js.map +1 -1
  29. package/out/replicache/src/replicache-options.d.ts +9 -0
  30. package/out/replicache/src/replicache-options.d.ts.map +1 -1
  31. package/out/shared/src/iterables.d.ts +2 -0
  32. package/out/shared/src/iterables.d.ts.map +1 -1
  33. package/out/shared/src/iterables.js +18 -1
  34. package/out/shared/src/iterables.js.map +1 -1
  35. package/out/shared/src/ring-buffer.d.ts +8 -0
  36. package/out/shared/src/ring-buffer.d.ts.map +1 -1
  37. package/out/shared/src/ring-buffer.js +22 -1
  38. package/out/shared/src/ring-buffer.js.map +1 -1
  39. package/out/zero/package.js +2 -3
  40. package/out/zero/package.js.map +1 -1
  41. package/out/zero-cache/src/config/zero-config.js +2 -2
  42. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  43. package/out/zero-cache/src/server/change-streamer.js +1 -1
  44. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  45. package/out/zero-cache/src/server/inspector-delegate.d.ts +18 -2
  46. package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
  47. package/out/zero-cache/src/server/inspector-delegate.js +20 -7
  48. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  49. package/out/zero-cache/src/services/change-source/pg/backfill-resume.d.ts +156 -0
  50. package/out/zero-cache/src/services/change-source/pg/backfill-resume.d.ts.map +1 -0
  51. package/out/zero-cache/src/services/change-source/pg/backfill-resume.js +15 -0
  52. package/out/zero-cache/src/services/change-source/pg/backfill-resume.js.map +1 -0
  53. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts +15 -0
  54. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts.map +1 -0
  55. package/out/zero-cache/src/services/change-source/pg/change-source-init.js +99 -0
  56. package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -0
  57. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +14 -16
  58. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  59. package/out/zero-cache/src/services/change-source/pg/change-source.js +33 -126
  60. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  61. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +16 -1
  62. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  63. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +8 -4
  64. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.d.ts +16 -0
  66. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.d.ts.map +1 -0
  67. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.js +113 -0
  68. package/out/zero-cache/src/services/change-source/pg/replication-slot-cleanup-monitor.js.map +1 -0
  69. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +1 -15
  70. package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
  71. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +18 -21
  72. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  73. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +8 -9
  74. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  75. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +17 -1
  76. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/upstream-acker.js +19 -3
  78. package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +1 -1
  80. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +1 -0
  81. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +1 -1
  82. package/out/zero-cache/src/services/replicator/change-processor.js +1 -0
  83. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  84. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts +14 -1
  85. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts.map +1 -1
  86. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +30 -4
  87. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
  88. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +1 -1
  89. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
  91. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  92. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  93. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +6 -10
  94. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  95. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  96. package/out/zero-cache/src/services/view-syncer/view-syncer.js +14 -4
  97. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  98. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  99. package/out/zero-cache/src/types/streams.js +1 -1
  100. package/out/zero-cache/src/types/streams.js.map +1 -1
  101. package/out/zero-client/src/client/connection-manager.d.ts +20 -0
  102. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  103. package/out/zero-client/src/client/connection-manager.js +32 -14
  104. package/out/zero-client/src/client/connection-manager.js.map +1 -1
  105. package/out/zero-client/src/client/connection-status-enum.d.ts +2 -0
  106. package/out/zero-client/src/client/connection-status-enum.d.ts.map +1 -1
  107. package/out/zero-client/src/client/connection-status-enum.js +3 -1
  108. package/out/zero-client/src/client/connection-status-enum.js.map +1 -1
  109. package/out/zero-client/src/client/connection.d.ts +6 -0
  110. package/out/zero-client/src/client/connection.d.ts.map +1 -1
  111. package/out/zero-client/src/client/connection.js +2 -1
  112. package/out/zero-client/src/client/connection.js.map +1 -1
  113. package/out/zero-client/src/client/context.d.ts +8 -11
  114. package/out/zero-client/src/client/context.d.ts.map +1 -1
  115. package/out/zero-client/src/client/context.js +11 -15
  116. package/out/zero-client/src/client/context.js.map +1 -1
  117. package/out/zero-client/src/client/custom.js +2 -2
  118. package/out/zero-client/src/client/custom.js.map +1 -1
  119. package/out/zero-client/src/client/error.js +1 -1
  120. package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
  121. package/out/zero-client/src/client/mutator-proxy.js +2 -1
  122. package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
  123. package/out/zero-client/src/client/options.d.ts +3 -0
  124. package/out/zero-client/src/client/options.d.ts.map +1 -1
  125. package/out/zero-client/src/client/options.js.map +1 -1
  126. package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
  127. package/out/zero-client/src/client/query-manager.js +42 -6
  128. package/out/zero-client/src/client/query-manager.js.map +1 -1
  129. package/out/zero-client/src/client/version.js +1 -1
  130. package/out/zero-client/src/client/zero-rep.d.ts +1 -0
  131. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  132. package/out/zero-client/src/client/zero-rep.js +7 -5
  133. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  134. package/out/zero-client/src/client/zero.d.ts +9 -3
  135. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  136. package/out/zero-client/src/client/zero.js +48 -11
  137. package/out/zero-client/src/client/zero.js.map +1 -1
  138. package/out/zero-client/src/types/query-result.d.ts +2 -0
  139. package/out/zero-client/src/types/query-result.d.ts.map +1 -1
  140. package/out/zero-react/src/use-query.d.ts +5 -4
  141. package/out/zero-react/src/use-query.d.ts.map +1 -1
  142. package/out/zero-react/src/use-query.js +12 -1
  143. package/out/zero-react/src/use-query.js.map +1 -1
  144. package/out/zero-server/src/adapters/drizzle.d.ts +2 -1
  145. package/out/zero-server/src/adapters/drizzle.d.ts.map +1 -1
  146. package/out/zero-server/src/adapters/drizzle.js +12 -7
  147. package/out/zero-server/src/adapters/drizzle.js.map +1 -1
  148. package/out/zero-server/src/adapters/kysely.d.ts +2 -1
  149. package/out/zero-server/src/adapters/kysely.d.ts.map +1 -1
  150. package/out/zero-server/src/adapters/kysely.js +8 -2
  151. package/out/zero-server/src/adapters/kysely.js.map +1 -1
  152. package/out/zero-server/src/adapters/pg.d.ts +1 -0
  153. package/out/zero-server/src/adapters/pg.d.ts.map +1 -1
  154. package/out/zero-server/src/adapters/pg.js +8 -2
  155. package/out/zero-server/src/adapters/pg.js.map +1 -1
  156. package/out/zero-server/src/adapters/postgresjs.d.ts +1 -0
  157. package/out/zero-server/src/adapters/postgresjs.d.ts.map +1 -1
  158. package/out/zero-server/src/adapters/postgresjs.js +7 -1
  159. package/out/zero-server/src/adapters/postgresjs.js.map +1 -1
  160. package/out/zero-server/src/adapters/prisma.d.ts +3 -2
  161. package/out/zero-server/src/adapters/prisma.d.ts.map +1 -1
  162. package/out/zero-server/src/adapters/prisma.js +8 -2
  163. package/out/zero-server/src/adapters/prisma.js.map +1 -1
  164. package/out/zero-server/src/custom.d.ts +5 -1
  165. package/out/zero-server/src/custom.d.ts.map +1 -1
  166. package/out/zero-server/src/custom.js +6 -3
  167. package/out/zero-server/src/custom.js.map +1 -1
  168. package/out/zero-server/src/mod.d.ts +1 -1
  169. package/out/zero-server/src/mod.d.ts.map +1 -1
  170. package/out/zero-server/src/pg-query-executor.d.ts +2 -2
  171. package/out/zero-server/src/pg-query-executor.d.ts.map +1 -1
  172. package/out/zero-server/src/pg-query-executor.js +2 -2
  173. package/out/zero-server/src/pg-query-executor.js.map +1 -1
  174. package/out/zero-server/src/schema.d.ts +2 -2
  175. package/out/zero-server/src/schema.d.ts.map +1 -1
  176. package/out/zero-server/src/schema.js +2 -2
  177. package/out/zero-server/src/schema.js.map +1 -1
  178. package/out/zero-server/src/zql-database.d.ts +21 -1
  179. package/out/zero-server/src/zql-database.d.ts.map +1 -1
  180. package/out/zero-server/src/zql-database.js +33 -2
  181. package/out/zero-server/src/zql-database.js.map +1 -1
  182. package/out/zero-solid/src/solid-view.d.ts +10 -0
  183. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  184. package/out/zero-solid/src/solid-view.js +27 -0
  185. package/out/zero-solid/src/solid-view.js.map +1 -1
  186. package/out/zql/src/ivm/array-view.d.ts +10 -0
  187. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  188. package/out/zql/src/ivm/array-view.js +20 -8
  189. package/out/zql/src/ivm/array-view.js.map +1 -1
  190. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  191. package/out/zql/src/ivm/cap.js +5 -3
  192. package/out/zql/src/ivm/cap.js.map +1 -1
  193. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -1
  194. package/out/zql/src/ivm/deferred-input.js +3 -2
  195. package/out/zql/src/ivm/deferred-input.js.map +1 -1
  196. package/out/zql/src/ivm/exists.d.ts +1 -1
  197. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  198. package/out/zql/src/ivm/exists.js.map +1 -1
  199. package/out/zql/src/ivm/fan-in.d.ts +2 -2
  200. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  201. package/out/zql/src/ivm/fan-in.js +6 -5
  202. package/out/zql/src/ivm/fan-in.js.map +1 -1
  203. package/out/zql/src/ivm/fan-out.d.ts +2 -2
  204. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  205. package/out/zql/src/ivm/fan-out.js.map +1 -1
  206. package/out/zql/src/ivm/filter-operators.d.ts +6 -6
  207. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  208. package/out/zql/src/ivm/filter-operators.js +10 -8
  209. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  210. package/out/zql/src/ivm/filter.d.ts +2 -2
  211. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  212. package/out/zql/src/ivm/filter.js +7 -4
  213. package/out/zql/src/ivm/filter.js.map +1 -1
  214. package/out/zql/src/ivm/flipped-join.js +2 -2
  215. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  216. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
  217. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
  218. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +6 -4
  219. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
  220. package/out/zql/src/ivm/memory-source.d.ts +2 -2
  221. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  222. package/out/zql/src/ivm/memory-source.js +9 -9
  223. package/out/zql/src/ivm/memory-source.js.map +1 -1
  224. package/out/zql/src/ivm/take.d.ts.map +1 -1
  225. package/out/zql/src/ivm/take.js +3 -4
  226. package/out/zql/src/ivm/take.js.map +1 -1
  227. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  228. package/out/zql/src/ivm/union-fan-in.js +9 -7
  229. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  230. package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
  231. package/out/zql/src/ivm/view-apply-change.js +3 -3
  232. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  233. package/out/zql/src/mutate/custom.d.ts +24 -1
  234. package/out/zql/src/mutate/custom.d.ts.map +1 -1
  235. package/out/zql/src/mutate/custom.js.map +1 -1
  236. package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
  237. package/out/zql/src/mutate/mutator-registry.js +2 -2
  238. package/out/zql/src/mutate/mutator-registry.js.map +1 -1
  239. package/out/zql/src/query/query-delegate-base.d.ts +2 -0
  240. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  241. package/out/zql/src/query/query-delegate-base.js +55 -28
  242. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  243. package/out/zql/src/query/query-delegate.d.ts +11 -1
  244. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  245. package/out/zql/src/query/query-impl.d.ts +1 -0
  246. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  247. package/out/zql/src/query/query-impl.js.map +1 -1
  248. package/out/zql/src/query/query.d.ts +7 -1
  249. package/out/zql/src/query/query.d.ts.map +1 -1
  250. package/out/zql/src/query/runnable-query-impl.d.ts +1 -0
  251. package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
  252. package/out/zql/src/query/runnable-query-impl.js.map +1 -1
  253. package/out/zql/src/query/typed-view.d.ts +1 -1
  254. package/out/zql/src/query/typed-view.d.ts.map +1 -1
  255. package/out/zqlite/src/table-source.d.ts.map +1 -1
  256. package/out/zqlite/src/table-source.js +7 -5
  257. package/out/zqlite/src/table-source.js.map +1 -1
  258. package/package.json +2 -3
@@ -1 +1 @@
1
- {"version":3,"file":"replicache-impl.js","names":["#subscriptions","#mutationRecovery","#kvStoreProvider","#zero","#auth","#idbDatabase","#clientID","#ready","#profileIDPromise","#clientGroupIDPromise","#mutatorRegistry","#requestOptions","#idbDatabases","#lc","#closeAbortController","#persistLock","#enableScheduledPersist","#enableScheduledRefresh","#enableRefresh","#enablePullAndPushInOpen","#onPersist","#queryInternal","#pullConnectionLoop","#invokePull","#pushConnectionLoop","#invokePush","#registerMutators","#wrapInOnlineCheck","#wrapInReauthRetries","#isPullDisabled","#isPushDisabled","#handlePersist","#open","#clientStateNotFoundOnClient","#fireOnUpdateNeeded","#onVisibilityChange","#closed","#checkForClientStateNotFoundAndCallHandler","#online","#schedulePersist","#changeSyncCounters","#convertToClientStateNotFoundError","#handleVersionNotSupportedResponse","#clientStateNotFoundOnServer","#fireOnClientStateNotFound","#schedule","#persistScheduler","#scheduleRefresh","#refreshScheduler","#pushCounter","#pullCounter","#mutate","#register"],"sources":["../../../../replicache/src/replicache-impl.ts"],"sourcesContent":["import {Lock} from '@rocicorp/lock';\nimport type {LogContext} from '@rocicorp/logger';\nimport {consoleLogSink} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {AbortError} from '../../shared/src/abort-error.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getBrowserGlobal} from '../../shared/src/browser-env.ts';\nimport {getDocumentVisibilityWatcher} from '../../shared/src/document-visible.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport {PullDelegate, PushDelegate} from './connection-loop-delegates.ts';\nimport {ConnectionLoop, MAX_DELAY_MS, MIN_DELAY_MS} from './connection-loop.ts';\nimport {assertCookie, type Cookie} from './cookies.ts';\nimport {LazyStore} from './dag/lazy-store.ts';\nimport {StoreImpl} from './dag/store-impl.ts';\nimport {ChunkNotFoundError, mustGetHeadHash, type Store} from './dag/store.ts';\nimport {\n baseSnapshotFromHash,\n DEFAULT_HEAD_NAME,\n isLocalMetaDD31,\n type LocalMeta,\n} from './db/commit.ts';\nimport {readFromDefaultHead} from './db/read.ts';\nimport {rebaseMutationAndCommit} from './db/rebase.ts';\nimport {newWriteLocal} from './db/write.ts';\nimport {\n isClientStateNotFoundResponse,\n isVersionNotSupportedResponse,\n type VersionNotSupportedResponse,\n} from './error-responses.ts';\nimport * as FormatVersion from './format-version-enum.ts';\nimport {deepFreeze} from './frozen-json.ts';\nimport {getDefaultPuller, isDefaultPuller} from './get-default-puller.ts';\nimport {getDefaultPusher, isDefaultPusher} from './get-default-pusher.ts';\nimport {getKVStoreProvider} from './get-kv-store-provider.ts';\nimport {assertHash, emptyHash, type Hash, newRandomHash} from './hash.ts';\nimport type {HTTPRequestInfo} from './http-request-info.ts';\nimport {httpStatusUnauthorized} from './http-status-unauthorized.ts';\nimport type {IndexDefinitions} from './index-defs.ts';\nimport type {StoreProvider} from './kv/store.ts';\nimport {createLogContext} from './log-options.ts';\nimport {makeIDBName} from './make-idb-name.ts';\nimport {MutationRecovery} from './mutation-recovery.ts';\nimport {initNewClientChannel} from './new-client-channel.ts';\nimport {\n initOnPersistChannel,\n type OnPersist,\n type PersistInfo,\n} from './on-persist-channel.ts';\nimport {\n type PendingMutation,\n pendingMutationsForAPI,\n} from './pending-mutations.ts';\nimport {\n CLIENT_MAX_INACTIVE_TIME,\n GC_INTERVAL,\n initClientGC,\n} from './persist/client-gc.ts';\nimport {initClientGroupGC} from './persist/client-group-gc.ts';\nimport {disableClientGroup} from './persist/client-groups.ts';\nimport {\n ClientStateNotFoundError,\n initClientV6,\n type OnClientsDeleted,\n hasClientState as persistHasClientState,\n} from './persist/clients.ts';\nimport {\n COLLECT_IDB_INTERVAL,\n initCollectIDBDatabases,\n INITIAL_COLLECT_IDB_DELAY,\n} from './persist/collect-idb-databases.ts';\nimport {HEARTBEAT_INTERVAL, startHeartbeats} from './persist/heartbeat.ts';\nimport {\n IDBDatabasesStore,\n type IndexedDBDatabase,\n} from './persist/idb-databases-store.ts';\nimport {makeClientID} from './persist/make-client-id.ts';\nimport {persistDD31} from './persist/persist.ts';\nimport {refresh} from './persist/refresh.ts';\nimport {ProcessScheduler} from './process-scheduler.ts';\nimport type {Puller} from './puller.ts';\nimport {type Pusher, PushError} from './pusher.ts';\nimport type {\n MutationTrackingData,\n ReplicacheOptions,\n ZeroOption,\n} from './replicache-options.ts';\nimport {ReportError} from './report-error.ts';\nimport {setIntervalWithSignal} from './set-interval-with-signal.ts';\nimport {\n type SubscribeOptions,\n SubscriptionImpl,\n type SubscriptionsManager,\n SubscriptionsManagerImpl,\n type WatchCallback,\n type WatchCallbackForOptions,\n type WatchNoIndexCallback,\n type WatchOptions,\n WatchSubscription,\n} from './subscriptions.ts';\nimport type {DiffsMap} from './sync/diff.ts';\nimport * as HandlePullResponseResultEnum from './sync/handle-pull-response-result-type-enum.ts';\nimport type {ClientGroupID, ClientID} from './sync/ids.ts';\nimport {PullError} from './sync/pull-error.ts';\nimport {beginPullV1, handlePullResponseV1, maybeEndPull} from './sync/pull.ts';\nimport {push, PUSH_VERSION_DD31} from './sync/push.ts';\nimport {newRequestID} from './sync/request-id.ts';\nimport {SYNC_HEAD_NAME} from './sync/sync-head-name.ts';\nimport {throwIfClosed} from './transaction-closed-error.ts';\nimport type {ReadTransaction, WriteTransaction} from './transactions.ts';\nimport {ReadTransactionImpl, WriteTransactionImpl} from './transactions.ts';\nimport type {\n BeginPullResult,\n MakeMutator,\n MakeMutators,\n MutatorDefs,\n MutatorReturn,\n PokeInternal,\n QueryInternal,\n RequestOptions,\n UpdateNeededReason,\n} from './types.ts';\nimport {version} from './version.ts';\nimport {\n withRead,\n withWrite,\n withWriteNoImplicitCommit,\n} from './with-transactions.ts';\n\n/**\n * The maximum number of time to call out to getAuth before giving up\n * and throwing an error.\n */\nconst MAX_REAUTH_TRIES = 8;\n\nconst PERSIST_IDLE_TIMEOUT_MS = 1000;\nconst REFRESH_IDLE_TIMEOUT_MS = 1000;\n\nconst PERSIST_THROTTLE_MS = 500;\nconst REFRESH_THROTTLE_MS = 500;\n\n/**\n * Opening the database blocks everything Replicache does, including Zero's\n * first connect attempt, so a slow open is worth a warning rather than a\n * debug line.\n */\nconst SLOW_DB_OPEN_THRESHOLD_MS = 50;\n\nconst LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT = 100 * 2 ** 20; // 100 MB\n\nconst RECOVER_MUTATIONS_INTERVAL_MS = 5 * 60 * 1000; // 5 mins\n\nconst noop = () => {\n // noop\n};\n\nconst updateNeededReasonNewClientGroup: UpdateNeededReason = {\n type: 'NewClientGroup',\n} as const;\n\n/** @deprecated Not used any more */\nexport interface MakeSubscriptionsManager {\n (queryInternal: QueryInternal, lc: LogContext): SubscriptionsManager;\n}\n\nexport interface ReplicacheImplOptions {\n /**\n * Defaults to true.\n */\n enableMutationRecovery?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledPersist?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledRefresh?: boolean | undefined;\n\n /**\n * Defaults to `() => true`.\n */\n enableRefresh?: (() => boolean) | undefined;\n\n /**\n * Defaults to true.\n */\n enablePullAndPushInOpen?: boolean | undefined;\n\n /**\n * @deprecated Not used anymore.\n */\n makeSubscriptionsManager?: unknown;\n\n /**\n * Default is `true`. If `false` if an exact match client group\n * is not found, a new client group is always made instead of forking\n * from an existing client group.\n */\n enableClientGroupForking?: boolean | undefined;\n\n /**\n * Callback for when Replicache has deleted clients.\n */\n onClientsDeleted?: OnClientsDeleted | undefined;\n\n /**\n * Internal option used by Zero.\n * Replicache will call this to and, if zero is enabled, will\n * invoke various hooks to allow Zero the keep IVM in sync with Replicache's b-trees.\n */\n zero?: ZeroOption | undefined;\n}\n\nexport class ReplicacheImpl<MD extends MutatorDefs = {}> {\n /** The URL to use when doing a pull request. */\n pullURL: string;\n\n /** The URL to use when doing a push request. */\n pushURL: string;\n\n /** The authorization token used when doing a push request. */\n #auth: string;\n\n /** The name of the Replicache database. Populated by {@link ReplicacheOptions#name}. */\n readonly name: string;\n\n readonly #subscriptions: SubscriptionsManager;\n readonly #mutationRecovery: MutationRecovery | undefined;\n\n /**\n * Client groups gets disabled when the server does not know about it.\n * A disabled client group prevents the client from pushing and pulling.\n */\n isClientGroupDisabled = false;\n\n readonly #kvStoreProvider: StoreProvider;\n\n lastMutationID: number = 0;\n\n /**\n * This is the name Replicache uses for the IndexedDB database where data is\n * stored.\n */\n get idbName(): string {\n return makeIDBName(this.name, this.schemaVersion);\n }\n\n set auth(auth: string) {\n if (this.#zero) {\n this.#zero.auth = auth;\n }\n\n this.#auth = auth;\n }\n\n get auth() {\n return this.#auth;\n }\n\n /** The schema version of the data understood by this application. */\n readonly schemaVersion: string;\n\n get #idbDatabase(): IndexedDBDatabase {\n return {\n name: this.idbName,\n replicacheName: this.name,\n replicacheFormatVersion: FormatVersion.Latest,\n schemaVersion: this.schemaVersion,\n };\n }\n #closed = false;\n #online = true;\n readonly #clientID = makeClientID();\n readonly #ready: Promise<void>;\n readonly #profileIDPromise: Promise<string>;\n readonly #clientGroupIDPromise: Promise<string>;\n readonly #mutatorRegistry: MutatorDefs = {};\n\n /**\n * The mutators that was registered in the constructor.\n */\n readonly mutate: MakeMutators<MD>;\n\n // Number of pushes/pulls at the moment.\n #pushCounter = 0;\n #pullCounter = 0;\n\n #pullConnectionLoop: ConnectionLoop;\n #pushConnectionLoop: ConnectionLoop;\n\n /**\n * The duration between each periodic {@link pull}. Setting this to `null`\n * disables periodic pull completely. Pull will still happen if you call\n * {@link pull} manually.\n */\n pullInterval: number | null;\n\n /**\n * The delay between when a change is made to Replicache and when Replicache\n * attempts to push that change.\n */\n pushDelay: number;\n\n readonly #requestOptions: Required<RequestOptions>;\n\n /**\n * The function to use to pull data from the server.\n */\n puller: Puller;\n\n /**\n * The function to use to push data to the server.\n */\n pusher: Pusher;\n\n readonly memdag: LazyStore;\n readonly perdag: Store;\n readonly #idbDatabases: IDBDatabasesStore;\n readonly #lc: LogContext;\n readonly #zero: ZeroOption | undefined;\n\n readonly #closeAbortController = new AbortController();\n\n readonly #persistLock = new Lock();\n readonly #enableScheduledPersist: boolean;\n readonly #enableScheduledRefresh: boolean;\n readonly #enableRefresh: () => boolean;\n readonly #enablePullAndPushInOpen: boolean;\n #persistScheduler = new ProcessScheduler(\n () => this.persist(),\n PERSIST_IDLE_TIMEOUT_MS,\n PERSIST_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n readonly #onPersist: OnPersist;\n #refreshScheduler = new ProcessScheduler(\n () => this.refresh(),\n REFRESH_IDLE_TIMEOUT_MS,\n REFRESH_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n\n /**\n * The options used to control the {@link pull} and push request behavior. This\n * object is live so changes to it will affect the next pull or push call.\n */\n get requestOptions(): Required<RequestOptions> {\n return this.#requestOptions;\n }\n\n /**\n * `onSync(true)` is called when Replicache transitions from no push or pull\n * happening to at least one happening. `onSync(false)` is called in the\n * opposite case: when Replicache transitions from at least one push or pull\n * happening to none happening.\n *\n * This can be used in a React like app by doing something like the following:\n *\n * ```js\n * const [syncing, setSyncing] = useState(false);\n * useEffect(() => {\n * rep.onSync = setSyncing;\n * }, [rep]);\n * ```\n */\n onSync: ((syncing: boolean) => void) | null = null;\n\n /**\n * `onClientStateNotFound` is called when the persistent client has been\n * garbage collected. This can happen if the client has no pending mutations\n * and has not been used for a while.\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically.\n */\n onClientStateNotFound: (() => void) | null = reload;\n\n /**\n * `onUpdateNeeded` is called when a code update is needed.\n *\n * A code update can be needed because:\n * - the server no longer supports the {@link pushVersion},\n * {@link pullVersion} or {@link schemaVersion} of the current code.\n * - a new Replicache client has created a new client group, because its code\n * has different mutators, indexes, schema version and/or format version\n * from this Replicache client. This is likely due to the new client having\n * newer code. A code update is needed to be able to locally sync with this\n * new Replicache client (i.e. to sync while offline, the clients can still\n * sync with each other via the server).\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically. You may want to provide your own function to\n * display a toast to inform the end user there is a new version of your app\n * available and prompting them to refresh.\n */\n onUpdateNeeded: ((reason: UpdateNeededReason) => void) | null = reload;\n\n /**\n * This gets called when we get an HTTP unauthorized (401) response from the\n * push or pull endpoint. Set this to a function that will ask your user to\n * reauthenticate.\n */\n getAuth: (() => MaybePromise<string | null | undefined>) | null | undefined =\n null;\n\n // These three are used for testing\n onPushInvoked = () => undefined;\n onBeginPull = () => undefined;\n onRecoverMutations = (r: Promise<boolean>) => r;\n\n constructor(\n options: ReplicacheOptions<MD>,\n implOptions: ReplicacheImplOptions = {},\n ) {\n validateOptions(options);\n const {\n name,\n logLevel = 'info',\n logSinks = [consoleLogSink],\n pullURL = '',\n auth,\n pushDelay = 10,\n pushURL = '',\n schemaVersion = '',\n pullInterval = 60000,\n mutators = {} as MD,\n requestOptions = {},\n puller,\n pusher,\n indexes = {},\n clientMaxAgeMs = CLIENT_MAX_INACTIVE_TIME,\n } = options;\n const {\n enableMutationRecovery = true,\n enableScheduledPersist = true,\n enableScheduledRefresh = true,\n enableRefresh = () => true,\n enablePullAndPushInOpen = true,\n enableClientGroupForking = true,\n onClientsDeleted = () => promiseVoid,\n } = implOptions;\n this.#zero = implOptions.zero;\n this.#auth = auth ?? '';\n this.pullURL = pullURL;\n this.pushURL = pushURL;\n this.name = name;\n this.schemaVersion = schemaVersion;\n this.pullInterval = pullInterval;\n this.pushDelay = pushDelay;\n this.puller = puller ?? getDefaultPuller(this);\n this.pusher = pusher ?? getDefaultPusher(this);\n\n this.#enableScheduledPersist = enableScheduledPersist;\n this.#enableScheduledRefresh = enableScheduledRefresh;\n this.#enableRefresh = enableRefresh;\n this.#enablePullAndPushInOpen = enablePullAndPushInOpen;\n\n this.#lc = createLogContext(logLevel, logSinks, {name});\n this.#lc.debug?.('Constructing Replicache', {\n name,\n 'replicache version': version,\n });\n\n this.#subscriptions = new SubscriptionsManagerImpl(\n this.#queryInternal,\n this.#lc,\n this.#closeAbortController.signal,\n );\n\n const kvStoreProvider = getKVStoreProvider(this.#lc, options.kvStore);\n this.#kvStoreProvider = kvStoreProvider;\n\n const perKVStore = kvStoreProvider.create(this.idbName);\n\n this.#idbDatabases = new IDBDatabasesStore(kvStoreProvider.create);\n this.perdag = new StoreImpl(perKVStore, newRandomHash, assertHash);\n this.memdag = new LazyStore(\n this.perdag,\n LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT,\n newRandomHash,\n assertHash,\n );\n\n // Use a promise-resolve pair so that we have a promise to use even before\n // we call the Open RPC.\n const readyResolver = resolver<void>();\n this.#ready = readyResolver.promise;\n\n const {minDelayMs = MIN_DELAY_MS, maxDelayMs = MAX_DELAY_MS} =\n requestOptions;\n this.#requestOptions = {maxDelayMs, minDelayMs};\n\n const visibilityWatcher = getDocumentVisibilityWatcher(\n getBrowserGlobal('document'),\n 0,\n this.#closeAbortController.signal,\n );\n\n this.#pullConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PULL'),\n new PullDelegate(this, () => this.#invokePull()),\n visibilityWatcher,\n );\n\n this.#pushConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PUSH'),\n new PushDelegate(this, () => this.#invokePush()),\n );\n\n this.mutate = this.#registerMutators(mutators);\n\n const profileIDResolver = resolver<string>();\n this.#profileIDPromise = profileIDResolver.promise;\n const clientGroupIDResolver = resolver<string>();\n this.#clientGroupIDPromise = clientGroupIDResolver.promise;\n\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n this.#mutationRecovery = new MutationRecovery({\n delegate: this,\n lc: this.#lc,\n enableMutationRecovery,\n wrapInOnlineCheck: this.#wrapInOnlineCheck.bind(this),\n wrapInReauthRetries: this.#wrapInReauthRetries.bind(this),\n isPullDisabled: this.#isPullDisabled.bind(this),\n isPushDisabled: this.#isPushDisabled.bind(this),\n clientGroupIDPromise: this.#clientGroupIDPromise,\n });\n }\n\n this.#onPersist = initOnPersistChannel(\n this.name,\n this.#closeAbortController.signal,\n persistInfo => {\n void this.#handlePersist(persistInfo);\n },\n );\n\n void this.#open(\n indexes,\n enableClientGroupForking,\n enableMutationRecovery,\n clientMaxAgeMs,\n profileIDResolver.resolve,\n clientGroupIDResolver.resolve,\n readyResolver.resolve,\n onClientsDeleted,\n );\n }\n\n async #open(\n indexes: IndexDefinitions,\n enableClientGroupForking: boolean,\n enableMutationRecovery: boolean,\n clientMaxAgeMs: number,\n profileIDResolver: (profileID: string) => void,\n resolveClientGroupID: (clientGroupID: ClientGroupID) => void,\n resolveReady: () => void,\n onClientsDeleted: OnClientsDeleted,\n ): Promise<void> {\n const {clientID} = this;\n // Everything up to the head write is what it takes to have a usable\n // database, including waiting out a previous instance of the same name.\n // The timer stops before the replica is loaded into Zero's IVM sources,\n // which is separate work and usually the larger of the two: a number that\n // spanned both would report a slow hydration as a slow disk.\n const openStart = performance.now();\n // If we are currently closing a Replicache instance with the same name,\n // wait for it to finish closing.\n await closingInstances.get(this.name);\n await this.#idbDatabases.getProfileID().then(profileIDResolver);\n await this.#idbDatabases.putDatabase(this.#idbDatabase);\n const [client, headHash, , isNewClientGroup] = await initClientV6(\n clientID,\n this.#lc,\n this.perdag,\n Object.keys(this.#mutatorRegistry),\n indexes,\n FormatVersion.Latest,\n enableClientGroupForking,\n );\n\n resolveClientGroupID(client.clientGroupID);\n await withWrite(this.memdag, write =>\n write.setHead(DEFAULT_HEAD_NAME, headHash),\n );\n\n // Now we have a profileID, a clientID, a clientGroupID and DB!\n const dbOpenMs = performance.now() - openStart;\n if (dbOpenMs > SLOW_DB_OPEN_THRESHOLD_MS) {\n this.#lc.warn?.(`Opening the database took ${Math.round(dbOpenMs)}ms`, {\n name: this.idbName,\n });\n } else {\n this.#lc.debug?.('Opened the database in', Math.round(dbOpenMs), 'ms');\n }\n\n await this.#zero?.init(headHash, this.memdag);\n resolveReady();\n\n if (this.#enablePullAndPushInOpen) {\n this.pull().catch(noop);\n this.push().catch(noop);\n }\n\n const {signal} = this.#closeAbortController;\n\n startHeartbeats(\n clientID,\n this.perdag,\n () => {\n this.#clientStateNotFoundOnClient(clientID);\n },\n HEARTBEAT_INTERVAL,\n this.#lc,\n signal,\n );\n initClientGC(\n clientID,\n this.perdag,\n clientMaxAgeMs,\n GC_INTERVAL,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initCollectIDBDatabases(\n this.#idbDatabases,\n this.#kvStoreProvider,\n COLLECT_IDB_INTERVAL,\n INITIAL_COLLECT_IDB_DELAY,\n 2 * clientMaxAgeMs,\n enableMutationRecovery,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initClientGroupGC(this.perdag, enableMutationRecovery, this.#lc, signal);\n initNewClientChannel(\n this.name,\n this.idbName,\n signal,\n client.clientGroupID,\n isNewClientGroup,\n () => {\n this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);\n },\n this.perdag,\n );\n\n setIntervalWithSignal(\n () => this.recoverMutations(),\n RECOVER_MUTATIONS_INTERVAL_MS,\n signal,\n );\n void this.recoverMutations();\n\n getBrowserGlobal('document')?.addEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n }\n\n #onVisibilityChange = async () => {\n if (this.#closed) {\n return;\n }\n\n // In case of running in a worker, we don't have a document.\n if (getBrowserGlobal('document')?.visibilityState !== 'visible') {\n return;\n }\n\n await this.#checkForClientStateNotFoundAndCallHandler();\n };\n\n async #checkForClientStateNotFoundAndCallHandler(): Promise<boolean> {\n const {clientID} = this;\n const hasClientState = await withRead(this.perdag, read =>\n persistHasClientState(clientID, read),\n );\n if (!hasClientState) {\n this.#clientStateNotFoundOnClient(clientID);\n }\n return !hasClientState;\n }\n\n /**\n * The browser profile ID for this browser profile. Every instance of Replicache\n * browser-profile-wide shares the same profile ID.\n */\n get profileID(): Promise<string> {\n return this.#profileIDPromise;\n }\n\n /**\n * The client ID for this instance of Replicache. Each instance of Replicache\n * gets a unique client ID.\n */\n get clientID(): string {\n return this.#clientID;\n }\n\n /**\n * The client group ID for this instance of Replicache. Instances of\n * Replicache will have the same client group ID if and only if they have\n * the same name, mutators, indexes, schema version, format version, and\n * browser profile.\n */\n get clientGroupID(): Promise<string> {\n return this.#clientGroupIDPromise;\n }\n\n /**\n * `onOnlineChange` is called when the {@link online} property changes. See\n * {@link online} for more details.\n */\n onOnlineChange: ((online: boolean) => void) | null = null;\n\n /**\n * A rough heuristic for whether the client is currently online. Note that\n * there is no way to know for certain whether a client is online - the next\n * request can always fail. This property returns true if the last sync attempt succeeded,\n * and false otherwise.\n */\n get online(): boolean {\n return this.#online;\n }\n\n /**\n * Whether the Replicache database has been closed. Once Replicache has been\n * closed it no longer syncs and you can no longer read or write data out of\n * it. After it has been closed it is pretty much useless and should not be\n * used any more.\n */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Closes this Replicache instance.\n *\n * When closed all subscriptions end and no more read or writes are allowed.\n */\n async close(): Promise<void> {\n this.#closed = true;\n const {promise, resolve} = resolver();\n closingInstances.set(this.name, promise);\n\n this.#closeAbortController.abort();\n\n getBrowserGlobal('document')?.removeEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n\n await this.#ready;\n const closingPromises = [\n this.memdag.close(),\n this.perdag.close(),\n this.#idbDatabases.close(),\n ];\n\n this.#pullConnectionLoop.close();\n this.#pushConnectionLoop.close();\n\n this.#subscriptions.clear();\n\n await Promise.all(closingPromises);\n closingInstances.delete(this.name);\n resolve();\n }\n\n async maybeEndPull(syncHead: Hash, requestID: string): Promise<void> {\n for (;;) {\n if (this.#closed) {\n return;\n }\n\n await this.#ready;\n const {clientID} = this;\n const lc = this.#lc\n .withContext('maybeEndPull')\n .withContext('requestID', requestID);\n const {replayMutations, diffs, oldMainHead, mainHead} =\n await maybeEndPull<LocalMeta>(\n this.memdag,\n lc,\n syncHead,\n clientID,\n this.#subscriptions,\n FormatVersion.Latest,\n );\n\n if (!replayMutations || replayMutations.length === 0) {\n // All done.\n this.#zero?.advance(oldMainHead, mainHead, diffs.get('') ?? []);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return;\n }\n\n // Replay.\n const zeroData = await this.#zero?.getTxData?.(syncHead);\n for (const mutation of replayMutations) {\n // TODO(greg): I'm not sure why this was in Replicache#_mutate...\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n const {meta} = mutation;\n syncHead = await withWriteNoImplicitCommit(this.memdag, dagWrite =>\n rebaseMutationAndCommit(\n mutation,\n dagWrite,\n syncHead,\n SYNC_HEAD_NAME,\n this.#mutatorRegistry,\n lc,\n isLocalMetaDD31(meta) ? meta.clientID : clientID,\n FormatVersion.Latest,\n zeroData,\n ),\n );\n }\n }\n }\n\n #invokePull(): Promise<boolean> {\n if (this.#isPullDisabled()) {\n return Promise.resolve(true);\n }\n\n return this.#wrapInOnlineCheck(async () => {\n try {\n this.#changeSyncCounters(0, 1);\n const {syncHead, requestID, ok} = await this.beginPull();\n if (!ok) {\n return false;\n }\n if (syncHead !== emptyHash) {\n await this.maybeEndPull(syncHead, requestID);\n }\n } catch (e) {\n throw await this.#convertToClientStateNotFoundError(e);\n } finally {\n this.#changeSyncCounters(0, -1);\n }\n return true;\n }, 'Pull');\n }\n\n #isPullDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pullURL === '' && isDefaultPuller(this.puller))\n );\n }\n\n async #wrapInOnlineCheck(\n f: () => Promise<boolean>,\n name: string,\n ): Promise<boolean> {\n let online = true;\n\n try {\n return await f();\n } catch (e) {\n // The error paths of beginPull and maybeEndPull need to be reworked.\n //\n // We want to distinguish between:\n // a) network requests failed -- we're offline basically\n // b) sync was aborted because one's already in progress\n // c) oh noes - something unexpected happened\n //\n // Right now, all of these come out as errors. We distinguish (b) with a\n // hacky string search. (a) and (c) are not distinguishable currently\n // because repc doesn't provide sufficient information, so we treat all\n // errors that aren't (b) as (a).\n if (e instanceof PushError || e instanceof PullError) {\n online = false;\n this.#lc.debug?.(`${name} threw:\\n`, e, '\\nwith cause:\\n', e.causedBy);\n } else if (e instanceof ReportError) {\n this.#lc.error?.(e);\n } else {\n this.#lc.info?.(`${name} threw:\\n`, e);\n }\n return false;\n } finally {\n if (this.#online !== online) {\n this.#online = online;\n this.onOnlineChange?.(online);\n if (online) {\n void this.recoverMutations();\n }\n }\n }\n }\n\n async #wrapInReauthRetries<R>(\n f: (\n requestID: string,\n requestLc: LogContext,\n ) => Promise<{\n httpRequestInfo: HTTPRequestInfo | undefined;\n result: R;\n }>,\n verb: string,\n lc: LogContext,\n preAuth: () => MaybePromise<void> = noop,\n postAuth: () => MaybePromise<void> = noop,\n ): Promise<{\n result: R;\n authFailure: boolean;\n }> {\n const {clientID} = this;\n let reauthAttempts = 0;\n let lastResult;\n lc = lc.withContext(verb);\n do {\n const requestID = newRequestID(clientID);\n const requestLc = lc.withContext('requestID', requestID);\n const {httpRequestInfo, result} = await f(requestID, requestLc);\n lastResult = result;\n if (!httpRequestInfo) {\n return {\n result,\n authFailure: false,\n };\n }\n const {errorMessage, httpStatusCode} = httpRequestInfo;\n\n if (errorMessage || httpStatusCode !== 200) {\n // TODO(arv): Maybe we should not log the server URL when the error comes\n // from a Pusher/Puller?\n requestLc.error?.(\n `Got a non 200 response doing ${verb}: ${httpStatusCode}` +\n (errorMessage ? `: ${errorMessage}` : ''),\n );\n }\n if (httpStatusCode !== httpStatusUnauthorized) {\n return {\n result,\n authFailure: false,\n };\n }\n if (!this.getAuth) {\n return {\n result,\n authFailure: true,\n };\n }\n let auth;\n try {\n await preAuth();\n auth = await this.getAuth();\n } finally {\n await postAuth();\n }\n if (auth === null || auth === undefined) {\n return {\n result,\n authFailure: true,\n };\n }\n this.auth = auth;\n reauthAttempts++;\n } while (reauthAttempts < MAX_REAUTH_TRIES);\n lc.info?.('Tried to reauthenticate too many times');\n return {\n result: lastResult,\n authFailure: true,\n };\n }\n\n #isPushDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pushURL === '' && isDefaultPusher(this.pusher))\n );\n }\n\n async #invokePush(): Promise<boolean> {\n if (TESTING) {\n this.onPushInvoked();\n }\n if (this.#isPushDisabled()) {\n return true;\n }\n\n await this.#ready;\n const profileID = await this.#profileIDPromise;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n return this.#wrapInOnlineCheck(async () => {\n const {result: pusherResult} = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n try {\n this.#changeSyncCounters(1, 0);\n const pusherResult = await push(\n requestID,\n this.memdag,\n requestLc,\n profileID,\n clientGroupID,\n clientID,\n this.pusher,\n this.schemaVersion,\n PUSH_VERSION_DD31,\n );\n return {\n result: pusherResult,\n httpRequestInfo: pusherResult?.httpRequestInfo,\n };\n } finally {\n this.#changeSyncCounters(-1, 0);\n }\n },\n 'push',\n this.#lc,\n );\n\n if (pusherResult === undefined) {\n // No pending mutations.\n return true;\n }\n\n const {response, httpRequestInfo} = pusherResult;\n\n if (isVersionNotSupportedResponse(response)) {\n this.#handleVersionNotSupportedResponse(response);\n } else if (isClientStateNotFoundResponse(response)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n // No pushResponse means we didn't do a push because there were no\n // pending mutations.\n return httpRequestInfo.httpStatusCode === 200;\n }, 'Push');\n }\n\n #handleVersionNotSupportedResponse(response: VersionNotSupportedResponse) {\n const reason: UpdateNeededReason = {\n type: response.error,\n };\n if (response.versionType) {\n reason.versionType = response.versionType;\n }\n this.#fireOnUpdateNeeded(reason);\n }\n\n /**\n * Push pushes pending changes to the {@link pushURL}.\n *\n * You do not usually need to manually call push. If {@link pushDelay} is\n * non-zero (which it is by default) pushes happen automatically shortly after\n * mutations.\n *\n * If the server endpoint fails push will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, push will happen immediately and ignore\n * {@link pushDelay}, {@link RequestOptions.minDelayMs} as well as the\n * exponential backoff in case of errors.\n * @returns A promise that resolves when the next push completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n push({now = false} = {}): Promise<void> {\n return throwIfError(this.#pushConnectionLoop.send(now));\n }\n\n /**\n * Pull pulls changes from the {@link pullURL}. If there are any changes local\n * changes will get replayed on top of the new server state.\n *\n * If the server endpoint fails pull will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, pull will happen immediately and ignore\n * {@link RequestOptions.minDelayMs} as well as the exponential backoff in\n * case of errors.\n * @returns A promise that resolves when the next pull completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n pull({now = false} = {}): Promise<void> {\n return throwIfError(this.#pullConnectionLoop.send(now));\n }\n\n /**\n * Applies an update from the server to Replicache.\n * Throws an error if cookie does not match. In that case the server thinks\n * this client has a different cookie than it does; the caller should disconnect\n * from the server and re-register, which transmits the cookie the client actually\n * has.\n *\n * @experimental This method is under development and its semantics will change.\n */\n async poke(poke: PokeInternal): Promise<void> {\n await this.#ready;\n // TODO(MP) Previously we created a request ID here and included it with the\n // PullRequest to the server so we could tie events across client and server\n // together. Since the direction is now reversed, creating and adding a request ID\n // here is kind of silly. We should consider creating the request ID\n // on the *server* and passing it down in the poke for inclusion here in the log\n // context\n const {clientID} = this;\n const requestID = newRequestID(clientID);\n const lc = this.#lc\n .withContext('handlePullResponse')\n .withContext('requestID', requestID);\n\n const {pullResponse} = poke;\n\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n return;\n }\n\n if (isClientStateNotFoundResponse(pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n return;\n }\n\n const result = await handlePullResponseV1(\n lc,\n this.memdag,\n deepFreeze(poke.baseCookie),\n pullResponse,\n clientID,\n FormatVersion.Latest,\n );\n\n switch (result.type) {\n case HandlePullResponseResultEnum.Applied:\n await this.maybeEndPull(result.syncHead, requestID);\n break;\n case HandlePullResponseResultEnum.CookieMismatch:\n throw new Error(\n 'unexpected base cookie for poke: ' + JSON.stringify(poke),\n );\n case HandlePullResponseResultEnum.NoOp:\n break;\n }\n }\n\n async beginPull(): Promise<BeginPullResult> {\n if (TESTING) {\n this.onBeginPull();\n }\n await this.#ready;\n const profileID = await this.profileID;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n const {\n result: {beginPullResponse, requestID},\n } = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n const beginPullResponse = await beginPullV1(\n profileID,\n clientID,\n clientGroupID,\n this.schemaVersion,\n this.puller,\n requestID,\n this.memdag,\n FormatVersion.Latest,\n requestLc,\n );\n return {\n result: {beginPullResponse, requestID},\n httpRequestInfo: beginPullResponse.httpRequestInfo,\n };\n },\n 'pull',\n this.#lc,\n () => this.#changeSyncCounters(0, -1),\n () => this.#changeSyncCounters(0, 1),\n );\n\n const {pullResponse} = beginPullResponse;\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n } else if (isClientStateNotFoundResponse(beginPullResponse.pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n const {syncHead, httpRequestInfo} = beginPullResponse;\n return {requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200};\n }\n\n persist(): Promise<void> {\n // Prevent multiple persist calls from running at the same time.\n return this.#persistLock.withLock(async () => {\n const {clientID} = this;\n await this.#ready;\n if (this.#closed) {\n return;\n }\n try {\n await persistDD31(\n this.#lc,\n clientID,\n this.memdag,\n this.perdag,\n this.#mutatorRegistry,\n () => this.#closed,\n FormatVersion.Latest,\n this.#zero?.getTxData,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception persisting during close', e);\n } else {\n throw e;\n }\n }\n\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.#onPersist({clientID, clientGroupID});\n });\n }\n\n async refresh(): Promise<void> {\n await this.#ready;\n const {clientID} = this;\n if (this.#closed || !this.#enableRefresh()) {\n return;\n }\n let refreshResult: Awaited<ReturnType<typeof refresh>>;\n try {\n refreshResult = await refresh(\n this.#lc,\n this.memdag,\n this.perdag,\n clientID,\n this.#mutatorRegistry,\n this.#subscriptions,\n () => this.closed,\n FormatVersion.Latest,\n this.#zero,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception refreshing during close', e);\n } else {\n throw e;\n }\n }\n if (refreshResult !== undefined) {\n await this.#subscriptions.fire(refreshResult.diffs);\n }\n }\n\n #fireOnClientStateNotFound() {\n this.onClientStateNotFound?.();\n }\n\n #clientStateNotFoundOnClient(clientID: ClientID) {\n this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);\n this.#fireOnClientStateNotFound();\n }\n\n async #clientStateNotFoundOnServer() {\n const clientGroupID = await this.#clientGroupIDPromise;\n this.#lc.error?.(\n `Client state not found on server, clientGroupID: ${clientGroupID}`,\n );\n await this.disableClientGroup();\n this.#fireOnClientStateNotFound();\n }\n\n async disableClientGroup(): Promise<void> {\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.isClientGroupDisabled = true;\n await withWrite(this.perdag, dagWrite =>\n disableClientGroup(clientGroupID, dagWrite),\n );\n }\n\n #fireOnUpdateNeeded(reason: UpdateNeededReason) {\n this.#lc.debug?.(`Update needed, reason: ${reason}`);\n this.onUpdateNeeded?.(reason);\n }\n\n async #schedulePersist(): Promise<void> {\n if (!this.#enableScheduledPersist) {\n return;\n }\n await this.#schedule('persist', this.#persistScheduler);\n }\n\n async #handlePersist(persistInfo: PersistInfo): Promise<void> {\n this.#lc.debug?.('Handling persist', persistInfo);\n const clientGroupID = await this.#clientGroupIDPromise;\n if (persistInfo.clientGroupID === clientGroupID) {\n void this.#scheduleRefresh();\n }\n }\n\n async #scheduleRefresh(): Promise<void> {\n if (!this.#enableScheduledRefresh) {\n return;\n }\n await this.#schedule('refresh from storage', this.#refreshScheduler);\n }\n\n async #schedule(name: string, scheduler: ProcessScheduler): Promise<void> {\n try {\n await scheduler.schedule();\n } catch (e) {\n if (e instanceof AbortError) {\n this.#lc.debug?.(`Scheduled ${name} did not complete before close.`);\n } else {\n this.#lc.error?.(`Error during ${name}`, e);\n }\n }\n }\n\n /**\n * Runs a refresh as soon as possible through the refresh scheduler.\n */\n runRefresh(): Promise<void> {\n return this.#refreshScheduler.run();\n }\n\n #changeSyncCounters(pushDelta: 0, pullDelta: 1 | -1): void;\n #changeSyncCounters(pushDelta: 1 | -1, pullDelta: 0): void;\n #changeSyncCounters(pushDelta: number, pullDelta: number): void {\n this.#pushCounter += pushDelta;\n this.#pullCounter += pullDelta;\n const delta = pushDelta + pullDelta;\n const counter = this.#pushCounter + this.#pullCounter;\n if ((delta === 1 && counter === 1) || counter === 0) {\n const syncing = counter > 0;\n // Run in a new microtask.\n void Promise.resolve().then(() => this.onSync?.(syncing));\n }\n }\n\n /**\n * Subscribe to the result of a {@link query}. The `body` function is\n * evaluated once and its results are returned via `onData`.\n *\n * Thereafter, each time the the result of `body` changes, `onData` is fired\n * again with the new result.\n *\n * `subscribe()` goes to significant effort to avoid extraneous work\n * re-evaluating subscriptions:\n *\n * 1. subscribe tracks the keys that `body` accesses each time it runs. `body`\n * is only re-evaluated when those keys change.\n * 2. subscribe only re-fires `onData` in the case that a result changes by\n * way of the `isEqual` option which defaults to doing a deep JSON value\n * equality check.\n *\n * Because of (1), `body` must be a pure function of the data in Replicache.\n * `body` must not access anything other than the `tx` parameter passed to it.\n *\n * Although subscribe is as efficient as it can be, it is somewhat constrained\n * by the goal of returning an arbitrary computation of the cache. For even\n * better performance (but worse dx), see {@link experimentalWatch}.\n *\n * If an error occurs in the `body` the `onError` function is called if\n * present. Otherwise, the error is logged at log level 'error'.\n *\n * To cancel the subscription, call the returned function.\n *\n * @param body The function to evaluate to get the value to pass into\n * `onData`.\n * @param options Options is either a function or an object. If it is a\n * function it is equivalent to passing it as the `onData` property of an\n * object.\n */\n subscribe<R>(\n body: (tx: ReadTransaction) => Promise<R>,\n options: SubscribeOptions<R> | ((result: R) => void),\n ): () => void {\n if (typeof options === 'function') {\n options = {onData: options};\n }\n\n const {onData, onError, onDone, isEqual} = options;\n return this.#subscriptions.add(\n new SubscriptionImpl(body, onData, onError, onDone, isEqual),\n );\n }\n\n /**\n * Watches Replicache for changes.\n *\n * The `callback` gets called whenever the underlying data changes and the\n * `key` changes matches the `prefix` of {@link ExperimentalWatchIndexOptions} or\n * {@link ExperimentalWatchNoIndexOptions} if present. If a change\n * occurs to the data but the change does not impact the key space the\n * callback is not called. In other words, the callback is never called with\n * an empty diff.\n *\n * This gets called after commit (a mutation or a rebase).\n *\n * @experimental This method is under development and its semantics will\n * change.\n */\n experimentalWatch(callback: WatchNoIndexCallback): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void {\n return this.#subscriptions.add(\n new WatchSubscription(callback as WatchCallback, options),\n );\n }\n\n /**\n * Query is used for read transactions. It is recommended to use transactions\n * to ensure you get a consistent view across multiple calls to `get`, `has`\n * and `scan`.\n */\n query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R> {\n return this.#queryInternal(body);\n }\n\n get cookie(): Promise<Cookie> {\n return this.#ready.then(() =>\n withRead(this.memdag, async dagRead => {\n const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);\n if (!mainHeadHash) {\n throw new Error('Internal no main head found');\n }\n const baseSnapshot = await baseSnapshotFromHash(mainHeadHash, dagRead);\n const baseSnapshotMeta = baseSnapshot.meta;\n const cookie = baseSnapshotMeta.cookieJSON;\n assertCookie(cookie);\n return cookie;\n }),\n );\n }\n\n #queryInternal: QueryInternal = async body => {\n await this.#ready;\n const {clientID} = this;\n return withRead(this.memdag, async dagRead => {\n try {\n const dbRead = await readFromDefaultHead(dagRead, FormatVersion.Latest);\n const tx = new ReadTransactionImpl(clientID, dbRead, this.#lc);\n return await body(tx);\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n };\n\n #register<Return extends ReadonlyJSONValue | void, Args extends JSONValue>(\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: Args) => MaybePromise<Return>,\n ): (\n args?: Args,\n ) => Promise<Return> | {client: Promise<Return>; server: Promise<unknown>} {\n this.#mutatorRegistry[name] = mutatorImpl as (\n tx: WriteTransaction,\n args: JSONValue | undefined,\n ) => Promise<void | JSONValue>;\n\n return (\n args?: Args,\n ):\n | Promise<Return>\n | {client: Promise<Return>; server: Promise<unknown>} => {\n // DO NOT track CRUD mutations as they do not receive responses from\n // the server.\n const trackingData =\n name === '_zero_crud' ? undefined : this.#zero?.trackMutation();\n\n const result = this.#mutate(\n trackingData,\n name,\n mutatorImpl,\n args,\n performance.now(),\n );\n\n if (trackingData) {\n return {\n client: result,\n server: trackingData.serverPromise,\n };\n }\n\n return result;\n };\n }\n\n #registerMutators<\n M extends {\n [key: string]: (\n tx: WriteTransaction,\n args?: ReadonlyJSONValue,\n ) => MutatorReturn;\n },\n >(regs: M): MakeMutators<M> {\n type Mut = MakeMutators<M>;\n const rv: Partial<Mut> = Object.create(null);\n for (const k in regs) {\n rv[k] = this.#register(k, regs[k]) as MakeMutator<M[typeof k]>;\n }\n return rv as Mut;\n }\n\n async #mutate<\n R extends ReadonlyJSONValue | void,\n A extends ReadonlyJSONValue,\n >(\n trackingData: MutationTrackingData | undefined,\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: A) => MaybePromise<R>,\n args: A | undefined,\n timestamp: number,\n ): Promise<R> {\n const frozenArgs = deepFreeze(args ?? null);\n\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n\n await this.#ready;\n const {clientID} = this;\n return withWriteNoImplicitCommit(this.memdag, async dagWrite => {\n try {\n let result: R;\n let newHead: Hash;\n let diffs: DiffsMap;\n let headHash: Hash;\n try {\n headHash = await mustGetHeadHash(DEFAULT_HEAD_NAME, dagWrite);\n const originalHash = null;\n\n const dbWrite = await newWriteLocal(\n headHash,\n name,\n frozenArgs,\n originalHash,\n dagWrite,\n timestamp,\n clientID,\n FormatVersion.Latest,\n );\n\n const mutationID = await dbWrite.getMutationID();\n const tx = new WriteTransactionImpl(\n clientID,\n mutationID,\n 'initial',\n await this.#zero?.getTxData(headHash, {\n openLazyRead: dagWrite,\n }),\n dbWrite,\n this.#lc,\n );\n\n if (trackingData) {\n this.#zero?.mutationIDAssigned(\n trackingData.ephemeralID,\n mutationID,\n );\n }\n\n result = await mutatorImpl(tx, args);\n\n throwIfClosed(dbWrite);\n const lastMutationID = await dbWrite.getMutationID();\n [newHead, diffs] = await dbWrite.commitWithDiffs(\n DEFAULT_HEAD_NAME,\n this.#subscriptions,\n );\n\n // Update this after the commit in case the commit fails.\n this.lastMutationID = lastMutationID;\n } catch (e) {\n // If we threw before we could persist the mutation\n // then we need to reject the mutation.\n if (trackingData) {\n this.#zero?.rejectMutation(trackingData.ephemeralID, e);\n }\n throw e;\n }\n\n this.#zero?.advance(headHash, newHead, diffs.get('') ?? []);\n\n // Send is not supposed to reject\n this.#pushConnectionLoop.send(false).catch(() => void 0);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return result;\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n }\n\n /**\n * In the case we get a ChunkNotFoundError we check if the client got garbage\n * collected and if so change the error to a ClientStateNotFoundError instead\n */\n async #convertToClientStateNotFoundError(ex: unknown): Promise<unknown> {\n if (\n ex instanceof ChunkNotFoundError &&\n (await this.#checkForClientStateNotFoundAndCallHandler())\n ) {\n return new ClientStateNotFoundError(this.clientID);\n }\n\n return ex;\n }\n\n recoverMutations(): Promise<boolean> | void {\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n // oxlint-disable-next-line no-non-null-assertion\n const result = this.#mutationRecovery!.recoverMutations(\n this.#ready,\n this.perdag,\n this.#idbDatabase,\n this.#idbDatabases,\n this.#kvStoreProvider.create,\n );\n if (TESTING) {\n void this.onRecoverMutations(result);\n }\n return result;\n }\n }\n\n /**\n * List of pending mutations. The order of this is from oldest to newest.\n *\n * Gives a list of local mutations that have `mutationID` >\n * `syncHead.mutationID` that exists on the main client group.\n *\n * @experimental This method is experimental and may change in the future.\n */\n experimentalPendingMutations(): Promise<readonly PendingMutation[]> {\n return withRead(this.memdag, pendingMutationsForAPI);\n }\n}\n\n// This map is used to keep track of closing instances of Replicache. When an\n// instance is opening we wait for any currently closing instances.\nconst closingInstances: Map<string, Promise<unknown>> = new Map();\n\nasync function throwIfError(p: Promise<undefined | {error: unknown}>) {\n const res = await p;\n if (res) {\n throw res.error;\n }\n}\n\nfunction reload(): void {\n if (typeof location !== 'undefined') {\n location.reload();\n }\n}\n\nfunction validateOptions<MD extends MutatorDefs>(\n options: ReplicacheOptions<MD>,\n): void {\n const {name, clientMaxAgeMs} = options;\n if (typeof name !== 'string' || !name) {\n throw new TypeError('name is required and must be non-empty');\n }\n\n if (clientMaxAgeMs !== undefined) {\n const min = Math.max(GC_INTERVAL, HEARTBEAT_INTERVAL);\n if (typeof clientMaxAgeMs !== 'number' || clientMaxAgeMs <= min) {\n throw new TypeError(\n `clientAgeMaxMs must be a number larger than ${min}ms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OAAO,eAAe,aAAa,aAAa,CAAC;KAExD,MAAM;IACR;IAEA,KAAKA,OAAO,QAAQ,UAAU,SAAS,MAAM,IAAI,EAAE,KAAK,CAAC,CAAC;IAG1D,KAAKqB,oBAAoB,KAAK,KAAK,EAAE,YAAY,KAAK,CAAC;IACvD,MAAM,KAAKxB,eAAe,KAAK,KAAK;IACpC,KAAUuC,iBAAiB;IAC3B,OAAO;GACT,SAAS,IAAI;IACX,MAAM,MAAM,KAAKE,mCAAmC,EAAE;GACxD;EACF,CAAC;CACH;;;;;CAMA,MAAMA,mCAAmC,IAA+B;EACtE,IACE,cAAc,sBACb,MAAM,KAAKJ,2CAA2C,GAEvD,OAAO,IAAI,yBAAyB,KAAK,QAAQ;EAGnD,OAAO;CACT;CAEA,mBAA4C,CAe5C;;;;;;;;;CAUA,+BAAoE;EAClE,OAAO,SAAS,KAAK,QAAQ,sBAAsB;CACrD;AACF;AAIA,IAAM,mCAAkD,IAAI,IAAI;AAEhE,eAAe,aAAa,GAA0C;CACpE,MAAM,MAAM,MAAM;CAClB,IAAI,KACF,MAAM,IAAI;AAEd;AAEA,SAAS,SAAe;CACtB,IAAI,OAAO,aAAa,aACtB,SAAS,OAAO;AAEpB;AAEA,SAAS,gBACP,SACM;CACN,MAAM,EAAC,MAAM,mBAAkB;CAC/B,IAAI,OAAO,SAAS,YAAY,CAAC,MAC/B,MAAM,IAAI,UAAU,wCAAwC;CAG9D,IAAI,mBAAmB,KAAA,GAAW;EAChC,MAAM,MAAM,KAAK,IAAI,aAAa,kBAAkB;EACpD,IAAI,OAAO,mBAAmB,YAAY,kBAAkB,KAC1D,MAAM,IAAI,UACR,+CAA+C,IAAI,GACrD;CAEJ;AACF"}
1
+ {"version":3,"file":"replicache-impl.js","names":["#subscriptions","#mutationRecovery","#kvStoreProvider","#zero","#auth","#idbDatabase","#clientID","#ready","#openFailed","#profileIDPromise","#clientGroupIDPromise","#mutatorRegistry","#requestOptions","#idbDatabases","#lc","#closeAbortController","#persistLock","#enableScheduledPersist","#enableScheduledRefresh","#enableRefresh","#enablePullAndPushInOpen","#onPersist","#queryInternal","#onInvalidRefCount","#pullConnectionLoop","#invokePull","#pushConnectionLoop","#invokePush","#registerMutators","#wrapInOnlineCheck","#wrapInReauthRetries","#isPullDisabled","#isPushDisabled","#handlePersist","#open","#clientStateNotFoundOnClient","#fireOnUpdateNeeded","#onVisibilityChange","#closed","#checkForClientStateNotFoundAndCallHandler","#online","#schedulePersist","#changeSyncCounters","#convertToClientStateNotFoundError","#handleVersionNotSupportedResponse","#clientStateNotFoundOnServer","#handleInvalidRefCount","#fireOnClientStateNotFound","#corruptDatabaseRecovery","#dropDatabaseAndFireOnClientStateNotFound","#schedule","#persistScheduler","#scheduleRefresh","#refreshScheduler","#pushCounter","#pullCounter","#mutate","#register"],"sources":["../../../../replicache/src/replicache-impl.ts"],"sourcesContent":["import {Lock} from '@rocicorp/lock';\nimport type {LogContext} from '@rocicorp/logger';\nimport {consoleLogSink} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {AbortError} from '../../shared/src/abort-error.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getBrowserGlobal} from '../../shared/src/browser-env.ts';\nimport {getDocumentVisibilityWatcher} from '../../shared/src/document-visible.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport {PullDelegate, PushDelegate} from './connection-loop-delegates.ts';\nimport {ConnectionLoop, MAX_DELAY_MS, MIN_DELAY_MS} from './connection-loop.ts';\nimport {assertCookie, type Cookie} from './cookies.ts';\nimport {InvalidRefCountError} from './dag/invalid-ref-count-error.ts';\nimport {LazyStore} from './dag/lazy-store.ts';\nimport {StoreImpl} from './dag/store-impl.ts';\nimport {ChunkNotFoundError, mustGetHeadHash, type Store} from './dag/store.ts';\nimport {\n baseSnapshotFromHash,\n DEFAULT_HEAD_NAME,\n isLocalMetaDD31,\n type LocalMeta,\n} from './db/commit.ts';\nimport {readFromDefaultHead} from './db/read.ts';\nimport {rebaseMutationAndCommit} from './db/rebase.ts';\nimport {newWriteLocal} from './db/write.ts';\nimport {\n isClientStateNotFoundResponse,\n isVersionNotSupportedResponse,\n type VersionNotSupportedResponse,\n} from './error-responses.ts';\nimport * as FormatVersion from './format-version-enum.ts';\nimport {deepFreeze} from './frozen-json.ts';\nimport {getDefaultPuller, isDefaultPuller} from './get-default-puller.ts';\nimport {getDefaultPusher, isDefaultPusher} from './get-default-pusher.ts';\nimport {getKVStoreProvider} from './get-kv-store-provider.ts';\nimport {assertHash, emptyHash, type Hash, newRandomHash} from './hash.ts';\nimport type {HTTPRequestInfo} from './http-request-info.ts';\nimport {httpStatusUnauthorized} from './http-status-unauthorized.ts';\nimport type {IndexDefinitions} from './index-defs.ts';\nimport type {StoreProvider} from './kv/store.ts';\nimport {createLogContext} from './log-options.ts';\nimport {makeIDBName} from './make-idb-name.ts';\nimport {MutationRecovery} from './mutation-recovery.ts';\nimport {initNewClientChannel} from './new-client-channel.ts';\nimport {\n initOnPersistChannel,\n type OnPersist,\n type PersistInfo,\n} from './on-persist-channel.ts';\nimport {\n type PendingMutation,\n pendingMutationsForAPI,\n} from './pending-mutations.ts';\nimport {\n CLIENT_MAX_INACTIVE_TIME,\n GC_INTERVAL,\n initClientGC,\n} from './persist/client-gc.ts';\nimport {initClientGroupGC} from './persist/client-group-gc.ts';\nimport {disableClientGroup} from './persist/client-groups.ts';\nimport {\n ClientStateNotFoundError,\n initClientV6,\n type OnClientsDeleted,\n hasClientState as persistHasClientState,\n} from './persist/clients.ts';\nimport {\n COLLECT_IDB_INTERVAL,\n dropDatabaseInternal,\n initCollectIDBDatabases,\n INITIAL_COLLECT_IDB_DELAY,\n} from './persist/collect-idb-databases.ts';\nimport {HEARTBEAT_INTERVAL, startHeartbeats} from './persist/heartbeat.ts';\nimport {\n IDBDatabasesStore,\n type IndexedDBDatabase,\n} from './persist/idb-databases-store.ts';\nimport {makeClientID} from './persist/make-client-id.ts';\nimport {persistDD31} from './persist/persist.ts';\nimport {refresh} from './persist/refresh.ts';\nimport {ProcessScheduler} from './process-scheduler.ts';\nimport type {Puller} from './puller.ts';\nimport {type Pusher, PushError} from './pusher.ts';\nimport type {\n MutationTrackingData,\n ReplicacheOptions,\n ZeroOption,\n} from './replicache-options.ts';\nimport {ReportError} from './report-error.ts';\nimport {setIntervalWithSignal} from './set-interval-with-signal.ts';\nimport {\n type SubscribeOptions,\n SubscriptionImpl,\n type SubscriptionsManager,\n SubscriptionsManagerImpl,\n type WatchCallback,\n type WatchCallbackForOptions,\n type WatchNoIndexCallback,\n type WatchOptions,\n WatchSubscription,\n} from './subscriptions.ts';\nimport type {DiffsMap} from './sync/diff.ts';\nimport * as HandlePullResponseResultEnum from './sync/handle-pull-response-result-type-enum.ts';\nimport type {ClientGroupID, ClientID} from './sync/ids.ts';\nimport {PullError} from './sync/pull-error.ts';\nimport {beginPullV1, handlePullResponseV1, maybeEndPull} from './sync/pull.ts';\nimport {push, PUSH_VERSION_DD31} from './sync/push.ts';\nimport {newRequestID} from './sync/request-id.ts';\nimport {SYNC_HEAD_NAME} from './sync/sync-head-name.ts';\nimport {throwIfClosed} from './transaction-closed-error.ts';\nimport type {ReadTransaction, WriteTransaction} from './transactions.ts';\nimport {ReadTransactionImpl, WriteTransactionImpl} from './transactions.ts';\nimport type {\n BeginPullResult,\n MakeMutator,\n MakeMutators,\n MutatorDefs,\n MutatorReturn,\n PokeInternal,\n QueryInternal,\n RequestOptions,\n UpdateNeededReason,\n} from './types.ts';\nimport {version} from './version.ts';\nimport {\n withRead,\n withWrite,\n withWriteNoImplicitCommit,\n} from './with-transactions.ts';\n\n/**\n * The maximum number of time to call out to getAuth before giving up\n * and throwing an error.\n */\nconst MAX_REAUTH_TRIES = 8;\n\nconst PERSIST_IDLE_TIMEOUT_MS = 1000;\nconst REFRESH_IDLE_TIMEOUT_MS = 1000;\n\nconst PERSIST_THROTTLE_MS = 500;\nconst REFRESH_THROTTLE_MS = 500;\n\n/**\n * Opening the database blocks everything Replicache does, including Zero's\n * first connect attempt, so a slow open is worth a warning rather than a\n * debug line.\n */\nconst SLOW_DB_OPEN_THRESHOLD_MS = 50;\n\nconst LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT = 100 * 2 ** 20; // 100 MB\n\nconst RECOVER_MUTATIONS_INTERVAL_MS = 5 * 60 * 1000; // 5 mins\n\nconst noop = () => {\n // noop\n};\n\nconst updateNeededReasonNewClientGroup: UpdateNeededReason = {\n type: 'NewClientGroup',\n} as const;\n\n/** @deprecated Not used any more */\nexport interface MakeSubscriptionsManager {\n (queryInternal: QueryInternal, lc: LogContext): SubscriptionsManager;\n}\n\nexport interface ReplicacheImplOptions {\n /**\n * Defaults to true.\n */\n enableMutationRecovery?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledPersist?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledRefresh?: boolean | undefined;\n\n /**\n * Defaults to `() => true`.\n */\n enableRefresh?: (() => boolean) | undefined;\n\n /**\n * Defaults to true.\n */\n enablePullAndPushInOpen?: boolean | undefined;\n\n /**\n * @deprecated Not used anymore.\n */\n makeSubscriptionsManager?: unknown;\n\n /**\n * Default is `true`. If `false` if an exact match client group\n * is not found, a new client group is always made instead of forking\n * from an existing client group.\n */\n enableClientGroupForking?: boolean | undefined;\n\n /**\n * Callback for when Replicache has deleted clients.\n */\n onClientsDeleted?: OnClientsDeleted | undefined;\n\n /**\n * Internal option used by Zero.\n * Replicache will call this to and, if zero is enabled, will\n * invoke various hooks to allow Zero the keep IVM in sync with Replicache's b-trees.\n */\n zero?: ZeroOption | undefined;\n}\n\nexport class ReplicacheImpl<MD extends MutatorDefs = {}> {\n /** The URL to use when doing a pull request. */\n pullURL: string;\n\n /** The URL to use when doing a push request. */\n pushURL: string;\n\n /** The authorization token used when doing a push request. */\n #auth: string;\n\n /** The name of the Replicache database. Populated by {@link ReplicacheOptions#name}. */\n readonly name: string;\n\n readonly #subscriptions: SubscriptionsManager;\n readonly #mutationRecovery: MutationRecovery | undefined;\n\n /**\n * Client groups gets disabled when the server does not know about it.\n * A disabled client group prevents the client from pushing and pulling.\n */\n isClientGroupDisabled = false;\n\n readonly #kvStoreProvider: StoreProvider;\n\n lastMutationID: number = 0;\n\n /**\n * This is the name Replicache uses for the IndexedDB database where data is\n * stored.\n */\n get idbName(): string {\n return makeIDBName(this.name, this.schemaVersion);\n }\n\n set auth(auth: string) {\n if (this.#zero) {\n this.#zero.auth = auth;\n }\n\n this.#auth = auth;\n }\n\n get auth() {\n return this.#auth;\n }\n\n /** The schema version of the data understood by this application. */\n readonly schemaVersion: string;\n\n get #idbDatabase(): IndexedDBDatabase {\n return {\n name: this.idbName,\n replicacheName: this.name,\n replicacheFormatVersion: FormatVersion.Latest,\n schemaVersion: this.schemaVersion,\n };\n }\n #closed = false;\n #online = true;\n readonly #clientID = makeClientID();\n readonly #ready: Promise<void>;\n /**\n * Resolves if open fails, for whatever reason. `#ready` never resolves in\n * that case, so `close()` waits on whichever of the two settles first\n * instead of hanging forever.\n */\n readonly #openFailed = resolver<void>();\n readonly #profileIDPromise: Promise<string>;\n readonly #clientGroupIDPromise: Promise<string>;\n readonly #mutatorRegistry: MutatorDefs = {};\n\n /**\n * The mutators that was registered in the constructor.\n */\n readonly mutate: MakeMutators<MD>;\n\n // Number of pushes/pulls at the moment.\n #pushCounter = 0;\n #pullCounter = 0;\n\n #pullConnectionLoop: ConnectionLoop;\n #pushConnectionLoop: ConnectionLoop;\n\n /**\n * The duration between each periodic {@link pull}. Setting this to `null`\n * disables periodic pull completely. Pull will still happen if you call\n * {@link pull} manually.\n */\n pullInterval: number | null;\n\n /**\n * The delay between when a change is made to Replicache and when Replicache\n * attempts to push that change.\n */\n pushDelay: number;\n\n readonly #requestOptions: Required<RequestOptions>;\n\n /**\n * The function to use to pull data from the server.\n */\n puller: Puller;\n\n /**\n * The function to use to push data to the server.\n */\n pusher: Pusher;\n\n readonly memdag: LazyStore;\n readonly perdag: Store;\n readonly #idbDatabases: IDBDatabasesStore;\n readonly #lc: LogContext;\n readonly #zero: ZeroOption | undefined;\n\n readonly #closeAbortController = new AbortController();\n\n readonly #persistLock = new Lock();\n readonly #enableScheduledPersist: boolean;\n readonly #enableScheduledRefresh: boolean;\n readonly #enableRefresh: () => boolean;\n readonly #enablePullAndPushInOpen: boolean;\n #persistScheduler = new ProcessScheduler(\n () => this.persist(),\n PERSIST_IDLE_TIMEOUT_MS,\n PERSIST_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n readonly #onPersist: OnPersist;\n #refreshScheduler = new ProcessScheduler(\n () => this.refresh(),\n REFRESH_IDLE_TIMEOUT_MS,\n REFRESH_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n\n /**\n * The options used to control the {@link pull} and push request behavior. This\n * object is live so changes to it will affect the next pull or push call.\n */\n get requestOptions(): Required<RequestOptions> {\n return this.#requestOptions;\n }\n\n /**\n * `onSync(true)` is called when Replicache transitions from no push or pull\n * happening to at least one happening. `onSync(false)` is called in the\n * opposite case: when Replicache transitions from at least one push or pull\n * happening to none happening.\n *\n * This can be used in a React like app by doing something like the following:\n *\n * ```js\n * const [syncing, setSyncing] = useState(false);\n * useEffect(() => {\n * rep.onSync = setSyncing;\n * }, [rep]);\n * ```\n */\n onSync: ((syncing: boolean) => void) | null = null;\n\n /**\n * `onClientStateNotFound` is called when the persistent client state can no\n * longer be used. This happens when:\n * - the persistent client has been garbage collected. This can happen if the\n * client has no pending mutations and has not been used for a while.\n * - the persistent store was found to be corrupt. Replicache then tries to\n * drop the database, including any pending mutations, so that a fresh one\n * is created on reload.\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically.\n */\n onClientStateNotFound: (() => void) | null = reload;\n\n /**\n * `onUpdateNeeded` is called when a code update is needed.\n *\n * A code update can be needed because:\n * - the server no longer supports the {@link pushVersion},\n * {@link pullVersion} or {@link schemaVersion} of the current code.\n * - a new Replicache client has created a new client group, because its code\n * has different mutators, indexes, schema version and/or format version\n * from this Replicache client. This is likely due to the new client having\n * newer code. A code update is needed to be able to locally sync with this\n * new Replicache client (i.e. to sync while offline, the clients can still\n * sync with each other via the server).\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically. You may want to provide your own function to\n * display a toast to inform the end user there is a new version of your app\n * available and prompting them to refresh.\n */\n onUpdateNeeded: ((reason: UpdateNeededReason) => void) | null = reload;\n\n /**\n * This gets called when we get an HTTP unauthorized (401) response from the\n * push or pull endpoint. Set this to a function that will ask your user to\n * reauthenticate.\n */\n getAuth: (() => MaybePromise<string | null | undefined>) | null | undefined =\n null;\n\n // These three are used for testing\n onPushInvoked = () => undefined;\n onBeginPull = () => undefined;\n onRecoverMutations = (r: Promise<boolean>) => r;\n\n constructor(\n options: ReplicacheOptions<MD>,\n implOptions: ReplicacheImplOptions = {},\n ) {\n validateOptions(options);\n const {\n name,\n logLevel = 'info',\n logSinks = [consoleLogSink],\n pullURL = '',\n auth,\n pushDelay = 10,\n pushURL = '',\n schemaVersion = '',\n pullInterval = 60000,\n mutators = {} as MD,\n requestOptions = {},\n puller,\n pusher,\n indexes = {},\n clientMaxAgeMs = CLIENT_MAX_INACTIVE_TIME,\n } = options;\n const {\n enableMutationRecovery = true,\n enableScheduledPersist = true,\n enableScheduledRefresh = true,\n enableRefresh = () => true,\n enablePullAndPushInOpen = true,\n enableClientGroupForking = true,\n onClientsDeleted = () => promiseVoid,\n } = implOptions;\n this.#zero = implOptions.zero;\n this.#auth = auth ?? '';\n this.pullURL = pullURL;\n this.pushURL = pushURL;\n this.name = name;\n this.schemaVersion = schemaVersion;\n this.pullInterval = pullInterval;\n this.pushDelay = pushDelay;\n this.puller = puller ?? getDefaultPuller(this);\n this.pusher = pusher ?? getDefaultPusher(this);\n\n this.#enableScheduledPersist = enableScheduledPersist;\n this.#enableScheduledRefresh = enableScheduledRefresh;\n this.#enableRefresh = enableRefresh;\n this.#enablePullAndPushInOpen = enablePullAndPushInOpen;\n\n this.#lc = createLogContext(logLevel, logSinks, {name});\n this.#lc.debug?.('Constructing Replicache', {\n name,\n 'replicache version': version,\n });\n\n this.#subscriptions = new SubscriptionsManagerImpl(\n this.#queryInternal,\n this.#lc,\n this.#closeAbortController.signal,\n );\n\n const kvStoreProvider = getKVStoreProvider(this.#lc, options.kvStore);\n this.#kvStoreProvider = kvStoreProvider;\n\n const perKVStore = kvStoreProvider.create(this.idbName);\n\n this.#idbDatabases = new IDBDatabasesStore(kvStoreProvider.create);\n this.perdag = new StoreImpl(\n perKVStore,\n newRandomHash,\n assertHash,\n this.#onInvalidRefCount,\n );\n this.memdag = new LazyStore(\n this.perdag,\n LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT,\n newRandomHash,\n assertHash,\n );\n\n // Use a promise-resolve pair so that we have a promise to use even before\n // we call the Open RPC.\n const readyResolver = resolver<void>();\n this.#ready = readyResolver.promise;\n\n const {minDelayMs = MIN_DELAY_MS, maxDelayMs = MAX_DELAY_MS} =\n requestOptions;\n this.#requestOptions = {maxDelayMs, minDelayMs};\n\n const visibilityWatcher = getDocumentVisibilityWatcher(\n getBrowserGlobal('document'),\n 0,\n this.#closeAbortController.signal,\n );\n\n this.#pullConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PULL'),\n new PullDelegate(this, () => this.#invokePull()),\n visibilityWatcher,\n );\n\n this.#pushConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PUSH'),\n new PushDelegate(this, () => this.#invokePush()),\n );\n\n this.mutate = this.#registerMutators(mutators);\n\n const profileIDResolver = resolver<string>();\n this.#profileIDPromise = profileIDResolver.promise;\n const clientGroupIDResolver = resolver<string>();\n this.#clientGroupIDPromise = clientGroupIDResolver.promise;\n\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n this.#mutationRecovery = new MutationRecovery({\n delegate: this,\n lc: this.#lc,\n enableMutationRecovery,\n wrapInOnlineCheck: this.#wrapInOnlineCheck.bind(this),\n wrapInReauthRetries: this.#wrapInReauthRetries.bind(this),\n isPullDisabled: this.#isPullDisabled.bind(this),\n isPushDisabled: this.#isPushDisabled.bind(this),\n clientGroupIDPromise: this.#clientGroupIDPromise,\n });\n }\n\n this.#onPersist = initOnPersistChannel(\n this.name,\n this.#closeAbortController.signal,\n persistInfo => {\n void this.#handlePersist(persistInfo);\n },\n );\n\n void this.#open(\n indexes,\n enableClientGroupForking,\n enableMutationRecovery,\n clientMaxAgeMs,\n profileIDResolver.resolve,\n clientGroupIDResolver.resolve,\n readyResolver.resolve,\n onClientsDeleted,\n ).catch(e => {\n // Whatever the reason, this open is over: `#ready` stays pending so\n // reads and writes never run against a store that failed to open, but\n // `close()` must still be able to dispose the instance. This must not\n // depend on why the open failed.\n this.#openFailed.resolve();\n if (e instanceof InvalidRefCountError) {\n // #onInvalidRefCount (called from the write's release()) already\n // started recovery: drop the database and fire onClientStateNotFound.\n // Nothing else can be done with this instance.\n this.#lc.debug?.('Open failed because the persistent store is corrupt');\n return;\n }\n throw e;\n });\n }\n\n async #open(\n indexes: IndexDefinitions,\n enableClientGroupForking: boolean,\n enableMutationRecovery: boolean,\n clientMaxAgeMs: number,\n profileIDResolver: (profileID: string) => void,\n resolveClientGroupID: (clientGroupID: ClientGroupID) => void,\n resolveReady: () => void,\n onClientsDeleted: OnClientsDeleted,\n ): Promise<void> {\n const {clientID} = this;\n // Everything up to the head write is what it takes to have a usable\n // database, including waiting out a previous instance of the same name.\n // The timer stops before the replica is loaded into Zero's IVM sources,\n // which is separate work and usually the larger of the two: a number that\n // spanned both would report a slow hydration as a slow disk.\n const openStart = performance.now();\n // If we are currently closing a Replicache instance with the same name,\n // wait for it to finish closing.\n await closingInstances.get(this.name);\n await this.#idbDatabases.getProfileID().then(profileIDResolver);\n await this.#idbDatabases.putDatabase(this.#idbDatabase);\n const [client, headHash, , isNewClientGroup] = await initClientV6(\n clientID,\n this.#lc,\n this.perdag,\n Object.keys(this.#mutatorRegistry),\n indexes,\n FormatVersion.Latest,\n enableClientGroupForking,\n );\n\n resolveClientGroupID(client.clientGroupID);\n await withWrite(this.memdag, write =>\n write.setHead(DEFAULT_HEAD_NAME, headHash),\n );\n\n // Now we have a profileID, a clientID, a clientGroupID and DB!\n const dbOpenMs = performance.now() - openStart;\n if (dbOpenMs > SLOW_DB_OPEN_THRESHOLD_MS) {\n this.#lc.warn?.(`Opening the database took ${Math.round(dbOpenMs)}ms`, {\n name: this.idbName,\n });\n } else {\n this.#lc.debug?.('Opened the database in', Math.round(dbOpenMs), 'ms');\n }\n\n await this.#zero?.init(headHash, this.memdag);\n resolveReady();\n\n if (this.#enablePullAndPushInOpen) {\n this.pull().catch(noop);\n this.push().catch(noop);\n }\n\n const {signal} = this.#closeAbortController;\n\n startHeartbeats(\n clientID,\n this.perdag,\n () => {\n this.#clientStateNotFoundOnClient(clientID);\n },\n HEARTBEAT_INTERVAL,\n this.#lc,\n signal,\n );\n initClientGC(\n clientID,\n this.perdag,\n clientMaxAgeMs,\n GC_INTERVAL,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initCollectIDBDatabases(\n this.#idbDatabases,\n this.#kvStoreProvider,\n COLLECT_IDB_INTERVAL,\n INITIAL_COLLECT_IDB_DELAY,\n 2 * clientMaxAgeMs,\n enableMutationRecovery,\n onClientsDeleted,\n this.#lc,\n signal,\n // Collection writes deleted clients into every surviving database using\n // its own dag store. When that is our database, a corrupt ref count\n // found there must reach the same recovery as writes through `perdag`.\n // A corrupt foreign database is left for its own instance to discover\n // and recover from on its next write.\n (name, createKVStore) =>\n new StoreImpl(\n createKVStore(name),\n newRandomHash,\n assertHash,\n name === this.idbName ? this.#onInvalidRefCount : undefined,\n ),\n );\n initClientGroupGC(this.perdag, enableMutationRecovery, this.#lc, signal);\n initNewClientChannel(\n this.name,\n this.idbName,\n signal,\n client.clientGroupID,\n isNewClientGroup,\n () => {\n this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);\n },\n this.perdag,\n );\n\n setIntervalWithSignal(\n () => this.recoverMutations(),\n RECOVER_MUTATIONS_INTERVAL_MS,\n signal,\n );\n void this.recoverMutations();\n\n getBrowserGlobal('document')?.addEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n }\n\n #onVisibilityChange = async () => {\n if (this.#closed) {\n return;\n }\n\n // In case of running in a worker, we don't have a document.\n if (getBrowserGlobal('document')?.visibilityState !== 'visible') {\n return;\n }\n\n await this.#checkForClientStateNotFoundAndCallHandler();\n };\n\n async #checkForClientStateNotFoundAndCallHandler(): Promise<boolean> {\n const {clientID} = this;\n const hasClientState = await withRead(this.perdag, read =>\n persistHasClientState(clientID, read),\n );\n if (!hasClientState) {\n this.#clientStateNotFoundOnClient(clientID);\n }\n return !hasClientState;\n }\n\n /**\n * The browser profile ID for this browser profile. Every instance of Replicache\n * browser-profile-wide shares the same profile ID.\n */\n get profileID(): Promise<string> {\n return this.#profileIDPromise;\n }\n\n /**\n * The client ID for this instance of Replicache. Each instance of Replicache\n * gets a unique client ID.\n */\n get clientID(): string {\n return this.#clientID;\n }\n\n /**\n * The client group ID for this instance of Replicache. Instances of\n * Replicache will have the same client group ID if and only if they have\n * the same name, mutators, indexes, schema version, format version, and\n * browser profile.\n */\n get clientGroupID(): Promise<string> {\n return this.#clientGroupIDPromise;\n }\n\n /**\n * `onOnlineChange` is called when the {@link online} property changes. See\n * {@link online} for more details.\n */\n onOnlineChange: ((online: boolean) => void) | null = null;\n\n /**\n * A rough heuristic for whether the client is currently online. Note that\n * there is no way to know for certain whether a client is online - the next\n * request can always fail. This property returns true if the last sync attempt succeeded,\n * and false otherwise.\n */\n get online(): boolean {\n return this.#online;\n }\n\n /**\n * Whether the Replicache database has been closed. Once Replicache has been\n * closed it no longer syncs and you can no longer read or write data out of\n * it. After it has been closed it is pretty much useless and should not be\n * used any more.\n */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Closes this Replicache instance.\n *\n * When closed all subscriptions end and no more read or writes are allowed.\n */\n async close(): Promise<void> {\n this.#closed = true;\n const {promise, resolve} = resolver();\n closingInstances.set(this.name, promise);\n\n this.#closeAbortController.abort();\n\n getBrowserGlobal('document')?.removeEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n\n await Promise.race([this.#ready, this.#openFailed.promise]);\n const closingPromises = [\n this.memdag.close(),\n this.perdag.close(),\n this.#idbDatabases.close(),\n ];\n\n this.#pullConnectionLoop.close();\n this.#pushConnectionLoop.close();\n\n this.#subscriptions.clear();\n\n await Promise.all(closingPromises);\n closingInstances.delete(this.name);\n resolve();\n }\n\n async maybeEndPull(syncHead: Hash, requestID: string): Promise<void> {\n for (;;) {\n if (this.#closed) {\n return;\n }\n\n await this.#ready;\n const {clientID} = this;\n const lc = this.#lc\n .withContext('maybeEndPull')\n .withContext('requestID', requestID);\n const {replayMutations, diffs, oldMainHead, mainHead} =\n await maybeEndPull<LocalMeta>(\n this.memdag,\n lc,\n syncHead,\n clientID,\n this.#subscriptions,\n FormatVersion.Latest,\n );\n\n if (!replayMutations || replayMutations.length === 0) {\n // All done.\n this.#zero?.advance(oldMainHead, mainHead, diffs.get('') ?? []);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return;\n }\n\n // Replay.\n let zeroData = await this.#zero?.getTxData?.(syncHead);\n for (const mutation of replayMutations) {\n // TODO(greg): I'm not sure why this was in Replicache#_mutate...\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n const {meta} = mutation;\n const {result, zeroData: next} = await withWriteNoImplicitCommit(\n this.memdag,\n dagWrite =>\n rebaseMutationAndCommit(\n mutation,\n dagWrite,\n syncHead,\n SYNC_HEAD_NAME,\n this.#mutatorRegistry,\n lc,\n isLocalMetaDD31(meta) ? meta.clientID : clientID,\n FormatVersion.Latest,\n zeroData,\n ),\n );\n syncHead = result;\n // The fork the mutation ran against when it succeeded, or the branch we\n // came in with when it threw.\n zeroData = next;\n }\n }\n }\n\n #invokePull(): Promise<boolean> {\n if (this.#isPullDisabled()) {\n return Promise.resolve(true);\n }\n\n return this.#wrapInOnlineCheck(async () => {\n try {\n this.#changeSyncCounters(0, 1);\n const {syncHead, requestID, ok} = await this.beginPull();\n if (!ok) {\n return false;\n }\n if (syncHead !== emptyHash) {\n await this.maybeEndPull(syncHead, requestID);\n }\n } catch (e) {\n throw await this.#convertToClientStateNotFoundError(e);\n } finally {\n this.#changeSyncCounters(0, -1);\n }\n return true;\n }, 'Pull');\n }\n\n #isPullDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pullURL === '' && isDefaultPuller(this.puller))\n );\n }\n\n async #wrapInOnlineCheck(\n f: () => Promise<boolean>,\n name: string,\n ): Promise<boolean> {\n let online = true;\n\n try {\n return await f();\n } catch (e) {\n // The error paths of beginPull and maybeEndPull need to be reworked.\n //\n // We want to distinguish between:\n // a) network requests failed -- we're offline basically\n // b) sync was aborted because one's already in progress\n // c) oh noes - something unexpected happened\n //\n // Right now, all of these come out as errors. We distinguish (b) with a\n // hacky string search. (a) and (c) are not distinguishable currently\n // because repc doesn't provide sufficient information, so we treat all\n // errors that aren't (b) as (a).\n if (e instanceof PushError || e instanceof PullError) {\n online = false;\n this.#lc.debug?.(`${name} threw:\\n`, e, '\\nwith cause:\\n', e.causedBy);\n } else if (e instanceof ReportError) {\n this.#lc.error?.(e);\n } else {\n this.#lc.info?.(`${name} threw:\\n`, e);\n }\n return false;\n } finally {\n if (this.#online !== online) {\n this.#online = online;\n this.onOnlineChange?.(online);\n if (online) {\n void this.recoverMutations();\n }\n }\n }\n }\n\n async #wrapInReauthRetries<R>(\n f: (\n requestID: string,\n requestLc: LogContext,\n ) => Promise<{\n httpRequestInfo: HTTPRequestInfo | undefined;\n result: R;\n }>,\n verb: string,\n lc: LogContext,\n preAuth: () => MaybePromise<void> = noop,\n postAuth: () => MaybePromise<void> = noop,\n ): Promise<{\n result: R;\n authFailure: boolean;\n }> {\n const {clientID} = this;\n let reauthAttempts = 0;\n let lastResult;\n lc = lc.withContext(verb);\n do {\n const requestID = newRequestID(clientID);\n const requestLc = lc.withContext('requestID', requestID);\n const {httpRequestInfo, result} = await f(requestID, requestLc);\n lastResult = result;\n if (!httpRequestInfo) {\n return {\n result,\n authFailure: false,\n };\n }\n const {errorMessage, httpStatusCode} = httpRequestInfo;\n\n if (errorMessage || httpStatusCode !== 200) {\n // TODO(arv): Maybe we should not log the server URL when the error comes\n // from a Pusher/Puller?\n requestLc.error?.(\n `Got a non 200 response doing ${verb}: ${httpStatusCode}` +\n (errorMessage ? `: ${errorMessage}` : ''),\n );\n }\n if (httpStatusCode !== httpStatusUnauthorized) {\n return {\n result,\n authFailure: false,\n };\n }\n if (!this.getAuth) {\n return {\n result,\n authFailure: true,\n };\n }\n let auth;\n try {\n await preAuth();\n auth = await this.getAuth();\n } finally {\n await postAuth();\n }\n if (auth === null || auth === undefined) {\n return {\n result,\n authFailure: true,\n };\n }\n this.auth = auth;\n reauthAttempts++;\n } while (reauthAttempts < MAX_REAUTH_TRIES);\n lc.info?.('Tried to reauthenticate too many times');\n return {\n result: lastResult,\n authFailure: true,\n };\n }\n\n #isPushDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pushURL === '' && isDefaultPusher(this.pusher))\n );\n }\n\n async #invokePush(): Promise<boolean> {\n if (TESTING) {\n this.onPushInvoked();\n }\n if (this.#isPushDisabled()) {\n return true;\n }\n\n await this.#ready;\n const profileID = await this.#profileIDPromise;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n return this.#wrapInOnlineCheck(async () => {\n const {result: pusherResult} = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n try {\n this.#changeSyncCounters(1, 0);\n const pusherResult = await push(\n requestID,\n this.memdag,\n requestLc,\n profileID,\n clientGroupID,\n clientID,\n this.pusher,\n this.schemaVersion,\n PUSH_VERSION_DD31,\n );\n return {\n result: pusherResult,\n httpRequestInfo: pusherResult?.httpRequestInfo,\n };\n } finally {\n this.#changeSyncCounters(-1, 0);\n }\n },\n 'push',\n this.#lc,\n );\n\n if (pusherResult === undefined) {\n // No pending mutations.\n return true;\n }\n\n const {response, httpRequestInfo} = pusherResult;\n\n if (isVersionNotSupportedResponse(response)) {\n this.#handleVersionNotSupportedResponse(response);\n } else if (isClientStateNotFoundResponse(response)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n // No pushResponse means we didn't do a push because there were no\n // pending mutations.\n return httpRequestInfo.httpStatusCode === 200;\n }, 'Push');\n }\n\n #handleVersionNotSupportedResponse(response: VersionNotSupportedResponse) {\n const reason: UpdateNeededReason = {\n type: response.error,\n };\n if (response.versionType) {\n reason.versionType = response.versionType;\n }\n this.#fireOnUpdateNeeded(reason);\n }\n\n /**\n * Push pushes pending changes to the {@link pushURL}.\n *\n * You do not usually need to manually call push. If {@link pushDelay} is\n * non-zero (which it is by default) pushes happen automatically shortly after\n * mutations.\n *\n * If the server endpoint fails push will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, push will happen immediately and ignore\n * {@link pushDelay}, {@link RequestOptions.minDelayMs} as well as the\n * exponential backoff in case of errors.\n * @returns A promise that resolves when the next push completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n push({now = false} = {}): Promise<void> {\n return throwIfError(this.#pushConnectionLoop.send(now));\n }\n\n /**\n * Pull pulls changes from the {@link pullURL}. If there are any changes local\n * changes will get replayed on top of the new server state.\n *\n * If the server endpoint fails pull will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, pull will happen immediately and ignore\n * {@link RequestOptions.minDelayMs} as well as the exponential backoff in\n * case of errors.\n * @returns A promise that resolves when the next pull completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n pull({now = false} = {}): Promise<void> {\n return throwIfError(this.#pullConnectionLoop.send(now));\n }\n\n /**\n * Applies an update from the server to Replicache.\n * Throws an error if cookie does not match. In that case the server thinks\n * this client has a different cookie than it does; the caller should disconnect\n * from the server and re-register, which transmits the cookie the client actually\n * has.\n *\n * @experimental This method is under development and its semantics will change.\n */\n async poke(poke: PokeInternal): Promise<void> {\n await this.#ready;\n // TODO(MP) Previously we created a request ID here and included it with the\n // PullRequest to the server so we could tie events across client and server\n // together. Since the direction is now reversed, creating and adding a request ID\n // here is kind of silly. We should consider creating the request ID\n // on the *server* and passing it down in the poke for inclusion here in the log\n // context\n const {clientID} = this;\n const requestID = newRequestID(clientID);\n const lc = this.#lc\n .withContext('handlePullResponse')\n .withContext('requestID', requestID);\n\n const {pullResponse} = poke;\n\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n return;\n }\n\n if (isClientStateNotFoundResponse(pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n return;\n }\n\n const result = await handlePullResponseV1(\n lc,\n this.memdag,\n deepFreeze(poke.baseCookie),\n pullResponse,\n clientID,\n FormatVersion.Latest,\n );\n\n switch (result.type) {\n case HandlePullResponseResultEnum.Applied:\n await this.maybeEndPull(result.syncHead, requestID);\n break;\n case HandlePullResponseResultEnum.CookieMismatch:\n throw new Error(\n 'unexpected base cookie for poke: ' + JSON.stringify(poke),\n );\n case HandlePullResponseResultEnum.NoOp:\n break;\n }\n }\n\n async beginPull(): Promise<BeginPullResult> {\n if (TESTING) {\n this.onBeginPull();\n }\n await this.#ready;\n const profileID = await this.profileID;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n const {\n result: {beginPullResponse, requestID},\n } = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n const beginPullResponse = await beginPullV1(\n profileID,\n clientID,\n clientGroupID,\n this.schemaVersion,\n this.puller,\n requestID,\n this.memdag,\n FormatVersion.Latest,\n requestLc,\n );\n return {\n result: {beginPullResponse, requestID},\n httpRequestInfo: beginPullResponse.httpRequestInfo,\n };\n },\n 'pull',\n this.#lc,\n () => this.#changeSyncCounters(0, -1),\n () => this.#changeSyncCounters(0, 1),\n );\n\n const {pullResponse} = beginPullResponse;\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n } else if (isClientStateNotFoundResponse(beginPullResponse.pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n const {syncHead, httpRequestInfo} = beginPullResponse;\n return {requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200};\n }\n\n persist(): Promise<void> {\n // Prevent multiple persist calls from running at the same time.\n return this.#persistLock.withLock(async () => {\n const {clientID} = this;\n await this.#ready;\n if (this.#closed) {\n return;\n }\n try {\n await persistDD31(\n this.#lc,\n clientID,\n this.memdag,\n this.perdag,\n this.#mutatorRegistry,\n () => this.#closed,\n FormatVersion.Latest,\n this.#zero?.getTxData,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (e instanceof InvalidRefCountError) {\n await this.#handleInvalidRefCount(e);\n // Nothing was persisted and the database is gone. Do not tell this\n // or other instances to refresh from it.\n return;\n } else if (this.#closed) {\n this.#lc.debug?.('Exception persisting during close', e);\n } else {\n throw e;\n }\n }\n\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.#onPersist({clientID, clientGroupID});\n });\n }\n\n async refresh(): Promise<void> {\n await this.#ready;\n const {clientID} = this;\n if (this.#closed || !this.#enableRefresh()) {\n return;\n }\n let refreshResult: Awaited<ReturnType<typeof refresh>>;\n try {\n refreshResult = await refresh(\n this.#lc,\n this.memdag,\n this.perdag,\n clientID,\n this.#mutatorRegistry,\n this.#subscriptions,\n () => this.closed,\n FormatVersion.Latest,\n this.#zero,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (e instanceof InvalidRefCountError) {\n await this.#handleInvalidRefCount(e);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception refreshing during close', e);\n } else {\n throw e;\n }\n }\n if (refreshResult !== undefined) {\n await this.#subscriptions.fire(refreshResult.diffs);\n }\n }\n\n #fireOnClientStateNotFound() {\n this.onClientStateNotFound?.();\n }\n\n #clientStateNotFoundOnClient(clientID: ClientID) {\n this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);\n this.#fireOnClientStateNotFound();\n }\n\n /**\n * Set once recovery from a corrupt database has started. Every write path\n * into the perdag (open, persist, refresh, heartbeat, GC, ...) can trip on\n * the same corrupt key, so recovery runs once and later reports await it.\n */\n #corruptDatabaseRecovery: Promise<void> | undefined;\n\n /**\n * Installed on the dag store that writes to our database. The store calls\n * it after the failing transaction has been released, so dropping the\n * database from here does not race with the rollback.\n */\n readonly #onInvalidRefCount = (e: InvalidRefCountError): void => {\n void this.#handleInvalidRefCount(e);\n };\n\n /**\n * The persistent dag store contains an invalid ref count. This means the\n * store is corrupt (due to some unknown bug) and every subsequent write that\n * touches that chunk would fail the same way. There is no way to repair it,\n * so we treat it like the client state was lost and fire\n * `onClientStateNotFound`.\n *\n * Disabling the client group is not enough: the corrupt ref count stays in\n * the underlying kv store and any later write that touches that chunk (for\n * example rewriting the `clients` chunk when a new client starts) would hit\n * it again. Instead we drop the whole database so that the reload starts\n * from a fresh store. Pending local mutations in this database are lost.\n *\n * This is expected to be exceedingly rare. Other instances sharing the\n * database are not told: they simply hit the same corrupt key (or, once\n * this instance drops the database, a generic storage error) on their own\n * next write and recover the same way then. That's an acceptable delay for\n * something we don't expect to ever happen.\n */\n #handleInvalidRefCount(e: InvalidRefCountError): Promise<void> {\n if (this.#corruptDatabaseRecovery === undefined) {\n this.#lc.error?.(\n `Client state is corrupt on client, clientID: ${this.clientID}. Dropping database ${this.idbName}`,\n e,\n );\n this.#corruptDatabaseRecovery =\n this.#dropDatabaseAndFireOnClientStateNotFound();\n }\n return this.#corruptDatabaseRecovery;\n }\n\n /**\n * Drops our database, then fires `onClientStateNotFound` so the app can\n * recover, whether or not the drop itself succeeded.\n *\n * Uses its own handle on the databases registry rather than `#idbDatabases`\n * so it works even when `close()` is already closing this instance.\n */\n async #dropDatabaseAndFireOnClientStateNotFound(): Promise<void> {\n const {idbName, clientID} = this;\n let idbDatabases: IDBDatabasesStore | undefined;\n try {\n idbDatabases = new IDBDatabasesStore(this.#kvStoreProvider.create);\n await dropDatabaseInternal(\n idbName,\n idbDatabases,\n this.#kvStoreProvider.drop,\n );\n } catch (dropError) {\n this.#lc.error?.(\n `Failed to drop database ${idbName}, clientID: ${clientID}`,\n dropError,\n );\n }\n try {\n await idbDatabases?.close();\n } catch (closeError) {\n // Closing the registry handle is best effort. The callback below must\n // fire regardless, and the drop outcome was already logged.\n this.#lc.debug?.(\n `Failed to close the databases registry after dropping ${idbName}, clientID: ${clientID}`,\n closeError,\n );\n }\n this.#fireOnClientStateNotFound();\n }\n\n async #clientStateNotFoundOnServer() {\n const clientGroupID = await this.#clientGroupIDPromise;\n this.#lc.error?.(\n `Client state not found on server, clientGroupID: ${clientGroupID}`,\n );\n await this.disableClientGroup();\n this.#fireOnClientStateNotFound();\n }\n\n async disableClientGroup(): Promise<void> {\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.isClientGroupDisabled = true;\n await withWrite(this.perdag, dagWrite =>\n disableClientGroup(clientGroupID, dagWrite),\n );\n }\n\n #fireOnUpdateNeeded(reason: UpdateNeededReason) {\n this.#lc.debug?.(`Update needed, reason: ${reason}`);\n this.onUpdateNeeded?.(reason);\n }\n\n async #schedulePersist(): Promise<void> {\n if (!this.#enableScheduledPersist) {\n return;\n }\n await this.#schedule('persist', this.#persistScheduler);\n }\n\n async #handlePersist(persistInfo: PersistInfo): Promise<void> {\n this.#lc.debug?.('Handling persist', persistInfo);\n const clientGroupID = await this.#clientGroupIDPromise;\n if (persistInfo.clientGroupID === clientGroupID) {\n void this.#scheduleRefresh();\n }\n }\n\n async #scheduleRefresh(): Promise<void> {\n if (!this.#enableScheduledRefresh) {\n return;\n }\n await this.#schedule('refresh from storage', this.#refreshScheduler);\n }\n\n async #schedule(name: string, scheduler: ProcessScheduler): Promise<void> {\n try {\n await scheduler.schedule();\n } catch (e) {\n if (e instanceof AbortError) {\n this.#lc.debug?.(`Scheduled ${name} did not complete before close.`);\n } else {\n this.#lc.error?.(`Error during ${name}`, e);\n }\n }\n }\n\n /**\n * Runs a refresh as soon as possible through the refresh scheduler.\n */\n runRefresh(): Promise<void> {\n return this.#refreshScheduler.run();\n }\n\n #changeSyncCounters(pushDelta: 0, pullDelta: 1 | -1): void;\n #changeSyncCounters(pushDelta: 1 | -1, pullDelta: 0): void;\n #changeSyncCounters(pushDelta: number, pullDelta: number): void {\n this.#pushCounter += pushDelta;\n this.#pullCounter += pullDelta;\n const delta = pushDelta + pullDelta;\n const counter = this.#pushCounter + this.#pullCounter;\n if ((delta === 1 && counter === 1) || counter === 0) {\n const syncing = counter > 0;\n // Run in a new microtask.\n void Promise.resolve().then(() => this.onSync?.(syncing));\n }\n }\n\n /**\n * Subscribe to the result of a {@link query}. The `body` function is\n * evaluated once and its results are returned via `onData`.\n *\n * Thereafter, each time the the result of `body` changes, `onData` is fired\n * again with the new result.\n *\n * `subscribe()` goes to significant effort to avoid extraneous work\n * re-evaluating subscriptions:\n *\n * 1. subscribe tracks the keys that `body` accesses each time it runs. `body`\n * is only re-evaluated when those keys change.\n * 2. subscribe only re-fires `onData` in the case that a result changes by\n * way of the `isEqual` option which defaults to doing a deep JSON value\n * equality check.\n *\n * Because of (1), `body` must be a pure function of the data in Replicache.\n * `body` must not access anything other than the `tx` parameter passed to it.\n *\n * Although subscribe is as efficient as it can be, it is somewhat constrained\n * by the goal of returning an arbitrary computation of the cache. For even\n * better performance (but worse dx), see {@link experimentalWatch}.\n *\n * If an error occurs in the `body` the `onError` function is called if\n * present. Otherwise, the error is logged at log level 'error'.\n *\n * To cancel the subscription, call the returned function.\n *\n * @param body The function to evaluate to get the value to pass into\n * `onData`.\n * @param options Options is either a function or an object. If it is a\n * function it is equivalent to passing it as the `onData` property of an\n * object.\n */\n subscribe<R>(\n body: (tx: ReadTransaction) => Promise<R>,\n options: SubscribeOptions<R> | ((result: R) => void),\n ): () => void {\n if (typeof options === 'function') {\n options = {onData: options};\n }\n\n const {onData, onError, onDone, isEqual} = options;\n return this.#subscriptions.add(\n new SubscriptionImpl(body, onData, onError, onDone, isEqual),\n );\n }\n\n /**\n * Watches Replicache for changes.\n *\n * The `callback` gets called whenever the underlying data changes and the\n * `key` changes matches the `prefix` of {@link ExperimentalWatchIndexOptions} or\n * {@link ExperimentalWatchNoIndexOptions} if present. If a change\n * occurs to the data but the change does not impact the key space the\n * callback is not called. In other words, the callback is never called with\n * an empty diff.\n *\n * This gets called after commit (a mutation or a rebase).\n *\n * @experimental This method is under development and its semantics will\n * change.\n */\n experimentalWatch(callback: WatchNoIndexCallback): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void {\n return this.#subscriptions.add(\n new WatchSubscription(callback as WatchCallback, options),\n );\n }\n\n /**\n * Query is used for read transactions. It is recommended to use transactions\n * to ensure you get a consistent view across multiple calls to `get`, `has`\n * and `scan`.\n */\n query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R> {\n return this.#queryInternal(body);\n }\n\n get cookie(): Promise<Cookie> {\n return this.#ready.then(() =>\n withRead(this.memdag, async dagRead => {\n const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);\n if (!mainHeadHash) {\n throw new Error('Internal no main head found');\n }\n const baseSnapshot = await baseSnapshotFromHash(mainHeadHash, dagRead);\n const baseSnapshotMeta = baseSnapshot.meta;\n const cookie = baseSnapshotMeta.cookieJSON;\n assertCookie(cookie);\n return cookie;\n }),\n );\n }\n\n #queryInternal: QueryInternal = async body => {\n await this.#ready;\n const {clientID} = this;\n return withRead(this.memdag, async dagRead => {\n try {\n const dbRead = await readFromDefaultHead(dagRead, FormatVersion.Latest);\n const tx = new ReadTransactionImpl(clientID, dbRead, this.#lc);\n return await body(tx);\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n };\n\n #register<Return extends ReadonlyJSONValue | void, Args extends JSONValue>(\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: Args) => MaybePromise<Return>,\n ): (\n args?: Args,\n ) => Promise<Return> | {client: Promise<Return>; server: Promise<unknown>} {\n this.#mutatorRegistry[name] = mutatorImpl as (\n tx: WriteTransaction,\n args: JSONValue | undefined,\n ) => Promise<void | JSONValue>;\n\n return (\n args?: Args,\n ):\n | Promise<Return>\n | {client: Promise<Return>; server: Promise<unknown>} => {\n // DO NOT track CRUD mutations as they do not receive responses from\n // the server.\n const trackingData =\n name === '_zero_crud' ? undefined : this.#zero?.trackMutation();\n\n const result = this.#mutate(\n trackingData,\n name,\n mutatorImpl,\n args,\n performance.now(),\n );\n\n if (trackingData) {\n return {\n client: result,\n server: trackingData.serverPromise,\n };\n }\n\n return result;\n };\n }\n\n #registerMutators<\n M extends {\n [key: string]: (\n tx: WriteTransaction,\n args?: ReadonlyJSONValue,\n ) => MutatorReturn;\n },\n >(regs: M): MakeMutators<M> {\n type Mut = MakeMutators<M>;\n const rv: Partial<Mut> = Object.create(null);\n for (const k in regs) {\n rv[k] = this.#register(k, regs[k]) as MakeMutator<M[typeof k]>;\n }\n return rv as Mut;\n }\n\n async #mutate<\n R extends ReadonlyJSONValue | void,\n A extends ReadonlyJSONValue,\n >(\n trackingData: MutationTrackingData | undefined,\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: A) => MaybePromise<R>,\n args: A | undefined,\n timestamp: number,\n ): Promise<R> {\n const frozenArgs = deepFreeze(args ?? null);\n\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n\n await this.#ready;\n const {clientID} = this;\n return withWriteNoImplicitCommit(this.memdag, async dagWrite => {\n try {\n let result: R;\n let newHead: Hash;\n let diffs: DiffsMap;\n let headHash: Hash;\n try {\n headHash = await mustGetHeadHash(DEFAULT_HEAD_NAME, dagWrite);\n const originalHash = null;\n\n const dbWrite = await newWriteLocal(\n headHash,\n name,\n frozenArgs,\n originalHash,\n dagWrite,\n timestamp,\n clientID,\n FormatVersion.Latest,\n );\n\n const mutationID = await dbWrite.getMutationID();\n const tx = new WriteTransactionImpl(\n clientID,\n mutationID,\n 'initial',\n await this.#zero?.getTxData(headHash, {\n openLazyRead: dagWrite,\n }),\n dbWrite,\n this.#lc,\n );\n\n if (trackingData) {\n this.#zero?.mutationIDAssigned(\n trackingData.ephemeralID,\n mutationID,\n );\n }\n\n result = await mutatorImpl(tx, args);\n\n throwIfClosed(dbWrite);\n const lastMutationID = await dbWrite.getMutationID();\n [newHead, diffs] = await dbWrite.commitWithDiffs(\n DEFAULT_HEAD_NAME,\n this.#subscriptions,\n );\n\n // Update this after the commit in case the commit fails.\n this.lastMutationID = lastMutationID;\n } catch (e) {\n // If we threw before we could persist the mutation\n // then we need to reject the mutation.\n if (trackingData) {\n this.#zero?.rejectMutation(trackingData.ephemeralID, e);\n }\n throw e;\n }\n\n this.#zero?.advance(headHash, newHead, diffs.get('') ?? []);\n\n // Send is not supposed to reject\n this.#pushConnectionLoop.send(false).catch(() => void 0);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return result;\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n }\n\n /**\n * In the case we get a ChunkNotFoundError we check if the client got garbage\n * collected and if so change the error to a ClientStateNotFoundError instead\n */\n async #convertToClientStateNotFoundError(ex: unknown): Promise<unknown> {\n if (\n ex instanceof ChunkNotFoundError &&\n (await this.#checkForClientStateNotFoundAndCallHandler())\n ) {\n return new ClientStateNotFoundError(this.clientID);\n }\n\n return ex;\n }\n\n recoverMutations(): Promise<boolean> | void {\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n // oxlint-disable-next-line no-non-null-assertion\n const result = this.#mutationRecovery!.recoverMutations(\n this.#ready,\n this.perdag,\n this.#idbDatabase,\n this.#idbDatabases,\n this.#kvStoreProvider.create,\n );\n if (TESTING) {\n void this.onRecoverMutations(result);\n }\n return result;\n }\n }\n\n /**\n * List of pending mutations. The order of this is from oldest to newest.\n *\n * Gives a list of local mutations that have `mutationID` >\n * `syncHead.mutationID` that exists on the main client group.\n *\n * @experimental This method is experimental and may change in the future.\n */\n experimentalPendingMutations(): Promise<readonly PendingMutation[]> {\n return withRead(this.memdag, pendingMutationsForAPI);\n }\n}\n\n// This map is used to keep track of closing instances of Replicache. When an\n// instance is opening we wait for any currently closing instances.\nconst closingInstances: Map<string, Promise<unknown>> = new Map();\n\nasync function throwIfError(p: Promise<undefined | {error: unknown}>) {\n const res = await p;\n if (res) {\n throw res.error;\n }\n}\n\nfunction reload(): void {\n if (typeof location !== 'undefined') {\n location.reload();\n }\n}\n\nfunction validateOptions<MD extends MutatorDefs>(\n options: ReplicacheOptions<MD>,\n): void {\n const {name, clientMaxAgeMs} = options;\n if (typeof name !== 'string' || !name) {\n throw new TypeError('name is required and must be non-empty');\n }\n\n if (clientMaxAgeMs !== undefined) {\n const min = Math.max(GC_INTERVAL, HEARTBEAT_INTERVAL);\n if (typeof clientMaxAgeMs !== 'number' || clientMaxAgeMs <= min) {\n throw new TypeError(\n `clientAgeMaxMs must be a number larger than ${min}ms`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyIA,IAAM,mBAAmB;AAEzB,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAEhC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;;;;;;AAO5B,IAAM,4BAA4B;AAElC,IAAM,2CA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,SAAS,IAAI;IACX,MAAM,MAAM,KAAKE,mCAAmC,EAAE;GACxD;EACF,CAAC;CACH;;;;;CAMA,MAAMA,mCAAmC,IAA+B;EACtE,IACE,cAAc,sBACb,MAAM,KAAKJ,2CAA2C,GAEvD,OAAO,IAAI,yBAAyB,KAAK,QAAQ;EAGnD,OAAO;CACT;CAEA,mBAA4C,CAe5C;;;;;;;;;CAUA,+BAAoE;EAClE,OAAO,SAAS,KAAK,QAAQ,sBAAsB;CACrD;AACF;AAIA,IAAM,mCAAkD,IAAI,IAAI;AAEhE,eAAe,aAAa,GAA0C;CACpE,MAAM,MAAM,MAAM;CAClB,IAAI,KACF,MAAM,IAAI;AAEd;AAEA,SAAS,SAAe;CACtB,IAAI,OAAO,aAAa,aACtB,SAAS,OAAO;AAEpB;AAEA,SAAS,gBACP,SACM;CACN,MAAM,EAAC,MAAM,mBAAkB;CAC/B,IAAI,OAAO,SAAS,YAAY,CAAC,MAC/B,MAAM,IAAI,UAAU,wCAAwC;CAG9D,IAAI,mBAAmB,KAAA,GAAW;EAChC,MAAM,MAAM,KAAK,IAAI,aAAa,kBAAkB;EACpD,IAAI,OAAO,mBAAmB,YAAY,kBAAkB,KAC1D,MAAM,IAAI,UACR,+CAA+C,IAAI,GACrD;CAEJ;AACF"}
@@ -236,6 +236,15 @@ export interface ZeroTxData {
236
236
  ivmSources: unknown;
237
237
  token: string | undefined;
238
238
  context: unknown;
239
+ /**
240
+ * A cheap copy, used for one mutation's speculative writes.
241
+ *
242
+ * Replaying a mutation writes to two places: Replicache's `Write` and the
243
+ * IVM sources held here. If the mutator throws, the `Write` is discarded,
244
+ * and the fork lets the IVM writes be discarded with it. The caller adopts
245
+ * the fork when the mutator succeeds and drops it when it throws.
246
+ */
247
+ fork(): ZeroTxData;
239
248
  }
240
249
  export type ZeroReadOptions = {
241
250
  openLazyRead?: Read | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"replicache-options.d.ts","sourceRoot":"","sources":["../../../../replicache/src/replicache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,kBAAkB,CAAC,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACvE,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE,EAAE,EAAE,OAAO,GAAG,IAAI,CAAC;CAC7D"}
@@ -16,5 +16,7 @@ export declare function wrapIterable<T>(iter: Iterable<T>): IteratorWithHelpers<
16
16
  */
17
17
  export declare function toSorted<T>(iter: Iterable<T>, compare?: (a: T, b: T) => number): T[];
18
18
  export declare function some<T>(iterable: Iterable<T>, predicate: (item: T, index: number) => boolean): boolean;
19
+ export declare const emptyIterator: IterableIterator<any, undefined, any>;
20
+ export declare function makeEmptyIteratorWithReturn<T>(value: T): IterableIterator<any, T, any>;
19
21
  export {};
20
22
  //# sourceMappingURL=iterables.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"iterables.d.ts","sourceRoot":"","sources":["../../../../shared/src/iterables.ts"],"names":[],"mappings":"AAAA,wBAAiB,aAAa,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,2BAIxD;AAwBD,wBAAgB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,CAK3D;AAED,wBAAiB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAOzD;AAKD,KAAK,mBAAmB,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG;IAC1C,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAC9D,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,mBAAmB,CAAC,CAAC,CAAC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AE,KAAK,EAAE,MAAM,KAAK,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAC9D,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;IACpE,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC;IACnD,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,mBAAmB,CAAC,CAAC,CAAC,CAAC;CAC7C,CAAC;AA6CF,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAEzE;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EACxB,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,EACjB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,MAAM,GAC/B,CAAC,EAAE,CAGL;AAED,wBAAgB,IAAI,CAAC,CAAC,EACpB,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,GAC7C,OAAO,CAQT;AAuBD,eAAO,MAAM,aAAa,EAAE,gBAAgB,CAAC,GAAG,EAAE,SAAS,EAAE,GAAG,CACxB,CAAC;AAEzC,wBAAgB,2BAA2B,CAAC,CAAC,EAC3C,KAAK,EAAE,CAAC,GAEP,gBAAgB,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,CAE/B"}
@@ -55,7 +55,24 @@ function some(iterable, predicate) {
55
55
  for (const item of iterable) if (predicate(item, index++)) return true;
56
56
  return false;
57
57
  }
58
+ var EmptyIteratorWithReturn = class {
59
+ value;
60
+ done = true;
61
+ constructor(value) {
62
+ this.value = value;
63
+ }
64
+ [Symbol.iterator]() {
65
+ return this;
66
+ }
67
+ next() {
68
+ return this;
69
+ }
70
+ };
71
+ var emptyIterator = new EmptyIteratorWithReturn(void 0);
72
+ function makeEmptyIteratorWithReturn(value) {
73
+ return new EmptyIteratorWithReturn(value);
74
+ }
58
75
  //#endregion
59
- export { joinIterables, once, some, toSorted, wrapIterable };
76
+ export { emptyIterator, joinIterables, makeEmptyIteratorWithReturn, once, some, toSorted, wrapIterable };
60
77
 
61
78
  //# sourceMappingURL=iterables.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"iterables.js","names":["#iterator"],"sources":["../../../../shared/src/iterables.ts"],"sourcesContent":["export function* joinIterables<T>(...iters: Iterable<T>[]) {\n for (const iter of iters) {\n yield* iter;\n }\n}\n\nfunction* filterIter<T>(\n iter: Iterable<T>,\n p: (t: T, index: number) => boolean,\n): Iterable<T> {\n let index = 0;\n for (const t of iter) {\n if (p(t, index++)) {\n yield t;\n }\n }\n}\n\nfunction* mapIter<T, U>(\n iter: Iterable<T>,\n f: (t: T, index: number) => U,\n): Iterable<U> {\n let index = 0;\n for (const t of iter) {\n yield f(t, index++);\n }\n}\n\nexport function first<T>(stream: Iterable<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n\nexport function* once<T>(stream: Iterable<T>): Iterable<T> {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n if (value !== undefined) {\n yield value;\n }\n it.return?.();\n}\n\n// ES2024 Iterator helpers are available in Node 22+ and part of ES2024.\n// https://github.com/tc39/proposal-iterator-helpers\n\ntype IteratorWithHelpers<T> = Iterator<T> & {\n map<U>(f: (t: T, index: number) => U): IteratorWithHelpers<U>;\n filter(p: (t: T, index: number) => boolean): IteratorWithHelpers<T>;\n some(p: (t: T, index: number) => boolean): boolean;\n [Symbol.iterator](): IteratorWithHelpers<T>;\n};\n\ntype IteratorConstructor = {\n from<T>(this: void, iter: Iterable<T>): IteratorWithHelpers<T>;\n};\n\n// Check if native Iterator.from is available and bind it once at startup\n// We use globalThis to access the runtime value safely\nconst iteratorCtor = (globalThis as {Iterator?: IteratorConstructor}).Iterator;\nconst nativeIteratorFrom = iteratorCtor?.from as\n | (<T>(iter: Iterable<T>) => IteratorWithHelpers<T>)\n | undefined;\n\nconst iteratorFrom: <T>(e: Iterable<T>) => IteratorWithHelpers<T> =\n nativeIteratorFrom ?? (e => new IterWrapper(e));\n\n// Fallback implementation for environments without ES2024 Iterator helpers\nclass IterWrapper<T> implements IteratorWithHelpers<T>, IterableIterator<T> {\n readonly #iterator: Iterator<T>;\n\n constructor(iterable: Iterable<T>) {\n this.#iterator = iterable[Symbol.iterator]();\n }\n\n next(): IteratorResult<T> {\n return this.#iterator.next();\n }\n\n [Symbol.iterator](): IteratorWithHelpers<T> {\n return this;\n }\n\n map<U>(f: (t: T, index: number) => U): IterWrapper<U> {\n return new IterWrapper(mapIter(this, f));\n }\n\n filter(p: (t: T, index: number) => boolean): IterWrapper<T> {\n return new IterWrapper(filterIter(this, p));\n }\n\n some(p: (t: T, index: number) => boolean): boolean {\n return some(this, p);\n }\n}\n\nexport function wrapIterable<T>(iter: Iterable<T>): IteratorWithHelpers<T> {\n return iteratorFrom(iter);\n}\n\n/**\n * This will make a new array where the elements are the same as the iterable\n * but sorted according to the compare function. If the compare function is not\n * provided, it will sort the elements in JS standard way which is string\n * compare.\n */\nexport function toSorted<T>(\n iter: Iterable<T>,\n compare?: (a: T, b: T) => number,\n): T[] {\n // oxlint-disable-next-line e18e/prefer-array-to-sorted\n return [...iter].sort(compare);\n}\n\nexport function some<T>(\n iterable: Iterable<T>,\n predicate: (item: T, index: number) => boolean,\n): boolean {\n let index = 0;\n for (const item of iterable) {\n if (predicate(item, index++)) {\n return true;\n }\n }\n return false;\n}\n"],"mappings":";AAAA,UAAiB,cAAiB,GAAG,OAAsB;CACzD,KAAK,MAAM,QAAQ,OACjB,OAAO;AAEX;AAEA,UAAU,WACR,MACA,GACa;CACb,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,MACd,IAAI,EAAE,GAAG,OAAO,GACd,MAAM;AAGZ;AAEA,UAAU,QACR,MACA,GACa;CACb,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,MACd,MAAM,EAAE,GAAG,OAAO;AAEtB;AASA,UAAiB,KAAQ,QAAkC;CACzD,MAAM,KAAK,OAAO,OAAO,UAAU;CACnC,MAAM,EAAC,UAAS,GAAG,KAAK;CACxB,IAAI,UAAU,KAAA,GACZ,MAAM;CAER,GAAG,SAAS;AACd;AAuBA,IAAM,eALgB,WAAgD,UAC7B,UAKhB,MAAK,IAAI,YAAY,CAAC;AAG/C,IAAM,cAAN,MAAM,YAAsE;CAC1E;CAEA,YAAY,UAAuB;EACjC,KAAKA,YAAY,SAAS,OAAO,UAAU;CAC7C;CAEA,OAA0B;EACxB,OAAO,KAAKA,UAAU,KAAK;CAC7B;CAEA,CAAC,OAAO,YAAoC;EAC1C,OAAO;CACT;CAEA,IAAO,GAA+C;EACpD,OAAO,IAAI,YAAY,QAAQ,MAAM,CAAC,CAAC;CACzC;CAEA,OAAO,GAAqD;EAC1D,OAAO,IAAI,YAAY,WAAW,MAAM,CAAC,CAAC;CAC5C;CAEA,KAAK,GAA8C;EACjD,OAAO,KAAK,MAAM,CAAC;CACrB;AACF;AAEA,SAAgB,aAAgB,MAA2C;CACzE,OAAO,aAAa,IAAI;AAC1B;;;;;;;AAQA,SAAgB,SACd,MACA,SACK;CAEL,OAAO,CAAC,GAAG,IAAI,EAAE,KAAK,OAAO;AAC/B;AAEA,SAAgB,KACd,UACA,WACS;CACT,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,UACjB,IAAI,UAAU,MAAM,OAAO,GACzB,OAAO;CAGX,OAAO;AACT"}
1
+ {"version":3,"file":"iterables.js","names":["#iterator"],"sources":["../../../../shared/src/iterables.ts"],"sourcesContent":["export function* joinIterables<T>(...iters: Iterable<T>[]) {\n for (const iter of iters) {\n yield* iter;\n }\n}\n\nfunction* filterIter<T>(\n iter: Iterable<T>,\n p: (t: T, index: number) => boolean,\n): Iterable<T> {\n let index = 0;\n for (const t of iter) {\n if (p(t, index++)) {\n yield t;\n }\n }\n}\n\nfunction* mapIter<T, U>(\n iter: Iterable<T>,\n f: (t: T, index: number) => U,\n): Iterable<U> {\n let index = 0;\n for (const t of iter) {\n yield f(t, index++);\n }\n}\n\nexport function first<T>(stream: Iterable<T>): T | undefined {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n it.return?.();\n return value;\n}\n\nexport function* once<T>(stream: Iterable<T>): Iterable<T> {\n const it = stream[Symbol.iterator]();\n const {value} = it.next();\n if (value !== undefined) {\n yield value;\n }\n it.return?.();\n}\n\n// ES2024 Iterator helpers are available in Node 22+ and part of ES2024.\n// https://github.com/tc39/proposal-iterator-helpers\n\ntype IteratorWithHelpers<T> = Iterator<T> & {\n map<U>(f: (t: T, index: number) => U): IteratorWithHelpers<U>;\n filter(p: (t: T, index: number) => boolean): IteratorWithHelpers<T>;\n some(p: (t: T, index: number) => boolean): boolean;\n [Symbol.iterator](): IteratorWithHelpers<T>;\n};\n\ntype IteratorConstructor = {\n from<T>(this: void, iter: Iterable<T>): IteratorWithHelpers<T>;\n};\n\n// Check if native Iterator.from is available and bind it once at startup\n// We use globalThis to access the runtime value safely\nconst iteratorCtor = (globalThis as {Iterator?: IteratorConstructor}).Iterator;\nconst nativeIteratorFrom = iteratorCtor?.from as\n | (<T>(iter: Iterable<T>) => IteratorWithHelpers<T>)\n | undefined;\n\nconst iteratorFrom: <T>(e: Iterable<T>) => IteratorWithHelpers<T> =\n nativeIteratorFrom ?? (e => new IterWrapper(e));\n\n// Fallback implementation for environments without ES2024 Iterator helpers\nclass IterWrapper<T> implements IteratorWithHelpers<T>, IterableIterator<T> {\n readonly #iterator: Iterator<T>;\n\n constructor(iterable: Iterable<T>) {\n this.#iterator = iterable[Symbol.iterator]();\n }\n\n next(): IteratorResult<T> {\n return this.#iterator.next();\n }\n\n [Symbol.iterator](): IteratorWithHelpers<T> {\n return this;\n }\n\n map<U>(f: (t: T, index: number) => U): IterWrapper<U> {\n return new IterWrapper(mapIter(this, f));\n }\n\n filter(p: (t: T, index: number) => boolean): IterWrapper<T> {\n return new IterWrapper(filterIter(this, p));\n }\n\n some(p: (t: T, index: number) => boolean): boolean {\n return some(this, p);\n }\n}\n\nexport function wrapIterable<T>(iter: Iterable<T>): IteratorWithHelpers<T> {\n return iteratorFrom(iter);\n}\n\n/**\n * This will make a new array where the elements are the same as the iterable\n * but sorted according to the compare function. If the compare function is not\n * provided, it will sort the elements in JS standard way which is string\n * compare.\n */\nexport function toSorted<T>(\n iter: Iterable<T>,\n compare?: (a: T, b: T) => number,\n): T[] {\n // oxlint-disable-next-line e18e/prefer-array-to-sorted\n return [...iter].sort(compare);\n}\n\nexport function some<T>(\n iterable: Iterable<T>,\n predicate: (item: T, index: number) => boolean,\n): boolean {\n let index = 0;\n for (const item of iterable) {\n if (predicate(item, index++)) {\n return true;\n }\n }\n return false;\n}\n\nclass EmptyIteratorWithReturn<T>\n // oxlint-disable-next-line typescript/no-explicit-any\n implements IterableIterator<any, T, any>, IteratorReturnResult<T>\n{\n readonly value: T;\n readonly done = true;\n\n constructor(value: T) {\n this.value = value;\n }\n\n [Symbol.iterator]() {\n return this;\n }\n\n next() {\n return this;\n }\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any\nexport const emptyIterator: IterableIterator<any, undefined, any> =\n new EmptyIteratorWithReturn(undefined);\n\nexport function makeEmptyIteratorWithReturn<T>(\n value: T,\n // oxlint-disable-next-line typescript/no-explicit-any\n): IterableIterator<any, T, any> {\n return new EmptyIteratorWithReturn(value);\n}\n"],"mappings":";AAAA,UAAiB,cAAiB,GAAG,OAAsB;CACzD,KAAK,MAAM,QAAQ,OACjB,OAAO;AAEX;AAEA,UAAU,WACR,MACA,GACa;CACb,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK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,gBACX,IAAI,wBAAwB,KAAA,CAAS;AAEvC,SAAgB,4BACd,OAE+B;CAC/B,OAAO,IAAI,wBAAwB,KAAK;AAC1C"}
@@ -14,6 +14,10 @@ export declare class RingBuffer<T> {
14
14
  constructor(initialCapacity?: number);
15
15
  get size(): number;
16
16
  push(value: T): void;
17
+ /** Returns the last element, or `undefined` if empty. */
18
+ last(): T | undefined;
19
+ /** Replaces the last element, or appends it if empty. */
20
+ replaceLast(value: T): void;
17
21
  /** Removes and returns the front element, or `undefined` if empty. */
18
22
  shift(): T | undefined;
19
23
  /**
@@ -28,5 +32,9 @@ export declare class RingBuffer<T> {
28
32
  * Removes and returns all elements in FIFO order, resetting the buffer.
29
33
  */
30
34
  drain(): T[];
35
+ /** Copies all elements in FIFO order without removing them. */
36
+ toArray(): T[];
37
+ /** Removes all elements and releases extra capacity. */
38
+ clear(): void;
31
39
  }
32
40
  //# sourceMappingURL=ring-buffer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ring-buffer.d.ts","sourceRoot":"","sources":["../../../../shared/src/ring-buffer.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;GAUG;AACH,qBAAa,UAAU,CAAC,CAAC;;IAMvB,YAAY,eAAe,SAA2B,EAGrD;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAMnB;IAED,sEAAsE;IACtE,KAAK,IAAI,CAAC,GAAG,SAAS,CAmBrB;IAED;;;;;;OAMG;IACH,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAoBvB;IAED;;OAEG;IACH,KAAK,IAAI,CAAC,EAAE,CASX;CA0CF"}
1
+ {"version":3,"file":"ring-buffer.d.ts","sourceRoot":"","sources":["../../../../shared/src/ring-buffer.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;GAUG;AACH,qBAAa,UAAU,CAAC,CAAC;;IAMvB,YAAY,eAAe,SAA2B,EAGrD;IAED,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAMnB;IAED,yDAAyD;IACzD,IAAI,IAAI,CAAC,GAAG,SAAS,CAIpB;IAED,yDAAyD;IACzD,WAAW,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAM1B;IAED,sEAAsE;IACtE,KAAK,IAAI,CAAC,GAAG,SAAS,CAmBrB;IAED;;;;;;OAMG;IACH,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAoBvB;IAED;;OAEG;IACH,KAAK,IAAI,CAAC,EAAE,CAMX;IAED,+DAA+D;IAC/D,OAAO,IAAI,CAAC,EAAE,CAMb;IAED,wDAAwD;IACxD,KAAK,IAAI,IAAI,CAKZ;CA0CF"}
@@ -29,6 +29,15 @@ var RingBuffer = class {
29
29
  this.#buffer[(this.#head + this.#size) % this.#capacity] = value;
30
30
  this.#size++;
31
31
  }
32
+ /** Returns the last element, or `undefined` if empty. */
33
+ last() {
34
+ return this.#size === 0 ? void 0 : this.#buffer[(this.#head + this.#size - 1) % this.#capacity];
35
+ }
36
+ /** Replaces the last element, or appends it if empty. */
37
+ replaceLast(value) {
38
+ if (this.#size === 0) this.push(value);
39
+ else this.#buffer[(this.#head + this.#size - 1) % this.#capacity] = value;
40
+ }
32
41
  /** Removes and returns the front element, or `undefined` if empty. */
33
42
  shift() {
34
43
  if (this.#size === 0) return;
@@ -65,12 +74,24 @@ var RingBuffer = class {
65
74
  * Removes and returns all elements in FIFO order, resetting the buffer.
66
75
  */
67
76
  drain() {
77
+ const result = this.toArray();
78
+ this.#head = 0;
79
+ this.#size = 0;
80
+ this.#buffer = Array.from({ length: this.#capacity });
81
+ return result;
82
+ }
83
+ /** Copies all elements in FIFO order without removing them. */
84
+ toArray() {
68
85
  const result = Array.from({ length: this.#size });
69
86
  for (let i = 0; i < this.#size; i++) result[i] = this.#buffer[(this.#head + i) % this.#capacity];
87
+ return result;
88
+ }
89
+ /** Removes all elements and releases extra capacity. */
90
+ clear() {
70
91
  this.#head = 0;
71
92
  this.#size = 0;
93
+ this.#capacity = MIN_CAPACITY;
72
94
  this.#buffer = Array.from({ length: this.#capacity });
73
- return result;
74
95
  }
75
96
  /**
76
97
  * Grows the buffer in place by doubling its length and relocating
@@ -1 +1 @@
1
- {"version":3,"file":"ring-buffer.js","names":["#capacity","#buffer","#size","#grow","#head","#shrink"],"sources":["../../../../shared/src/ring-buffer.ts"],"sourcesContent":["const DEFAULT_INITIAL_CAPACITY = 16;\nconst MIN_CAPACITY = 16;\n\n/**\n * A FIFO ring buffer backed by a circular array. Provides:\n *\n * - `push()` — O(1) amortized (O(n) on resize)\n * - `shift()` — O(1)\n * - `size` — O(1)\n * - `drain()` — O(n)\n *\n * The buffer grows (doubles) when full and shrinks (halves) when\n * utilization drops below 25%, bounded by {@link MIN_CAPACITY}.\n */\nexport class RingBuffer<T> {\n #buffer: (T | undefined)[];\n #head = 0;\n #size = 0;\n #capacity: number;\n\n constructor(initialCapacity = DEFAULT_INITIAL_CAPACITY) {\n this.#capacity = Math.max(MIN_CAPACITY, initialCapacity);\n this.#buffer = Array.from({length: initialCapacity});\n }\n\n get size(): number {\n return this.#size;\n }\n\n push(value: T): void {\n if (this.#size === this.#capacity) {\n this.#grow();\n }\n this.#buffer[(this.#head + this.#size) % this.#capacity] = value;\n this.#size++;\n }\n\n /** Removes and returns the front element, or `undefined` if empty. */\n shift(): T | undefined {\n if (this.#size === 0) {\n return undefined;\n }\n const value = this.#buffer[this.#head];\n this.#buffer[this.#head] = undefined; // allow GC of removed element\n this.#head = (this.#head + 1) % this.#capacity;\n this.#size--;\n\n // Shrink when utilization drops below 25%, keeping a minimum capacity.\n if (\n this.#size > 0 &&\n this.#size < this.#capacity >> 2 &&\n this.#capacity > MIN_CAPACITY\n ) {\n this.#shrink();\n }\n\n return value;\n }\n\n /**\n * Removes all elements matching `value` (by identity `===`).\n *\n * This is O(n) — suitable for rare operations like cancellation.\n *\n * @returns The number of elements removed.\n */\n delete(value: T): number {\n if (this.#size === 0) {\n return 0;\n }\n // Rebuild the buffer without matching elements.\n const newBuffer: (T | undefined)[] = Array.from({length: this.#capacity});\n let newSize = 0;\n let count = 0;\n for (let i = 0; i < this.#size; i++) {\n const item = this.#buffer[(this.#head + i) % this.#capacity];\n if (item === value) {\n count++;\n } else {\n newBuffer[newSize++] = item;\n }\n }\n this.#buffer = newBuffer;\n this.#head = 0;\n this.#size = newSize;\n return count;\n }\n\n /**\n * Removes and returns all elements in FIFO order, resetting the buffer.\n */\n drain(): T[] {\n const result = Array.from<T>({length: this.#size});\n for (let i = 0; i < this.#size; i++) {\n result[i] = this.#buffer[(this.#head + i) % this.#capacity] as T;\n }\n this.#head = 0;\n this.#size = 0;\n this.#buffer = Array.from({length: this.#capacity});\n return result;\n }\n\n /**\n * Grows the buffer in place by doubling its length and relocating\n * only the wrapped-around elements (those before #head) into the\n * newly available space. No new array is allocated.\n */\n #grow(): void {\n const oldLen = this.#buffer.length;\n const newLen = oldLen * 2;\n this.#buffer.length = newLen;\n this.#capacity = newLen;\n\n // Copy wrapped-around elements (indices 0..head-1) into the new space.\n for (let i = 0; i < this.#head; i++) {\n this.#buffer[oldLen + i] = this.#buffer[i];\n this.#buffer[i] = undefined; // ensure gc when the element is removed\n }\n }\n\n /**\n * Shrinks the buffer in place by halving its length. Elements whose\n * indices fall in the removed half are relocated into the lower half,\n * then the array is truncated.\n */\n #shrink(): void {\n const oldLen = this.#buffer.length;\n const newLen = Math.max(MIN_CAPACITY, oldLen >> 1);\n\n // Move elements that sit in the upper half down by newLen.\n const left = Math.max(newLen, this.#head);\n const right = Math.min(this.#head + this.#size, oldLen);\n for (let i = left; i < right; i++) {\n this.#buffer[i - newLen] = this.#buffer[i];\n }\n\n if (this.#head >= newLen) {\n this.#head -= newLen;\n }\n this.#buffer.length = newLen;\n this.#capacity = newLen;\n }\n}\n"],"mappings":";AAAA,IAAM,2BAA2B;AACjC,IAAM,eAAe;;;;;;;;;;;;AAar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AAK,KAAKD,SAAS,KAAKG,QAAQ,KAAK,KAAKJ;EAEnD,KAAKI,QAAQ;EACb,KAAKF,QAAQ;EACb,KAAKD,UAAU,MAAM,KAAK,EAAC,QAAQ,KAAKD,UAAS,CAAC;EAClD,OAAO;CACT;;;;;;CAOA,QAAc;EACZ,MAAM,SAAS,KAAKC,QAAQ;EAC5B,MAAM,SAAS,SAAS;EACxB,KAAKA,QAAQ,SAAS;EACtB,KAAKD,YAAY;EAGjB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAKI,OAAO,KAAK;GACnC,KAAKH,QAAQ,SAAS,KAAK,KAAKA,QAAQ;GACxC,KAAKA,QAAQ,KAAK,KAAA;EACpB;CACF;;;;;;CAOA,UAAgB;EACd,MAAM,SAAS,KAAKA,QAAQ;EAC5B,MAAM,SAAS,KAAK,IAAI,cAAc,UAAU,CAAC;EAGjD,MAAM,OAAO,KAAK,IAAI,QAAQ,KAAKG,KAAK;EACxC,MAAM,QAAQ,KAAK,IAAI,KAAKA,QAAQ,KAAKF,OAAO,MAAM;EACtD,KAAK,IAAI,IAAI,MAAM,IAAI,OAAO,KAC5B,KAAKD,QAAQ,IAAI,UAAU,KAAKA,QAAQ;EAG1C,IAAI,KAAKG,SAAS,QAChB,KAAKA,SAAS;EAEhB,KAAKH,QAAQ,SAAS;EACtB,KAAKD,YAAY;CACnB;AACF"}
1
+ {"version":3,"file":"ring-buffer.js","names":["#capacity","#buffer","#size","#grow","#head","#shrink"],"sources":["../../../../shared/src/ring-buffer.ts"],"sourcesContent":["const DEFAULT_INITIAL_CAPACITY = 16;\nconst MIN_CAPACITY = 16;\n\n/**\n * A FIFO ring buffer backed by a circular array. Provides:\n *\n * - `push()` — O(1) amortized (O(n) on resize)\n * - `shift()` — O(1)\n * - `size` — O(1)\n * - `drain()` — O(n)\n *\n * The buffer grows (doubles) when full and shrinks (halves) when\n * utilization drops below 25%, bounded by {@link MIN_CAPACITY}.\n */\nexport class RingBuffer<T> {\n #buffer: (T | undefined)[];\n #head = 0;\n #size = 0;\n #capacity: number;\n\n constructor(initialCapacity = DEFAULT_INITIAL_CAPACITY) {\n this.#capacity = Math.max(MIN_CAPACITY, initialCapacity);\n this.#buffer = Array.from({length: initialCapacity});\n }\n\n get size(): number {\n return this.#size;\n }\n\n push(value: T): void {\n if (this.#size === this.#capacity) {\n this.#grow();\n }\n this.#buffer[(this.#head + this.#size) % this.#capacity] = value;\n this.#size++;\n }\n\n /** Returns the last element, or `undefined` if empty. */\n last(): T | undefined {\n return this.#size === 0\n ? undefined\n : this.#buffer[(this.#head + this.#size - 1) % this.#capacity];\n }\n\n /** Replaces the last element, or appends it if empty. */\n replaceLast(value: T): void {\n if (this.#size === 0) {\n this.push(value);\n } else {\n this.#buffer[(this.#head + this.#size - 1) % this.#capacity] = value;\n }\n }\n\n /** Removes and returns the front element, or `undefined` if empty. */\n shift(): T | undefined {\n if (this.#size === 0) {\n return undefined;\n }\n const value = this.#buffer[this.#head];\n this.#buffer[this.#head] = undefined; // allow GC of removed element\n this.#head = (this.#head + 1) % this.#capacity;\n this.#size--;\n\n // Shrink when utilization drops below 25%, keeping a minimum capacity.\n if (\n this.#size > 0 &&\n this.#size < this.#capacity >> 2 &&\n this.#capacity > MIN_CAPACITY\n ) {\n this.#shrink();\n }\n\n return value;\n }\n\n /**\n * Removes all elements matching `value` (by identity `===`).\n *\n * This is O(n) — suitable for rare operations like cancellation.\n *\n * @returns The number of elements removed.\n */\n delete(value: T): number {\n if (this.#size === 0) {\n return 0;\n }\n // Rebuild the buffer without matching elements.\n const newBuffer: (T | undefined)[] = Array.from({length: this.#capacity});\n let newSize = 0;\n let count = 0;\n for (let i = 0; i < this.#size; i++) {\n const item = this.#buffer[(this.#head + i) % this.#capacity];\n if (item === value) {\n count++;\n } else {\n newBuffer[newSize++] = item;\n }\n }\n this.#buffer = newBuffer;\n this.#head = 0;\n this.#size = newSize;\n return count;\n }\n\n /**\n * Removes and returns all elements in FIFO order, resetting the buffer.\n */\n drain(): T[] {\n const result = this.toArray();\n this.#head = 0;\n this.#size = 0;\n this.#buffer = Array.from({length: this.#capacity});\n return result;\n }\n\n /** Copies all elements in FIFO order without removing them. */\n toArray(): T[] {\n const result = Array.from<T>({length: this.#size});\n for (let i = 0; i < this.#size; i++) {\n result[i] = this.#buffer[(this.#head + i) % this.#capacity] as T;\n }\n return result;\n }\n\n /** Removes all elements and releases extra capacity. */\n clear(): void {\n this.#head = 0;\n this.#size = 0;\n this.#capacity = MIN_CAPACITY;\n this.#buffer = Array.from({length: this.#capacity});\n }\n\n /**\n * Grows the buffer in place by doubling its length and relocating\n * only the wrapped-around elements (those before #head) into the\n * newly available space. No new array is allocated.\n */\n #grow(): void {\n const oldLen = this.#buffer.length;\n const newLen = oldLen * 2;\n this.#buffer.length = newLen;\n this.#capacity = newLen;\n\n // Copy wrapped-around elements (indices 0..head-1) into the new space.\n for (let i = 0; i < this.#head; i++) {\n this.#buffer[oldLen + i] = this.#buffer[i];\n this.#buffer[i] = undefined; // ensure gc when the element is removed\n }\n }\n\n /**\n * Shrinks the buffer in place by halving its length. Elements whose\n * indices fall in the removed half are relocated into the lower half,\n * then the array is truncated.\n */\n #shrink(): void {\n const oldLen = this.#buffer.length;\n const newLen = Math.max(MIN_CAPACITY, oldLen >> 1);\n\n // Move elements that sit in the upper half down by newLen.\n const left = Math.max(newLen, this.#head);\n const right = Math.min(this.#head + this.#size, oldLen);\n for (let i = left; i < right; i++) {\n this.#buffer[i - newLen] = this.#buffer[i];\n }\n\n if (this.#head >= newLen) {\n this.#head -= newLen;\n }\n this.#buffer.length = newLen;\n this.#capacity = newLen;\n }\n}\n"],"mappings":";AAAA,IAAM,2BAA2B;AACjC,IAAM,eAAe;;;;;;;;;;;;AAarB,IAAa,aAAb,MAA2B;CACzB;CACA,QAAQ;CACR,QAAQ;CACR;CAEA,YAAY,kBAAkB,0BAA0B;EACtD,KAAKA,YAAY,KAAK,IAAI,cAAc,eAAe;EACvD,KAAKC,UAAU,MAAM,KAAK,EAAC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version: "1.11.0-canary.9",
4
4
  description: "Zero is a web framework for serverless web development.",
5
5
  homepage: "https://zero.rocicorp.dev",
6
6
  bugs: { "url": "https://bugs.rocicorp.dev" },
@@ -166,7 +166,6 @@ var package_default = {
166
166
  },
167
167
  devDependencies: {
168
168
  "@op-engineering/op-sqlite": ">=15",
169
- "@vitest/runner": "^4.1.6",
170
169
  "analyze-query": "workspace:*",
171
170
  "ast-to-zql": "workspace:*",
172
171
  "expo-sqlite": ">=15",
@@ -177,7 +176,7 @@ var package_default = {
177
176
  "typedoc": "^0.28.17",
178
177
  "typescript": "~7.0.2",
179
178
  "vite": "^8.0.13",
180
- "vitest": "^4.1.6",
179
+ "vitest": "^5.0.0",
181
180
  "zero-cache": "workspace:*",
182
181
  "zero-client": "workspace:*",
183
182
  "zero-pg": "workspace:*",