@rocicorp/zero 0.26.0 → 0.26.1-canary.11

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 (149) hide show
  1. package/out/analyze-query/src/run-ast.d.ts.map +1 -1
  2. package/out/analyze-query/src/run-ast.js +4 -1
  3. package/out/analyze-query/src/run-ast.js.map +1 -1
  4. package/out/replicache/src/btree/node.js +4 -4
  5. package/out/replicache/src/btree/node.js.map +1 -1
  6. package/out/replicache/src/btree/write.js +2 -2
  7. package/out/replicache/src/btree/write.js.map +1 -1
  8. package/out/replicache/src/dag/gc.js +5 -2
  9. package/out/replicache/src/dag/gc.js.map +1 -1
  10. package/out/replicache/src/db/write.d.ts.map +1 -1
  11. package/out/replicache/src/db/write.js +21 -6
  12. package/out/replicache/src/db/write.js.map +1 -1
  13. package/out/replicache/src/error-responses.d.ts.map +1 -1
  14. package/out/replicache/src/error-responses.js +4 -1
  15. package/out/replicache/src/error-responses.js.map +1 -1
  16. package/out/replicache/src/persist/clients.d.ts.map +1 -1
  17. package/out/replicache/src/persist/clients.js +4 -1
  18. package/out/replicache/src/persist/clients.js.map +1 -1
  19. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  20. package/out/replicache/src/persist/collect-idb-databases.js +2 -1
  21. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  22. package/out/replicache/src/persist/idb-databases-store.d.ts.map +1 -1
  23. package/out/replicache/src/persist/idb-databases-store.js +4 -1
  24. package/out/replicache/src/persist/idb-databases-store.js.map +1 -1
  25. package/out/replicache/src/process-scheduler.js +4 -1
  26. package/out/replicache/src/process-scheduler.js.map +1 -1
  27. package/out/replicache/src/replicache-impl.js +2 -2
  28. package/out/replicache/src/replicache-impl.js.map +1 -1
  29. package/out/replicache/src/subscriptions.d.ts.map +1 -1
  30. package/out/replicache/src/subscriptions.js +5 -2
  31. package/out/replicache/src/subscriptions.js.map +1 -1
  32. package/out/replicache/src/sync/diff.d.ts.map +1 -1
  33. package/out/replicache/src/sync/diff.js +4 -1
  34. package/out/replicache/src/sync/diff.js.map +1 -1
  35. package/out/replicache/src/sync/pull.d.ts.map +1 -1
  36. package/out/replicache/src/sync/pull.js +4 -1
  37. package/out/replicache/src/sync/pull.js.map +1 -1
  38. package/out/replicache/src/sync/push.d.ts.map +1 -1
  39. package/out/replicache/src/sync/push.js +5 -2
  40. package/out/replicache/src/sync/push.js.map +1 -1
  41. package/out/shared/src/asserts.d.ts +1 -1
  42. package/out/shared/src/asserts.d.ts.map +1 -1
  43. package/out/shared/src/asserts.js +1 -1
  44. package/out/shared/src/asserts.js.map +1 -1
  45. package/out/z2s/src/compiler.d.ts.map +1 -1
  46. package/out/z2s/src/compiler.js +8 -2
  47. package/out/z2s/src/compiler.js.map +1 -1
  48. package/out/zero/package.json.js +1 -1
  49. package/out/zero-cache/src/config/zero-config.d.ts +4 -0
  50. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  51. package/out/zero-cache/src/config/zero-config.js +17 -0
  52. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  53. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  54. package/out/zero-cache/src/db/transaction-pool.js +17 -11
  55. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  56. package/out/zero-cache/src/observability/events.d.ts.map +1 -1
  57. package/out/zero-cache/src/observability/events.js +28 -9
  58. package/out/zero-cache/src/observability/events.js.map +1 -1
  59. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  60. package/out/zero-cache/src/server/change-streamer.js +3 -1
  61. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  62. package/out/zero-cache/src/services/analyze.js +1 -0
  63. package/out/zero-cache/src/services/analyze.js.map +1 -1
  64. package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +29 -14
  66. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  67. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +6 -1
  68. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +69 -25
  70. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  71. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  72. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +6 -1
  73. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  74. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/change-source/pg/schema/init.js +12 -8
  76. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  77. package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +26 -0
  78. package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts.map +1 -1
  79. package/out/zero-cache/src/services/change-source/protocol/current/data.js +15 -3
  80. package/out/zero-cache/src/services/change-source/protocol/current/data.js.map +1 -1
  81. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +30 -0
  82. package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/change-source/protocol/current.js +2 -1
  84. package/out/zero-cache/src/services/change-streamer/broadcast.d.ts +100 -0
  85. package/out/zero-cache/src/services/change-streamer/broadcast.d.ts.map +1 -0
  86. package/out/zero-cache/src/services/change-streamer/broadcast.js +171 -0
  87. package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -0
  88. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +1 -1
  89. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  90. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +22 -9
  91. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  92. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +10 -0
  93. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +17 -1
  95. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
  96. package/out/zero-cache/src/services/change-streamer/forwarder.js +52 -4
  97. package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
  98. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +18 -0
  99. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  100. package/out/zero-cache/src/services/change-streamer/subscriber.js +68 -12
  101. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  102. package/out/zero-cache/src/services/replicator/change-processor.d.ts +2 -0
  103. package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
  104. package/out/zero-cache/src/services/replicator/change-processor.js +8 -6
  105. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  106. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  107. package/out/zero-cache/src/services/replicator/incremental-sync.js +39 -1
  108. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  109. package/out/zero-cache/src/services/replicator/replication-status.d.ts +4 -3
  110. package/out/zero-cache/src/services/replicator/replication-status.d.ts.map +1 -1
  111. package/out/zero-cache/src/services/replicator/replication-status.js +25 -10
  112. package/out/zero-cache/src/services/replicator/replication-status.js.map +1 -1
  113. package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
  114. package/out/zero-cache/src/services/run-ast.js +22 -2
  115. package/out/zero-cache/src/services/run-ast.js.map +1 -1
  116. package/out/zero-cache/src/services/running-state.d.ts +1 -0
  117. package/out/zero-cache/src/services/running-state.d.ts.map +1 -1
  118. package/out/zero-cache/src/services/running-state.js +4 -0
  119. package/out/zero-cache/src/services/running-state.js.map +1 -1
  120. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  121. package/out/zero-cache/src/services/view-syncer/cvr.js +8 -2
  122. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  123. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  124. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +10 -1
  125. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  126. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +1 -1
  127. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  128. package/out/zero-cache/src/services/view-syncer/snapshotter.js +15 -7
  129. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  130. package/out/zero-cache/src/types/subscription.d.ts +3 -1
  131. package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
  132. package/out/zero-cache/src/types/subscription.js +21 -9
  133. package/out/zero-cache/src/types/subscription.js.map +1 -1
  134. package/out/zero-client/src/client/http-string.js.map +1 -1
  135. package/out/zero-client/src/client/version.js +1 -1
  136. package/out/zero-client/src/client/zero.js.map +1 -1
  137. package/out/zero-events/src/status.d.ts +8 -0
  138. package/out/zero-events/src/status.d.ts.map +1 -1
  139. package/out/zero-schema/src/permissions.d.ts.map +1 -1
  140. package/out/zero-schema/src/permissions.js +4 -1
  141. package/out/zero-schema/src/permissions.js.map +1 -1
  142. package/out/zero-server/src/process-mutations.d.ts.map +1 -1
  143. package/out/zero-server/src/process-mutations.js +13 -19
  144. package/out/zero-server/src/process-mutations.js.map +1 -1
  145. package/out/zql/src/builder/filter.d.ts.map +1 -1
  146. package/out/zql/src/builder/filter.js +5 -2
  147. package/out/zql/src/builder/filter.js.map +1 -1
  148. package/out/zql/src/ivm/constraint.js.map +1 -1
  149. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"replicache-impl.js","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 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\ndeclare const TESTING: boolean;\n\ndeclare const process: {\n env: {\n ['DISABLE_MUTATION_RECOVERY']?: string | undefined;\n };\n};\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\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 // 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 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);\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);\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"],"names":["FormatVersion.Latest","hasClientState","persistHasClientState","pusherResult","HandlePullResponseResultEnum.Applied","HandlePullResponseResultEnum.CookieMismatch","requestID","beginPullResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A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AAIA,MAAM,uCAAsD,IAAA;AAE5D,eAAe,aAAa,GAA0C;AACpE,QAAM,MAAM,MAAM;AAClB,MAAI,KAAK;AACP,UAAM,IAAI;AAAA,EACZ;AACF;AAEA,SAAS,SAAe;AACtB,MAAI,OAAO,aAAa,aAAa;AACnC,aAAS,OAAA;AAAA,EACX;AACF;AAEA,SAAS,gBACP,SACM;AACN,QAAM,EAAC,MAAM,eAAA,IAAkB;AAC/B,MAAI,OAAO,SAAS,YAAY,CAAC,MAAM;AACrC,UAAM,IAAI,UAAU,wCAAwC;AAAA,EAC9D;AAEA,MAAI,mBAAmB,QAAW;AAChC,UAAM,MAAM,KAAK,IAAI,aAAa,kBAAkB;AACpD,QAAI,OAAO,mBAAmB,YAAY,kBAAkB,KAAK;AAC/D,YAAM,IAAI;AAAA,QACR,+CAA+C,GAAG;AAAA,MAAA;AAAA,IAEtD;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"replicache-impl.js","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 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\ndeclare const TESTING: boolean;\n\ndeclare const process: {\n env: {\n ['DISABLE_MUTATION_RECOVERY']?: string | undefined;\n };\n};\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\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 // 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 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`,\n );\n }\n }\n}\n"],"names":["FormatVersion.Latest","hasClientState","persistHasClientState","pusherResult","HandlePullResponseResultEnum.Applied","HandlePullResponseResultEnum.CookieMismatch","requestID","beginPullResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8IA,MAAM,mBAAmB;AAEzB,MAAM,0BAA0B;AAChC,MAAM,0BAA0B;AAEhC,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;AAE5B,MAAM,2CAA2C,MAAM,KAAK;AAE5D,MAAM,gCAAgC,IAAI,KAAK;AAE/C,MAAM,OAAO,MAAM;AAEnB;AAEA,MAAM,mCAAuD;AAAA,EAC3D,MAAM;AACR;AA0DO,MAAM,eAA4C;AAAA;AAAA,EAEvD;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGS;AAAA,EAEA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,wBAAwB;AAAA,EAEf;AAAA,EAET,iBAAyB;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,EAAE,MAAM,EACvB,UAAU,EAAE,MAAM,GACjB,OAAO,CA6ET;AAyCD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,KAAK,EACzC,IAAI,EAAE,SAAS,qBAAqB,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAClD,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,CAAC,IAAI,EAAE,qBAAqB,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK,MAAM,GAC9D,MAAM,CAIR"}
@@ -81,7 +81,10 @@ class WatchSubscription {
81
81
  if (!this.#initialValuesInFirstDiff) {
82
82
  return void 0;
83
83
  }
84
- assert(diffs === void 0);
84
+ assert(
85
+ diffs === void 0,
86
+ "Expected diffs to be undefined on initial run"
87
+ );
85
88
  const newDiff2 = [];
86
89
  for await (const entry of tx.scan({ prefix, indexName }).entries()) {
87
90
  newDiff2.push({
@@ -92,7 +95,7 @@ class WatchSubscription {
92
95
  }
93
96
  diff = newDiff2;
94
97
  } else {
95
- assert(diffs);
98
+ assert(diffs, "Expected diffs to be defined for non-initial run");
96
99
  const maybeDiff = diffs.get(indexName ?? "") ?? [];
97
100
  diff = convertInternalDiff(maybeDiff);
98
101
  }
@@ -1 +1 @@
1
- {"version":3,"file":"subscriptions.js","sources":["../../../../replicache/src/subscriptions.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {compareUTF8, greaterThan, lessThan, lessThanEq} from 'compare-utf8';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {binarySearch} from '../../shared/src/binary-search.ts';\nimport type {Enum} from '../../shared/src/enum.ts';\nimport {deepEqual} from '../../shared/src/json.ts';\nimport type {\n Diff,\n DiffOperation,\n IndexDiff,\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from './btree/node.ts';\nimport type {IndexKey} from './db/index.ts';\nimport {decodeIndexKey} from './db/index.ts';\nimport type {ScanOptions} from './db/scan.ts';\nimport * as InvokeKind from './invoke-kind-enum.ts';\nimport type {DiffComputationConfig, DiffsMap} from './sync/diff.ts';\nimport {\n type ReadTransaction,\n SubscriptionTransactionWrapper,\n} from './transactions.ts';\nimport type {QueryInternal} from './types.ts';\n\ntype InvokeKind = Enum<typeof InvokeKind>;\n\nexport interface Subscription<R> {\n hasIndexSubscription(indexName: string): boolean;\n\n invoke(\n tx: ReadTransaction,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ): Promise<R>;\n\n matches(diffs: DiffsMap): boolean;\n\n updateDeps(\n keys: ReadonlySet<string>,\n scans: ReadonlyArray<Readonly<ScanSubscriptionInfo>>,\n ): void;\n\n readonly onData: (result: R) => void;\n readonly onError: ((error: unknown) => void) | undefined;\n readonly onDone: (() => void) | undefined;\n}\n\nconst emptySet: ReadonlySet<string> = new Set();\n\nconst unitializedLastValue = Symbol();\ntype UnitializedLastValue = typeof unitializedLastValue;\n\nexport class SubscriptionImpl<R> implements Subscription<R> {\n readonly #body: (tx: ReadTransaction) => Promise<R>;\n readonly #onData: (result: R) => void;\n #lastValue: R | UnitializedLastValue = unitializedLastValue;\n #keys = emptySet;\n #scans: readonly Readonly<ScanSubscriptionInfo>[] = [];\n\n readonly onError: ((error: unknown) => void) | undefined;\n readonly onDone: (() => void) | undefined;\n readonly #isEqual: (a: R, b: R) => boolean;\n\n constructor(\n body: (tx: ReadTransaction) => Promise<R>,\n onData: (result: R) => void,\n onError: ((error: unknown) => void) | undefined,\n onDone: (() => void) | undefined,\n // deepEqual operates on any JSON value but argument might be more specific.\n isEqual: (a: R, b: R) => boolean = deepEqual as (a: R, b: R) => boolean,\n ) {\n this.#body = body;\n this.#onData = onData;\n this.onError = onError;\n this.onDone = onDone;\n this.#isEqual = isEqual;\n }\n\n hasIndexSubscription(indexName: string): boolean {\n for (const scan of this.#scans) {\n if (scan.options.indexName === indexName) {\n return true;\n }\n }\n return false;\n }\n\n invoke(\n tx: ReadTransaction,\n _kind: InvokeKind,\n _diffs: DiffsMap | undefined,\n ): Promise<R> {\n return this.#body(tx);\n }\n\n matches(diffs: DiffsMap): boolean {\n for (const [indexName, diff] of diffs) {\n if (diffMatchesSubscription(this.#keys, this.#scans, indexName, diff)) {\n return true;\n }\n }\n\n return false;\n }\n\n updateDeps(\n keys: ReadonlySet<string>,\n scans: readonly Readonly<ScanSubscriptionInfo>[],\n ): void {\n this.#keys = keys;\n this.#scans = scans;\n }\n\n onData(result: R): void {\n if (\n this.#lastValue === unitializedLastValue ||\n !this.#isEqual(this.#lastValue, result)\n ) {\n this.#lastValue = result;\n this.#onData(result);\n }\n }\n}\n\nexport {SubscriptionImpl as SubscriptionImplForTesting};\n\n/**\n * Function that gets passed into {@link Replicache.experimentalWatch} and gets\n * called when the data in Replicache changes.\n *\n * @experimental This type is experimental and may change in the future.\n */\nexport type WatchNoIndexCallback = (diff: NoIndexDiff) => void;\n\nexport type WatchCallbackForOptions<Options extends WatchOptions> =\n Options extends WatchIndexOptions ? WatchIndexCallback : WatchNoIndexCallback;\n\n/**\n * Function that gets passed into {@link Replicache.experimentalWatch} when doing a\n * watch on a secondary index map and gets called when the data in Replicache\n * changes.\n *\n * @experimental This type is experimental and may change in the future.\n */\nexport type WatchIndexCallback = (diff: IndexDiff) => void;\n\n/**\n * Options for {@link Replicache.experimentalWatch}.\n *\n * @experimental This interface is experimental and may change in the future.\n */\nexport type WatchOptions = WatchIndexOptions | WatchNoIndexOptions;\n\n/**\n * Options object passed to {@link Replicache.experimentalWatch}. This is for an\n * index watch.\n */\nexport type WatchIndexOptions = WatchNoIndexOptions & {\n /**\n * When provided, the `watch` is limited to the changes that apply to the index map.\n */\n indexName: string;\n};\n\n/**\n * Options object passed to {@link Replicache.experimentalWatch}. This is for a non\n * index watch.\n */\nexport type WatchNoIndexOptions = {\n /**\n * When provided, the `watch` is limited to changes where the `key` starts\n * with `prefix`.\n */\n prefix?: string | undefined;\n\n /**\n * When this is set to `true` (default is `false`), the `watch` callback will\n * be called once asynchronously when watch is called. The arguments in that\n * case is a diff where we consider all the existing values in Replicache as\n * being added.\n */\n initialValuesInFirstDiff?: boolean | undefined;\n};\n\nexport type WatchCallback = (diff: Diff) => void;\n\nexport class WatchSubscription implements Subscription<Diff | undefined> {\n readonly #callback: WatchCallback;\n readonly #prefix: string;\n readonly #indexName: string | undefined;\n readonly #initialValuesInFirstDiff: boolean;\n\n readonly onError: ((error: unknown) => void) | undefined = undefined;\n readonly onDone: (() => void) | undefined = undefined;\n\n constructor(callback: WatchCallback, options?: WatchOptions) {\n this.#callback = callback;\n this.#prefix = options?.prefix ?? '';\n this.#indexName = (options as WatchIndexOptions)?.indexName;\n this.#initialValuesInFirstDiff = options?.initialValuesInFirstDiff ?? false;\n }\n\n hasIndexSubscription(indexName: string): boolean {\n return this.#indexName === indexName;\n }\n\n onData(result: Diff | undefined): void {\n if (result !== undefined) {\n this.#callback(result);\n }\n }\n\n invoke(\n tx: ReadTransaction,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ): Promise<Diff | undefined> {\n const invoke = async <Key extends IndexKey | string>(\n indexName: string | undefined,\n prefix: string,\n compareKey: (diff: DiffOperation<Key>) => string,\n convertInternalDiff: (\n diff: InternalDiff,\n ) => readonly DiffOperation<Key>[],\n ): Promise<readonly DiffOperation<Key>[] | undefined> => {\n let diff: readonly DiffOperation<Key>[];\n if (kind === InvokeKind.InitialRun) {\n if (!this.#initialValuesInFirstDiff) {\n // We are using `undefined` here as a sentinel value to indicate that we\n // should not call the callback in `onDone`.\n return undefined;\n }\n\n // For the initial run, we need to get the \"diffs\" for the whole tree.\n assert(diffs === undefined);\n\n const newDiff: DiffOperation<Key>[] = [];\n for await (const entry of tx.scan({prefix, indexName}).entries()) {\n newDiff.push({\n op: 'add',\n key: entry[0] as Key,\n newValue: entry[1],\n });\n }\n diff = newDiff;\n } else {\n assert(diffs);\n const maybeDiff = diffs.get(indexName ?? '') ?? [];\n diff = convertInternalDiff(maybeDiff);\n }\n const newDiff: DiffOperation<Key>[] = [];\n const {length} = diff;\n for (\n let i = diffBinarySearch(diff, prefix, compareKey);\n i < length;\n i++\n ) {\n if (compareKey(diff[i]).startsWith(prefix)) {\n newDiff.push(diff[i]);\n } else {\n break;\n }\n }\n\n // For initial run we should always return something.\n return kind === InvokeKind.InitialRun || newDiff.length > 0\n ? newDiff\n : undefined;\n };\n\n if (this.#indexName) {\n return invoke<IndexKey>(\n this.#indexName,\n this.#prefix,\n diff => diff.key[0],\n internalDiff => convertDiffValues(internalDiff, decodeIndexKey),\n );\n }\n\n return invoke<string>(\n undefined,\n this.#prefix,\n diff => diff.key,\n internalDiff => convertDiffValues(internalDiff, k => k),\n );\n }\n\n matches(diffs: DiffsMap): boolean {\n const diff = diffs.get(this.#indexName ?? '');\n if (diff === undefined) {\n return false;\n }\n\n return watcherMatchesDiff(diff, this.#prefix, this.#indexName);\n }\n\n updateDeps(\n _keys: ReadonlySet<string>,\n _scans: readonly Readonly<ScanSubscriptionInfo>[],\n ): void {\n // not used\n }\n}\n\nfunction convertDiffValues<Key>(\n diff: InternalDiff,\n convertKey: (k: string) => Key,\n): DiffOperation<Key>[] {\n return diff.map(op => {\n const key = convertKey(op.key);\n switch (op.op) {\n case 'add':\n return {\n op: 'add',\n key,\n newValue: op.newValue,\n };\n case 'change':\n return {\n op: 'change',\n key,\n oldValue: op.oldValue,\n newValue: op.newValue,\n };\n case 'del':\n return {\n op: 'del',\n key,\n oldValue: op.oldValue,\n };\n }\n });\n}\n\n/**\n * The options passed to {@link Replicache.subscribe}.\n */\nexport interface SubscribeOptions<R> {\n /**\n * Called when the return value of the body function changes.\n */\n onData: (result: R) => void;\n\n /**\n * If present, called when an error occurs.\n */\n onError?: ((error: unknown) => void) | undefined;\n\n /**\n * If present, called when the subscription is removed/done.\n */\n onDone?: (() => void) | undefined;\n\n /**\n * If present this function is used to determine if the value returned by the\n * body function has changed. If not provided a JSON deep equality check is\n * used.\n */\n isEqual?: ((a: R, b: R) => boolean) | undefined;\n}\n\nexport type UnknownSubscription = Subscription<unknown>;\n\ntype SubscriptionSet = Set<UnknownSubscription>;\n\nexport interface SubscriptionsManager extends DiffComputationConfig {\n clear(): void;\n fire(diffs: DiffsMap): Promise<void>;\n hasPendingSubscriptionRuns: boolean;\n add<R>(subscription: Subscription<R>): () => void;\n}\n\nexport class SubscriptionsManagerImpl implements SubscriptionsManager {\n readonly #subscriptions: SubscriptionSet = new Set();\n readonly #pendingSubscriptions: SubscriptionSet = new Set();\n readonly #queryInternal: QueryInternal;\n readonly #lc: LogContext;\n hasPendingSubscriptionRuns = false;\n readonly #signal: AbortSignal;\n\n constructor(\n queryInternal: QueryInternal,\n lc: LogContext,\n signal: AbortSignal,\n ) {\n this.#queryInternal = queryInternal;\n this.#lc = lc;\n this.#signal = signal;\n }\n\n add<R>(subscription: Subscription<R>): () => void {\n this.#subscriptions.add(subscription as UnknownSubscription);\n void this.#scheduleInitialSubscriptionRun(\n subscription as UnknownSubscription,\n );\n return () =>\n this.#subscriptions.delete(subscription as UnknownSubscription);\n }\n\n clear(): void {\n for (const subscription of this.#subscriptions) {\n subscription.onDone?.();\n }\n this.#subscriptions.clear();\n }\n\n fire(diffs: DiffsMap): Promise<void> {\n const subscriptions = subscriptionsForDiffs(this.#subscriptions, diffs);\n return this.#fireSubscriptions(subscriptions, InvokeKind.Regular, diffs);\n }\n\n async #fireSubscriptions(\n subscriptions: Iterable<UnknownSubscription>,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ) {\n if (this.#signal.aborted) {\n return;\n }\n\n const subs = [...subscriptions] as readonly Subscription<unknown>[];\n if (subs.length === 0) {\n return;\n }\n\n // Use allSettled to gather fulfilled and rejected promises.\n const results = await this.#queryInternal(tx =>\n Promise.allSettled(\n subs.map(async s => {\n const stx = new SubscriptionTransactionWrapper(tx);\n try {\n return await s.invoke(stx, kind, diffs);\n } finally {\n // We need to keep track of the subscription keys even if there was an\n // exception because changes to the keys can make the subscription\n // body succeed.\n s.updateDeps(stx.keys, stx.scans);\n }\n }),\n ),\n );\n\n this.callCallbacks(subs, results);\n }\n\n // Public method so that ZQL can wrap it in a transaction.\n callCallbacks(\n subs: readonly Subscription<unknown>[],\n results: PromiseSettledResult<unknown>[],\n ) {\n for (let i = 0; i < subs.length; i++) {\n const s = subs[i];\n const result = results[i];\n if (result.status === 'fulfilled') {\n s.onData(result.value);\n } else {\n if (s.onError) {\n s.onError(result.reason);\n } else {\n this.#lc.error?.('Error in subscription body:', result.reason);\n }\n }\n }\n }\n\n async #scheduleInitialSubscriptionRun(s: UnknownSubscription) {\n this.#pendingSubscriptions.add(s);\n\n if (!this.hasPendingSubscriptionRuns) {\n this.hasPendingSubscriptionRuns = true;\n await Promise.resolve();\n this.hasPendingSubscriptionRuns = false;\n const subscriptions = [...this.#pendingSubscriptions];\n this.#pendingSubscriptions.clear();\n await this.#fireSubscriptions(\n subscriptions,\n InvokeKind.InitialRun,\n undefined,\n );\n }\n }\n\n shouldComputeDiffs(): boolean {\n return this.#subscriptions.size > 0;\n }\n\n shouldComputeDiffsForIndex(indexName: string): boolean {\n for (const s of this.#subscriptions) {\n if (s.hasIndexSubscription(indexName)) {\n return true;\n }\n }\n return false;\n }\n}\n\nexport type ScanSubscriptionInfo = {\n options: ScanOptions;\n inclusiveLimitKey?: string | undefined;\n};\n\nfunction diffMatchesSubscription(\n keys: ReadonlySet<string>,\n scans: Iterable<Readonly<ScanSubscriptionInfo>>,\n indexName: string,\n diff: InternalDiff,\n): boolean {\n // Keys can only match for non index scans.\n if (indexName === '') {\n for (const diffEntry of diff) {\n if (keys.has(diffEntry.key)) {\n return true;\n }\n }\n }\n\n for (const scanInfo of scans) {\n if (scanInfoMatchesDiff(scanInfo, indexName, diff)) {\n return true;\n }\n }\n return false;\n}\n\nfunction scanInfoMatchesDiff(\n scanInfo: ScanSubscriptionInfo,\n changeIndexName: string,\n diff: InternalDiff,\n): boolean {\n // TODO(arv): Use binary search\n for (const diffEntry of diff) {\n if (scanInfoMatchesKey(scanInfo, changeIndexName, diffEntry.key)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function scanInfoMatchesKey(\n scanInfo: ScanSubscriptionInfo,\n changeIndexName: string,\n changedKey: string,\n): boolean {\n const {\n indexName = '',\n limit,\n prefix,\n startKey,\n startExclusive,\n startSecondaryKey,\n } = scanInfo.options;\n\n if (changeIndexName !== indexName) {\n return false;\n }\n\n if (!indexName) {\n // A scan with limit <= 0 can have no matches\n if (limit !== undefined && limit <= 0) {\n return false;\n }\n\n // No prefix and no start. Must recompute the subscription because all keys\n // will have an effect on the subscription.\n if (!prefix && !startKey) {\n return true;\n }\n\n if (\n prefix &&\n (!changedKey.startsWith(prefix) ||\n isKeyPastInclusiveLimit(scanInfo, changedKey))\n ) {\n return false;\n }\n\n if (\n startKey &&\n ((startExclusive && lessThanEq(changedKey, startKey)) ||\n lessThan(changedKey, startKey) ||\n isKeyPastInclusiveLimit(scanInfo, changedKey))\n ) {\n return false;\n }\n\n return true;\n }\n\n // No prefix and no start. Must recompute the subscription because all keys\n // will have an effect on the subscription.\n if (!prefix && !startKey && !startSecondaryKey) {\n return true;\n }\n\n const [changedKeySecondary, changedKeyPrimary] = decodeIndexKey(changedKey);\n\n if (prefix) {\n if (!changedKeySecondary.startsWith(prefix)) {\n return false;\n }\n }\n\n if (\n startSecondaryKey &&\n ((startExclusive && lessThanEq(changedKeySecondary, startSecondaryKey)) ||\n lessThan(changedKeySecondary, startSecondaryKey))\n ) {\n return false;\n }\n\n if (\n startKey &&\n ((startExclusive && lessThanEq(changedKeyPrimary, startKey)) ||\n lessThan(changedKeyPrimary, startKey))\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isKeyPastInclusiveLimit(\n scanInfo: ScanSubscriptionInfo,\n changedKey: string,\n): boolean {\n const {inclusiveLimitKey} = scanInfo;\n return (\n scanInfo.options.limit !== undefined &&\n inclusiveLimitKey !== undefined &&\n greaterThan(changedKey, inclusiveLimitKey)\n );\n}\n\nfunction* subscriptionsForDiffs<V>(\n subscriptions: Set<Subscription<V>>,\n diffs: DiffsMap,\n): Generator<Subscription<V>> {\n for (const subscription of subscriptions) {\n if (subscription.matches(diffs)) {\n yield subscription;\n }\n }\n}\n\nfunction watcherMatchesDiff(\n diff: InternalDiff,\n prefix: string,\n indexName: string | undefined,\n): boolean {\n if (prefix === '') {\n return true;\n }\n\n const compareKey = indexName\n ? (diffOp: InternalDiffOperation) => decodeIndexKey(diffOp.key)[0]\n : (diffOp: InternalDiffOperation) => diffOp.key;\n const i = diffBinarySearch(diff, prefix, compareKey);\n return i < diff.length && compareKey(diff[i]).startsWith(prefix);\n}\n\nexport function diffBinarySearch<Key, Value>(\n diff: readonly InternalDiffOperation<Key, Value>[],\n prefix: string,\n compareKey: (diff: InternalDiffOperation<Key, Value>) => string,\n): number {\n return binarySearch(diff.length, i =>\n compareUTF8(prefix, compareKey(diff[i])),\n );\n}\n"],"names":["InvokeKind.InitialRun","newDiff","InvokeKind.Regular"],"mappings":";;;;;;;AAgDA,MAAM,+BAAoC,IAAA;AAE1C,MAAM,uBAAuB,OAAA;AAGtB,MAAM,iBAA+C;AAAA,EACjD;AAAA,EACA;AAAA,EACT,aAAuC;AAAA,EACvC,QAAQ;AAAA,EACR,SAAoD,CAAA;AAAA,EAE3C;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,QACA,SACA,QAEA,UAAmC,WACnC;AACA,SAAK,QAAQ;AACb,SAAK,UAAU;AACf,SAAK,UAAU;AACf,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,qBAAqB,WAA4B;AAC/C,eAAW,QAAQ,KAAK,QAAQ;AAC9B,UAAI,KAAK,QAAQ,cAAc,WAAW;AACxC,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,OACE,IACA,OACA,QACY;AACZ,WAAO,KAAK,MAAM,EAAE;AAAA,EACtB;AAAA,EAEA,QAAQ,OAA0B;AAChC,eAAW,CAAC,WAAW,IAAI,KAAK,OAAO;AACrC,UAAI,wBAAwB,KAAK,OAAO,KAAK,QAAQ,WAAW,IAAI,GAA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AAAA,EACT;AAEA,SAAO;AACT;AAEA,SAAS,wBACP,UACA,YACS;AACT,QAAM,EAAC,sBAAqB;AAC5B,SACE,SAAS,QAAQ,UAAU,UAC3B,sBAAsB,UACtB,YAAY,YAAY,iBAAiB;AAE7C;AAEA,UAAU,sBACR,eACA,OAC4B;AAC5B,aAAW,gBAAgB,eAAe;AACxC,QAAI,aAAa,QAAQ,KAAK,GAAG;AAC/B,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAEA,SAAS,mBACP,MACA,QACA,WACS;AACT,MAAI,WAAW,IAAI;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,YACf,CAAC,WAAkC,eAAe,OAAO,GAAG,EAAE,CAAC,IAC/D,CAAC,WAAkC,OAAO;AAC9C,QAAM,IAAI,iBAAiB,MAAM,QAAQ,UAAU;AACnD,SAAO,IAAI,KAAK,UAAU,WAAW,KAAK,CAAC,CAAC,EAAE,WAAW,MAAM;AACjE;AAEO,SAAS,iBACd,MACA,QACA,YACQ;AACR,SAAO;AAAA,IAAa,KAAK;AAAA,IAAQ,OAC/B,YAAY,QAAQ,WAAW,KAAK,CAAC,CAAC,CAAC;AAAA,EAAA;AAE3C;"}
1
+ {"version":3,"file":"subscriptions.js","sources":["../../../../replicache/src/subscriptions.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {compareUTF8, greaterThan, lessThan, lessThanEq} from 'compare-utf8';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {binarySearch} from '../../shared/src/binary-search.ts';\nimport type {Enum} from '../../shared/src/enum.ts';\nimport {deepEqual} from '../../shared/src/json.ts';\nimport type {\n Diff,\n DiffOperation,\n IndexDiff,\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from './btree/node.ts';\nimport type {IndexKey} from './db/index.ts';\nimport {decodeIndexKey} from './db/index.ts';\nimport type {ScanOptions} from './db/scan.ts';\nimport * as InvokeKind from './invoke-kind-enum.ts';\nimport type {DiffComputationConfig, DiffsMap} from './sync/diff.ts';\nimport {\n type ReadTransaction,\n SubscriptionTransactionWrapper,\n} from './transactions.ts';\nimport type {QueryInternal} from './types.ts';\n\ntype InvokeKind = Enum<typeof InvokeKind>;\n\nexport interface Subscription<R> {\n hasIndexSubscription(indexName: string): boolean;\n\n invoke(\n tx: ReadTransaction,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ): Promise<R>;\n\n matches(diffs: DiffsMap): boolean;\n\n updateDeps(\n keys: ReadonlySet<string>,\n scans: ReadonlyArray<Readonly<ScanSubscriptionInfo>>,\n ): void;\n\n readonly onData: (result: R) => void;\n readonly onError: ((error: unknown) => void) | undefined;\n readonly onDone: (() => void) | undefined;\n}\n\nconst emptySet: ReadonlySet<string> = new Set();\n\nconst unitializedLastValue = Symbol();\ntype UnitializedLastValue = typeof unitializedLastValue;\n\nexport class SubscriptionImpl<R> implements Subscription<R> {\n readonly #body: (tx: ReadTransaction) => Promise<R>;\n readonly #onData: (result: R) => void;\n #lastValue: R | UnitializedLastValue = unitializedLastValue;\n #keys = emptySet;\n #scans: readonly Readonly<ScanSubscriptionInfo>[] = [];\n\n readonly onError: ((error: unknown) => void) | undefined;\n readonly onDone: (() => void) | undefined;\n readonly #isEqual: (a: R, b: R) => boolean;\n\n constructor(\n body: (tx: ReadTransaction) => Promise<R>,\n onData: (result: R) => void,\n onError: ((error: unknown) => void) | undefined,\n onDone: (() => void) | undefined,\n // deepEqual operates on any JSON value but argument might be more specific.\n isEqual: (a: R, b: R) => boolean = deepEqual as (a: R, b: R) => boolean,\n ) {\n this.#body = body;\n this.#onData = onData;\n this.onError = onError;\n this.onDone = onDone;\n this.#isEqual = isEqual;\n }\n\n hasIndexSubscription(indexName: string): boolean {\n for (const scan of this.#scans) {\n if (scan.options.indexName === indexName) {\n return true;\n }\n }\n return false;\n }\n\n invoke(\n tx: ReadTransaction,\n _kind: InvokeKind,\n _diffs: DiffsMap | undefined,\n ): Promise<R> {\n return this.#body(tx);\n }\n\n matches(diffs: DiffsMap): boolean {\n for (const [indexName, diff] of diffs) {\n if (diffMatchesSubscription(this.#keys, this.#scans, indexName, diff)) {\n return true;\n }\n }\n\n return false;\n }\n\n updateDeps(\n keys: ReadonlySet<string>,\n scans: readonly Readonly<ScanSubscriptionInfo>[],\n ): void {\n this.#keys = keys;\n this.#scans = scans;\n }\n\n onData(result: R): void {\n if (\n this.#lastValue === unitializedLastValue ||\n !this.#isEqual(this.#lastValue, result)\n ) {\n this.#lastValue = result;\n this.#onData(result);\n }\n }\n}\n\nexport {SubscriptionImpl as SubscriptionImplForTesting};\n\n/**\n * Function that gets passed into {@link Replicache.experimentalWatch} and gets\n * called when the data in Replicache changes.\n *\n * @experimental This type is experimental and may change in the future.\n */\nexport type WatchNoIndexCallback = (diff: NoIndexDiff) => void;\n\nexport type WatchCallbackForOptions<Options extends WatchOptions> =\n Options extends WatchIndexOptions ? WatchIndexCallback : WatchNoIndexCallback;\n\n/**\n * Function that gets passed into {@link Replicache.experimentalWatch} when doing a\n * watch on a secondary index map and gets called when the data in Replicache\n * changes.\n *\n * @experimental This type is experimental and may change in the future.\n */\nexport type WatchIndexCallback = (diff: IndexDiff) => void;\n\n/**\n * Options for {@link Replicache.experimentalWatch}.\n *\n * @experimental This interface is experimental and may change in the future.\n */\nexport type WatchOptions = WatchIndexOptions | WatchNoIndexOptions;\n\n/**\n * Options object passed to {@link Replicache.experimentalWatch}. This is for an\n * index watch.\n */\nexport type WatchIndexOptions = WatchNoIndexOptions & {\n /**\n * When provided, the `watch` is limited to the changes that apply to the index map.\n */\n indexName: string;\n};\n\n/**\n * Options object passed to {@link Replicache.experimentalWatch}. This is for a non\n * index watch.\n */\nexport type WatchNoIndexOptions = {\n /**\n * When provided, the `watch` is limited to changes where the `key` starts\n * with `prefix`.\n */\n prefix?: string | undefined;\n\n /**\n * When this is set to `true` (default is `false`), the `watch` callback will\n * be called once asynchronously when watch is called. The arguments in that\n * case is a diff where we consider all the existing values in Replicache as\n * being added.\n */\n initialValuesInFirstDiff?: boolean | undefined;\n};\n\nexport type WatchCallback = (diff: Diff) => void;\n\nexport class WatchSubscription implements Subscription<Diff | undefined> {\n readonly #callback: WatchCallback;\n readonly #prefix: string;\n readonly #indexName: string | undefined;\n readonly #initialValuesInFirstDiff: boolean;\n\n readonly onError: ((error: unknown) => void) | undefined = undefined;\n readonly onDone: (() => void) | undefined = undefined;\n\n constructor(callback: WatchCallback, options?: WatchOptions) {\n this.#callback = callback;\n this.#prefix = options?.prefix ?? '';\n this.#indexName = (options as WatchIndexOptions)?.indexName;\n this.#initialValuesInFirstDiff = options?.initialValuesInFirstDiff ?? false;\n }\n\n hasIndexSubscription(indexName: string): boolean {\n return this.#indexName === indexName;\n }\n\n onData(result: Diff | undefined): void {\n if (result !== undefined) {\n this.#callback(result);\n }\n }\n\n invoke(\n tx: ReadTransaction,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ): Promise<Diff | undefined> {\n const invoke = async <Key extends IndexKey | string>(\n indexName: string | undefined,\n prefix: string,\n compareKey: (diff: DiffOperation<Key>) => string,\n convertInternalDiff: (\n diff: InternalDiff,\n ) => readonly DiffOperation<Key>[],\n ): Promise<readonly DiffOperation<Key>[] | undefined> => {\n let diff: readonly DiffOperation<Key>[];\n if (kind === InvokeKind.InitialRun) {\n if (!this.#initialValuesInFirstDiff) {\n // We are using `undefined` here as a sentinel value to indicate that we\n // should not call the callback in `onDone`.\n return undefined;\n }\n\n // For the initial run, we need to get the \"diffs\" for the whole tree.\n assert(\n diffs === undefined,\n 'Expected diffs to be undefined on initial run',\n );\n\n const newDiff: DiffOperation<Key>[] = [];\n for await (const entry of tx.scan({prefix, indexName}).entries()) {\n newDiff.push({\n op: 'add',\n key: entry[0] as Key,\n newValue: entry[1],\n });\n }\n diff = newDiff;\n } else {\n assert(diffs, 'Expected diffs to be defined for non-initial run');\n const maybeDiff = diffs.get(indexName ?? '') ?? [];\n diff = convertInternalDiff(maybeDiff);\n }\n const newDiff: DiffOperation<Key>[] = [];\n const {length} = diff;\n for (\n let i = diffBinarySearch(diff, prefix, compareKey);\n i < length;\n i++\n ) {\n if (compareKey(diff[i]).startsWith(prefix)) {\n newDiff.push(diff[i]);\n } else {\n break;\n }\n }\n\n // For initial run we should always return something.\n return kind === InvokeKind.InitialRun || newDiff.length > 0\n ? newDiff\n : undefined;\n };\n\n if (this.#indexName) {\n return invoke<IndexKey>(\n this.#indexName,\n this.#prefix,\n diff => diff.key[0],\n internalDiff => convertDiffValues(internalDiff, decodeIndexKey),\n );\n }\n\n return invoke<string>(\n undefined,\n this.#prefix,\n diff => diff.key,\n internalDiff => convertDiffValues(internalDiff, k => k),\n );\n }\n\n matches(diffs: DiffsMap): boolean {\n const diff = diffs.get(this.#indexName ?? '');\n if (diff === undefined) {\n return false;\n }\n\n return watcherMatchesDiff(diff, this.#prefix, this.#indexName);\n }\n\n updateDeps(\n _keys: ReadonlySet<string>,\n _scans: readonly Readonly<ScanSubscriptionInfo>[],\n ): void {\n // not used\n }\n}\n\nfunction convertDiffValues<Key>(\n diff: InternalDiff,\n convertKey: (k: string) => Key,\n): DiffOperation<Key>[] {\n return diff.map(op => {\n const key = convertKey(op.key);\n switch (op.op) {\n case 'add':\n return {\n op: 'add',\n key,\n newValue: op.newValue,\n };\n case 'change':\n return {\n op: 'change',\n key,\n oldValue: op.oldValue,\n newValue: op.newValue,\n };\n case 'del':\n return {\n op: 'del',\n key,\n oldValue: op.oldValue,\n };\n }\n });\n}\n\n/**\n * The options passed to {@link Replicache.subscribe}.\n */\nexport interface SubscribeOptions<R> {\n /**\n * Called when the return value of the body function changes.\n */\n onData: (result: R) => void;\n\n /**\n * If present, called when an error occurs.\n */\n onError?: ((error: unknown) => void) | undefined;\n\n /**\n * If present, called when the subscription is removed/done.\n */\n onDone?: (() => void) | undefined;\n\n /**\n * If present this function is used to determine if the value returned by the\n * body function has changed. If not provided a JSON deep equality check is\n * used.\n */\n isEqual?: ((a: R, b: R) => boolean) | undefined;\n}\n\nexport type UnknownSubscription = Subscription<unknown>;\n\ntype SubscriptionSet = Set<UnknownSubscription>;\n\nexport interface SubscriptionsManager extends DiffComputationConfig {\n clear(): void;\n fire(diffs: DiffsMap): Promise<void>;\n hasPendingSubscriptionRuns: boolean;\n add<R>(subscription: Subscription<R>): () => void;\n}\n\nexport class SubscriptionsManagerImpl implements SubscriptionsManager {\n readonly #subscriptions: SubscriptionSet = new Set();\n readonly #pendingSubscriptions: SubscriptionSet = new Set();\n readonly #queryInternal: QueryInternal;\n readonly #lc: LogContext;\n hasPendingSubscriptionRuns = false;\n readonly #signal: AbortSignal;\n\n constructor(\n queryInternal: QueryInternal,\n lc: LogContext,\n signal: AbortSignal,\n ) {\n this.#queryInternal = queryInternal;\n this.#lc = lc;\n this.#signal = signal;\n }\n\n add<R>(subscription: Subscription<R>): () => void {\n this.#subscriptions.add(subscription as UnknownSubscription);\n void this.#scheduleInitialSubscriptionRun(\n subscription as UnknownSubscription,\n );\n return () =>\n this.#subscriptions.delete(subscription as UnknownSubscription);\n }\n\n clear(): void {\n for (const subscription of this.#subscriptions) {\n subscription.onDone?.();\n }\n this.#subscriptions.clear();\n }\n\n fire(diffs: DiffsMap): Promise<void> {\n const subscriptions = subscriptionsForDiffs(this.#subscriptions, diffs);\n return this.#fireSubscriptions(subscriptions, InvokeKind.Regular, diffs);\n }\n\n async #fireSubscriptions(\n subscriptions: Iterable<UnknownSubscription>,\n kind: InvokeKind,\n diffs: DiffsMap | undefined,\n ) {\n if (this.#signal.aborted) {\n return;\n }\n\n const subs = [...subscriptions] as readonly Subscription<unknown>[];\n if (subs.length === 0) {\n return;\n }\n\n // Use allSettled to gather fulfilled and rejected promises.\n const results = await this.#queryInternal(tx =>\n Promise.allSettled(\n subs.map(async s => {\n const stx = new SubscriptionTransactionWrapper(tx);\n try {\n return await s.invoke(stx, kind, diffs);\n } finally {\n // We need to keep track of the subscription keys even if there was an\n // exception because changes to the keys can make the subscription\n // body succeed.\n s.updateDeps(stx.keys, stx.scans);\n }\n }),\n ),\n );\n\n this.callCallbacks(subs, results);\n }\n\n // Public method so that ZQL can wrap it in a transaction.\n callCallbacks(\n subs: readonly Subscription<unknown>[],\n results: PromiseSettledResult<unknown>[],\n ) {\n for (let i = 0; i < subs.length; i++) {\n const s = subs[i];\n const result = results[i];\n if (result.status === 'fulfilled') {\n s.onData(result.value);\n } else {\n if (s.onError) {\n s.onError(result.reason);\n } else {\n this.#lc.error?.('Error in subscription body:', result.reason);\n }\n }\n }\n }\n\n async #scheduleInitialSubscriptionRun(s: UnknownSubscription) {\n this.#pendingSubscriptions.add(s);\n\n if (!this.hasPendingSubscriptionRuns) {\n this.hasPendingSubscriptionRuns = true;\n await Promise.resolve();\n this.hasPendingSubscriptionRuns = false;\n const subscriptions = [...this.#pendingSubscriptions];\n this.#pendingSubscriptions.clear();\n await this.#fireSubscriptions(\n subscriptions,\n InvokeKind.InitialRun,\n undefined,\n );\n }\n }\n\n shouldComputeDiffs(): boolean {\n return this.#subscriptions.size > 0;\n }\n\n shouldComputeDiffsForIndex(indexName: string): boolean {\n for (const s of this.#subscriptions) {\n if (s.hasIndexSubscription(indexName)) {\n return true;\n }\n }\n return false;\n }\n}\n\nexport type ScanSubscriptionInfo = {\n options: ScanOptions;\n inclusiveLimitKey?: string | undefined;\n};\n\nfunction diffMatchesSubscription(\n keys: ReadonlySet<string>,\n scans: Iterable<Readonly<ScanSubscriptionInfo>>,\n indexName: string,\n diff: InternalDiff,\n): boolean {\n // Keys can only match for non index scans.\n if (indexName === '') {\n for (const diffEntry of diff) {\n if (keys.has(diffEntry.key)) {\n return true;\n }\n }\n }\n\n for (const scanInfo of scans) {\n if (scanInfoMatchesDiff(scanInfo, indexName, diff)) {\n return true;\n }\n }\n return false;\n}\n\nfunction scanInfoMatchesDiff(\n scanInfo: ScanSubscriptionInfo,\n changeIndexName: string,\n diff: InternalDiff,\n): boolean {\n // TODO(arv): Use binary search\n for (const diffEntry of diff) {\n if (scanInfoMatchesKey(scanInfo, changeIndexName, diffEntry.key)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function scanInfoMatchesKey(\n scanInfo: ScanSubscriptionInfo,\n changeIndexName: string,\n changedKey: string,\n): boolean {\n const {\n indexName = '',\n limit,\n prefix,\n startKey,\n startExclusive,\n startSecondaryKey,\n } = scanInfo.options;\n\n if (changeIndexName !== indexName) {\n return false;\n }\n\n if (!indexName) {\n // A scan with limit <= 0 can have no matches\n if (limit !== undefined && limit <= 0) {\n return false;\n }\n\n // No prefix and no start. Must recompute the subscription because all keys\n // will have an effect on the subscription.\n if (!prefix && !startKey) {\n return true;\n }\n\n if (\n prefix &&\n (!changedKey.startsWith(prefix) ||\n isKeyPastInclusiveLimit(scanInfo, changedKey))\n ) {\n return false;\n }\n\n if (\n startKey &&\n ((startExclusive && lessThanEq(changedKey, startKey)) ||\n lessThan(changedKey, startKey) ||\n isKeyPastInclusiveLimit(scanInfo, changedKey))\n ) {\n return false;\n }\n\n return true;\n }\n\n // No prefix and no start. Must recompute the subscription because all keys\n // will have an effect on the subscription.\n if (!prefix && !startKey && !startSecondaryKey) {\n return true;\n }\n\n const [changedKeySecondary, changedKeyPrimary] = decodeIndexKey(changedKey);\n\n if (prefix) {\n if (!changedKeySecondary.startsWith(prefix)) {\n return false;\n }\n }\n\n if (\n startSecondaryKey &&\n ((startExclusive && lessThanEq(changedKeySecondary, startSecondaryKey)) ||\n lessThan(changedKeySecondary, startSecondaryKey))\n ) {\n return false;\n }\n\n if (\n startKey &&\n ((startExclusive && lessThanEq(changedKeyPrimary, startKey)) ||\n lessThan(changedKeyPrimary, startKey))\n ) {\n return false;\n }\n\n return true;\n}\n\nfunction isKeyPastInclusiveLimit(\n scanInfo: ScanSubscriptionInfo,\n changedKey: string,\n): boolean {\n const {inclusiveLimitKey} = scanInfo;\n return (\n scanInfo.options.limit !== undefined &&\n inclusiveLimitKey !== undefined &&\n greaterThan(changedKey, inclusiveLimitKey)\n );\n}\n\nfunction* subscriptionsForDiffs<V>(\n subscriptions: Set<Subscription<V>>,\n diffs: DiffsMap,\n): Generator<Subscription<V>> {\n for (const subscription of subscriptions) {\n if (subscription.matches(diffs)) {\n yield subscription;\n }\n }\n}\n\nfunction watcherMatchesDiff(\n diff: InternalDiff,\n prefix: string,\n indexName: string | undefined,\n): boolean {\n if (prefix === '') {\n return true;\n }\n\n const compareKey = indexName\n ? (diffOp: InternalDiffOperation) => decodeIndexKey(diffOp.key)[0]\n : (diffOp: InternalDiffOperation) => diffOp.key;\n const i = diffBinarySearch(diff, prefix, compareKey);\n return i < diff.length && compareKey(diff[i]).startsWith(prefix);\n}\n\nexport function diffBinarySearch<Key, Value>(\n diff: readonly InternalDiffOperation<Key, Value>[],\n prefix: string,\n compareKey: (diff: InternalDiffOperation<Key, Value>) => string,\n): number {\n return binarySearch(diff.length, i =>\n compareUTF8(prefix, compareKey(diff[i])),\n );\n}\n"],"names":["InvokeKind.InitialRun","newDiff","InvokeKind.Regular"],"mappings":";;;;;;;AAgDA,MAAM,+BAAoC,IAAA;AAE1C,MAAM,uBAAuB,OAAA;AAGtB,MAAM,iBAA+C;AAAA,EACjD;AAAA,EACA;AAAA,EACT,aAAuC;AAAA,EACvC,QAAQ;AAAA,EACR,SAAoD,CAAA;AAAA,EAE3C;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,QACA,SACA,QAEA,UAAmC,WACnC;AACA,SAAK,QAAQ;AACb,SAAK,UAAU;AACf,SAAK,UAAU;AACf,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,qBAAqB,WAA4B;AAC/C,eAAW,QAAQ,KAAK,QAAQ;AAC9B,UAAI,KAAK,QAAQ,cAAc,WAAW;AACxC,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,OACE,IACA,OACA,QACY;AACZ,WAAO,KAAK,MAAM,EAAE;AAAA,EACtB;AAAA,EAEA,QAAQ,OAA0B;AAChC,eAAW,CAAC,WAAW,IAAI,KAAK,OAAO;AACrC,UAAI,wBAAwB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,EAClB,UAAU,EAAE,qBAAqB,EACjC,aAAa,EAAE,aAAa,iBAkC7B"}
@@ -46,7 +46,10 @@ async function addDiffsForIndexes(mainCommit, syncCommit, read, diffsMap, diffCo
46
46
  }
47
47
  const newIndex = newIndexes.get(oldIndexName);
48
48
  if (newIndex !== void 0) {
49
- assert(newIndex !== oldIndex);
49
+ assert(
50
+ newIndex !== oldIndex,
51
+ "Expected newIndex to differ from oldIndex"
52
+ );
50
53
  const diffs = await diff$1(oldIndex.map, newIndex.map);
51
54
  newIndexes.delete(oldIndexName);
52
55
  diffsMap.set(oldIndexName, diffs);
@@ -1 +1 @@
1
- {"version":3,"file":"diff.js","sources":["../../../../../replicache/src/sync/diff.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Enum} from '../../../shared/src/enum.ts';\nimport {diff as btreeDiff} from '../btree/diff.ts';\nimport type {InternalDiff} from '../btree/node.ts';\nimport {allEntriesAsDiff, BTreeRead} from '../btree/read.ts';\nimport type {Read} from '../dag/store.ts';\nimport type {Commit} from '../db/commit.ts';\nimport {commitFromHash, type Meta} from '../db/commit.ts';\nimport {readIndexesForRead} from '../db/read.ts';\nimport type * as FormatVersion from '../format-version-enum.ts';\nimport type {Hash} from '../hash.ts';\n\ntype FormatVersion = Enum<typeof FormatVersion>;\n\n/**\n * Interface allowing different diff functions to skip costly diff computations.\n */\nexport interface DiffComputationConfig {\n shouldComputeDiffs(): boolean;\n shouldComputeDiffsForIndex(name: string): boolean;\n}\n\n/**\n * The diffs in different indexes. The key of the map is the index name.\n * \"\" is used for the primary index.\n */\nexport class DiffsMap extends Map<string, InternalDiff> {\n override set(key: string, value: InternalDiff): this {\n if (value.length === 0) {\n return this;\n }\n return super.set(key, value);\n }\n}\n\n/**\n * Diffs the state of the db at two different hashes.\n * It will include the primary indexes as well as all the secondary indexes.\n */\nexport async function diff(\n oldHash: Hash,\n newHash: Hash,\n read: Read,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n): Promise<DiffsMap> {\n const [oldCommit, newCommit] = await Promise.all([\n commitFromHash(oldHash, read),\n commitFromHash(newHash, read),\n ]);\n\n return diffCommits(oldCommit, newCommit, read, diffConfig, formatVersion);\n}\n\n/**\n * Diffs the state of the db at two different commits.\n * It will include the primary indexes as well as all the secondary indexes.\n */\n// TODO: this should probably move to db/\nexport async function diffCommits(\n oldCommit: Commit<Meta>,\n newCommit: Commit<Meta>,\n read: Read,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n): Promise<DiffsMap> {\n const diffsMap = new DiffsMap();\n if (!diffConfig.shouldComputeDiffs()) {\n return diffsMap;\n }\n\n const oldMap = new BTreeRead(read, formatVersion, oldCommit.valueHash);\n const newMap = new BTreeRead(read, formatVersion, newCommit.valueHash);\n const valueDiff = await btreeDiff(oldMap, newMap);\n diffsMap.set('', valueDiff);\n\n await addDiffsForIndexes(\n oldCommit,\n newCommit,\n read,\n diffsMap,\n diffConfig,\n formatVersion,\n );\n\n return diffsMap;\n}\n\nexport async function addDiffsForIndexes(\n mainCommit: Commit<Meta>,\n syncCommit: Commit<Meta>,\n read: Read,\n diffsMap: DiffsMap,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n) {\n const oldIndexes = readIndexesForRead(mainCommit, read, formatVersion);\n const newIndexes = readIndexesForRead(syncCommit, read, formatVersion);\n\n for (const [oldIndexName, oldIndex] of oldIndexes) {\n if (!diffConfig.shouldComputeDiffsForIndex(oldIndexName)) {\n continue;\n }\n\n const newIndex = newIndexes.get(oldIndexName);\n if (newIndex !== undefined) {\n assert(newIndex !== oldIndex);\n const diffs = await btreeDiff(oldIndex.map, newIndex.map);\n newIndexes.delete(oldIndexName);\n diffsMap.set(oldIndexName, diffs);\n } else {\n // old index name is not in the new indexes. All entries removed!\n const diffs = await allEntriesAsDiff(oldIndex.map, 'del');\n diffsMap.set(oldIndexName, diffs);\n }\n }\n\n for (const [newIndexName, newIndex] of newIndexes) {\n if (!diffConfig.shouldComputeDiffsForIndex(newIndexName)) {\n continue;\n }\n // new index name is not in the old indexes. All keys added!\n const diffs = await allEntriesAsDiff(newIndex.map, 'add');\n diffsMap.set(newIndexName, diffs);\n }\n}\n"],"names":["btreeDiff"],"mappings":";;;;;AA0BO,MAAM,iBAAiB,IAA0B;AAAA,EAC7C,IAAI,KAAa,OAA2B;AACnD,QAAI,MAAM,WAAW,GAAG;AACtB,aAAO;AAAA,IACT;AACA,WAAO,MAAM,IAAI,KAAK,KAAK;AAAA,EAC7B;AACF;AAMA,eAAsB,KACpB,SACA,SACA,MACA,YACA,eACmB;AACnB,QAAM,CAAC,WAAW,SAAS,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC/C,eAAe,SAAS,IAAI;AAAA,IAC5B,eAAe,SAAS,IAAI;AAAA,EAAA,CAC7B;AAED,SAAO,YAAY,WAAW,WAAW,MAAM,YAAY,aAAa;AAC1E;AAOA,eAAsB,YACpB,WACA,WACA,MACA,YACA,eACmB;AACnB,QAAM,WAAW,IAAI,SAAA;AACrB,MAAI,CAAC,WAAW,sBAAsB;AACpC,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI,UAAU,MAAM,eAAe,UAAU,SAAS;AACrE,QAAM,SAAS,IAAI,UAAU,MAAM,eAAe,UAAU,SAAS;AACrE,QAAM,YAAY,MAAMA,OAAU,QAAQ,MAAM;AAChD,WAAS,IAAI,IAAI,SAAS;AAE1B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AACT;AAEA,eAAsB,mBACpB,YACA,YACA,MACA,UACA,YACA,eACA;AACA,QAAM,aAAa,mBAAmB,YAAY,MAAM,aAAa;AACrE,QAAM,aAAa,mBAAmB,YAAY,MAAM,aAAa;AAErE,aAAW,CAAC,cAAc,QAAQ,KAAK,YAAY;AACjD,QAAI,CAAC,WAAW,2BAA2B,YAAY,GAAG;AACxD;AAAA,IACF;AAEA,UAAM,WAAW,WAAW,IAAI,YAAY;AAC5C,QAAI,aAAa,QAAW;AAC1B,aAAO,aAAa,QAAQ;AAC5B,YAAM,QAAQ,MAAMA,OAAU,SAAS,KAAK,SAAS,GAAG;AACxD,iBAAW,OAAO,YAAY;AAC9B,eAAS,IAAI,cAAc,KAAK;AAAA,IAClC,OAAO;AAEL,YAAM,QAAQ,MAAM,iBAAiB,SAAS,KAAK,KAAK;AACxD,eAAS,IAAI,cAAc,KAAK;AAAA,IAClC;AAAA,EACF;AAEA,aAAW,CAAC,cAAc,QAAQ,KAAK,YAAY;AACjD,QAAI,CAAC,WAAW,2BAA2B,YAAY,GAAG;AACxD;AAAA,IACF;AAEA,UAAM,QAAQ,MAAM,iBAAiB,SAAS,KAAK,KAAK;AACxD,aAAS,IAAI,cAAc,KAAK;AAAA,EAClC;AACF;"}
1
+ {"version":3,"file":"diff.js","sources":["../../../../../replicache/src/sync/diff.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Enum} from '../../../shared/src/enum.ts';\nimport {diff as btreeDiff} from '../btree/diff.ts';\nimport type {InternalDiff} from '../btree/node.ts';\nimport {allEntriesAsDiff, BTreeRead} from '../btree/read.ts';\nimport type {Read} from '../dag/store.ts';\nimport type {Commit} from '../db/commit.ts';\nimport {commitFromHash, type Meta} from '../db/commit.ts';\nimport {readIndexesForRead} from '../db/read.ts';\nimport type * as FormatVersion from '../format-version-enum.ts';\nimport type {Hash} from '../hash.ts';\n\ntype FormatVersion = Enum<typeof FormatVersion>;\n\n/**\n * Interface allowing different diff functions to skip costly diff computations.\n */\nexport interface DiffComputationConfig {\n shouldComputeDiffs(): boolean;\n shouldComputeDiffsForIndex(name: string): boolean;\n}\n\n/**\n * The diffs in different indexes. The key of the map is the index name.\n * \"\" is used for the primary index.\n */\nexport class DiffsMap extends Map<string, InternalDiff> {\n override set(key: string, value: InternalDiff): this {\n if (value.length === 0) {\n return this;\n }\n return super.set(key, value);\n }\n}\n\n/**\n * Diffs the state of the db at two different hashes.\n * It will include the primary indexes as well as all the secondary indexes.\n */\nexport async function diff(\n oldHash: Hash,\n newHash: Hash,\n read: Read,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n): Promise<DiffsMap> {\n const [oldCommit, newCommit] = await Promise.all([\n commitFromHash(oldHash, read),\n commitFromHash(newHash, read),\n ]);\n\n return diffCommits(oldCommit, newCommit, read, diffConfig, formatVersion);\n}\n\n/**\n * Diffs the state of the db at two different commits.\n * It will include the primary indexes as well as all the secondary indexes.\n */\n// TODO: this should probably move to db/\nexport async function diffCommits(\n oldCommit: Commit<Meta>,\n newCommit: Commit<Meta>,\n read: Read,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n): Promise<DiffsMap> {\n const diffsMap = new DiffsMap();\n if (!diffConfig.shouldComputeDiffs()) {\n return diffsMap;\n }\n\n const oldMap = new BTreeRead(read, formatVersion, oldCommit.valueHash);\n const newMap = new BTreeRead(read, formatVersion, newCommit.valueHash);\n const valueDiff = await btreeDiff(oldMap, newMap);\n diffsMap.set('', valueDiff);\n\n await addDiffsForIndexes(\n oldCommit,\n newCommit,\n read,\n diffsMap,\n diffConfig,\n formatVersion,\n );\n\n return diffsMap;\n}\n\nexport async function addDiffsForIndexes(\n mainCommit: Commit<Meta>,\n syncCommit: Commit<Meta>,\n read: Read,\n diffsMap: DiffsMap,\n diffConfig: DiffComputationConfig,\n formatVersion: FormatVersion,\n) {\n const oldIndexes = readIndexesForRead(mainCommit, read, formatVersion);\n const newIndexes = readIndexesForRead(syncCommit, read, formatVersion);\n\n for (const [oldIndexName, oldIndex] of oldIndexes) {\n if (!diffConfig.shouldComputeDiffsForIndex(oldIndexName)) {\n continue;\n }\n\n const newIndex = newIndexes.get(oldIndexName);\n if (newIndex !== undefined) {\n assert(\n newIndex !== oldIndex,\n 'Expected newIndex to differ from oldIndex',\n );\n const diffs = await btreeDiff(oldIndex.map, newIndex.map);\n newIndexes.delete(oldIndexName);\n diffsMap.set(oldIndexName, diffs);\n } else {\n // old index name is not in the new indexes. All entries removed!\n const diffs = await allEntriesAsDiff(oldIndex.map, 'del');\n diffsMap.set(oldIndexName, diffs);\n }\n }\n\n for (const [newIndexName, newIndex] of newIndexes) {\n if (!diffConfig.shouldComputeDiffsForIndex(newIndexName)) {\n continue;\n }\n // new index name is not in the old indexes. All keys added!\n const diffs = await allEntriesAsDiff(newIndex.map, 'add');\n diffsMap.set(newIndexName, diffs);\n }\n}\n"],"names":["btreeDiff"],"mappings":";;;;;AA0BO,MAAM,iBAAiB,IAA0B;AAAA,EAC7C,IAAI,KAAa,OAA2B;AACnD,QAAI,MAAM,WAAW,GAAG;AACtB,aAAO;AAAA,IACT;AACA,WAAO,MAAM,IAAI,KAAK,KAAK;AAAA,EAC7B;AACF;AAMA,eAAsB,KACpB,SACA,SACA,MACA,YACA,eACmB;AACnB,QAAM,CAAC,WAAW,SAAS,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC/C,eAAe,SAAS,IAAI;AAAA,IAC5B,eAAe,SAAS,IAAI;AAAA,EAAA,CAC7B;AAED,SAAO,YAAY,WAAW,WAAW,MAAM,YAAY,aAAa;AAC1E;AAOA,eAAsB,YACpB,WACA,WACA,MACA,YACA,eACmB;AACnB,QAAM,WAAW,IAAI,SAAA;AACrB,MAAI,CAAC,WAAW,sBAAsB;AACpC,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI,UAAU,MAAM,eAAe,UAAU,SAAS;AACrE,QAAM,SAAS,IAAI,UAAU,MAAM,eAAe,UAAU,SAAS;AACrE,QAAM,YAAY,MAAMA,OAAU,QAAQ,MAAM;AAChD,WAAS,IAAI,IAAI,SAAS;AAE1B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AACT;AAEA,eAAsB,mBACpB,YACA,YACA,MACA,UACA,YACA,eACA;AACA,QAAM,aAAa,mBAAmB,YAAY,MAAM,aAAa;AAC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