@rocicorp/zero 1.10.0-canary.24 → 1.10.0-canary.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/analyze-query/src/bin-analyze.js +8 -9
- package/out/analyze-query/src/bin-analyze.js.map +1 -1
- package/out/replicache/src/btree/node.d.ts.map +1 -1
- package/out/replicache/src/btree/node.js +6 -3
- package/out/replicache/src/btree/node.js.map +1 -1
- package/out/replicache/src/btree/read.d.ts +1 -12
- package/out/replicache/src/btree/read.d.ts.map +1 -1
- package/out/replicache/src/btree/read.js +12 -24
- package/out/replicache/src/btree/read.js.map +1 -1
- package/out/replicache/src/dag/gc.d.ts.map +1 -1
- package/out/replicache/src/dag/gc.js +11 -8
- package/out/replicache/src/dag/gc.js.map +1 -1
- package/out/replicache/src/dag/store-impl.d.ts +2 -12
- package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
- package/out/replicache/src/dag/store-impl.js +8 -22
- package/out/replicache/src/dag/store-impl.js.map +1 -1
- package/out/replicache/src/db/rebase.d.ts +2 -14
- package/out/replicache/src/db/rebase.d.ts.map +1 -1
- package/out/replicache/src/db/rebase.js +5 -27
- package/out/replicache/src/db/rebase.js.map +1 -1
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
- package/out/replicache/src/kv/expo-sqlite/store.js +5 -28
- package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts +5 -15
- package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts.map +1 -1
- package/out/replicache/src/kv/idb-store-with-mem-fallback.js +25 -25
- package/out/replicache/src/kv/idb-store-with-mem-fallback.js.map +1 -1
- package/out/replicache/src/kv/idb-store.d.ts +0 -9
- package/out/replicache/src/kv/idb-store.d.ts.map +1 -1
- package/out/replicache/src/kv/idb-store.js +2 -14
- package/out/replicache/src/kv/idb-store.js.map +1 -1
- package/out/replicache/src/kv/mem-store.d.ts +0 -1
- package/out/replicache/src/kv/mem-store.d.ts.map +1 -1
- package/out/replicache/src/kv/mem-store.js +0 -3
- package/out/replicache/src/kv/mem-store.js.map +1 -1
- package/out/replicache/src/kv/op-sqlite/store.d.ts.map +1 -1
- package/out/replicache/src/kv/op-sqlite/store.js +1 -1
- package/out/replicache/src/kv/op-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/sqlite-store.d.ts +1 -13
- package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
- package/out/replicache/src/kv/sqlite-store.js +6 -73
- package/out/replicache/src/kv/sqlite-store.js.map +1 -1
- package/out/replicache/src/kv/store.d.ts +0 -6
- package/out/replicache/src/kv/store.d.ts.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.d.ts +5 -10
- package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.js +9 -16
- package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
- package/out/replicache/src/persist/persist.d.ts.map +1 -1
- package/out/replicache/src/persist/persist.js +6 -13
- package/out/replicache/src/persist/persist.js.map +1 -1
- package/out/replicache/src/persist/refresh.js +2 -6
- package/out/replicache/src/persist/refresh.js.map +1 -1
- package/out/replicache/src/replicache-impl.d.ts +3 -14
- package/out/replicache/src/replicache-impl.d.ts.map +1 -1
- package/out/replicache/src/replicache-impl.js +11 -118
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/replicache-options.d.ts +0 -9
- package/out/replicache/src/replicache-options.d.ts.map +1 -1
- package/out/replicache/src/transactions.d.ts.map +1 -1
- package/out/replicache/src/transactions.js +1 -1
- package/out/replicache/src/transactions.js.map +1 -1
- package/out/shared/src/arrays.d.ts +0 -5
- package/out/shared/src/arrays.d.ts.map +1 -1
- package/out/shared/src/arrays.js +24 -8
- package/out/shared/src/arrays.js.map +1 -1
- package/out/shared/src/base64.d.ts +19 -0
- package/out/shared/src/base64.d.ts.map +1 -0
- package/out/shared/src/base64.js +40 -0
- package/out/shared/src/base64.js.map +1 -0
- package/out/shared/src/error.d.ts +0 -11
- package/out/shared/src/error.d.ts.map +1 -1
- package/out/shared/src/error.js +1 -35
- package/out/shared/src/error.js.map +1 -1
- package/out/shared/src/hash.d.ts +0 -1
- package/out/shared/src/hash.d.ts.map +1 -1
- package/out/shared/src/hash.js +10 -87
- package/out/shared/src/hash.js.map +1 -1
- package/out/shared/src/iterables.d.ts +0 -2
- package/out/shared/src/iterables.d.ts.map +1 -1
- package/out/shared/src/iterables.js +1 -18
- package/out/shared/src/iterables.js.map +1 -1
- package/out/shared/src/json.d.ts.map +1 -1
- package/out/shared/src/json.js +2 -2
- package/out/shared/src/json.js.map +1 -1
- package/out/shared/src/map.d.ts +2 -24
- package/out/shared/src/map.d.ts.map +1 -1
- package/out/shared/src/map.js +4 -18
- package/out/shared/src/map.js.map +1 -1
- package/out/shared/src/ring-buffer.d.ts +0 -8
- package/out/shared/src/ring-buffer.d.ts.map +1 -1
- package/out/shared/src/ring-buffer.js +1 -22
- package/out/shared/src/ring-buffer.js.map +1 -1
- package/out/z2s/src/sql.d.ts.map +1 -1
- package/out/z2s/src/sql.js +2 -2
- package/out/z2s/src/sql.js.map +1 -1
- package/out/zero/package.js +3 -2
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/read-authorizer.js +1 -1
- package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +0 -1
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +2 -42
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +28 -149
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.js +1 -1
- package/out/zero-cache/src/db/create.d.ts.map +1 -1
- package/out/zero-cache/src/db/create.js +1 -4
- package/out/zero-cache/src/db/create.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.d.ts +2 -10
- package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +6 -10
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/specs.d.ts +0 -41
- package/out/zero-cache/src/db/specs.d.ts.map +1 -1
- package/out/zero-cache/src/db/specs.js +3 -30
- package/out/zero-cache/src/db/specs.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/observability/metrics.js +7 -2
- package/out/zero-cache/src/observability/metrics.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +4 -13
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.d.ts +2 -18
- package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js +17 -25
- package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
- package/out/zero-cache/src/server/main.d.ts.map +1 -1
- package/out/zero-cache/src/server/main.js +1 -8
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/mutator.js +0 -2
- package/out/zero-cache/src/server/mutator.js.map +1 -1
- package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
- package/out/zero-cache/src/server/reaper.js +0 -2
- package/out/zero-cache/src/server/reaper.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +2 -8
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
- package/out/zero-cache/src/server/runner/zero-dispatcher.js +0 -3
- package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -5
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
- package/out/zero-cache/src/services/analyze.js +9 -11
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js +1 -14
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +3 -15
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +1 -11
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +2 -21
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +0 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +7 -8
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +229 -1513
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +2 -2
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -15
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +20 -137
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js +13 -82
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +21 -128
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +5 -5
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +0 -2
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +0 -3
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +0 -3
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +1 -3
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +0 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +3 -8
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/config-v5.yml +1 -15
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts +0 -5
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +1 -7
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.d.ts +119 -119
- package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.js +6 -5
- package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +16 -16
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +0 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.d.ts +2 -27
- package/out/zero-cache/src/services/replicator/write-worker-client.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.js +2 -3
- package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js +5 -24
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts +0 -12
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +15 -27
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/runner.d.ts.map +1 -1
- package/out/zero-cache/src/services/runner.js +1 -1
- package/out/zero-cache/src/services/runner.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts +0 -45
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +1 -133
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts +1 -14
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +4 -30
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +1 -2
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +27 -48
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.js +6 -2
- package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +4 -42
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +28 -117
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +1 -11
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +95 -466
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/processes.d.ts +0 -32
- package/out/zero-cache/src/types/processes.d.ts.map +1 -1
- package/out/zero-cache/src/types/processes.js +4 -43
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/profiler.d.ts +0 -12
- package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
- package/out/zero-cache/src/types/profiler.js +1 -46
- package/out/zero-cache/src/types/profiler.js.map +1 -1
- package/out/zero-cache/src/types/row-key.d.ts.map +1 -1
- package/out/zero-cache/src/types/row-key.js +5 -5
- package/out/zero-cache/src/types/row-key.js.map +1 -1
- package/out/zero-cache/src/workers/connect-params.d.ts +7 -0
- package/out/zero-cache/src/workers/connect-params.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connect-params.js +20 -1
- package/out/zero-cache/src/workers/connect-params.js.map +1 -1
- package/out/zero-cache/src/workers/connection.d.ts +4 -4
- package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connection.js +8 -8
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.d.ts +0 -1
- package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +2 -4
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js +16 -21
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +1 -10
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/connection-manager.d.ts +0 -20
- package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/connection-manager.js +13 -77
- package/out/zero-client/src/client/connection-manager.js.map +1 -1
- package/out/zero-client/src/client/connection-status-enum.d.ts +0 -2
- package/out/zero-client/src/client/connection-status-enum.d.ts.map +1 -1
- package/out/zero-client/src/client/connection-status-enum.js +1 -3
- package/out/zero-client/src/client/connection-status-enum.js.map +1 -1
- package/out/zero-client/src/client/connection.d.ts +0 -6
- package/out/zero-client/src/client/connection.d.ts.map +1 -1
- package/out/zero-client/src/client/connection.js +1 -2
- package/out/zero-client/src/client/connection.js.map +1 -1
- package/out/zero-client/src/client/context.d.ts +2 -27
- package/out/zero-client/src/client/context.d.ts.map +1 -1
- package/out/zero-client/src/client/context.js +1 -112
- package/out/zero-client/src/client/context.js.map +1 -1
- package/out/zero-client/src/client/custom.js +2 -2
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/error.js +1 -1
- package/out/zero-client/src/client/inspector/lazy-inspector.js +2 -2
- package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
- package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
- package/out/zero-client/src/client/ivm-branch.js +3 -20
- package/out/zero-client/src/client/ivm-branch.js.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.d.ts.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.js +1 -1
- package/out/zero-client/src/client/mutation-tracker.js.map +1 -1
- package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
- package/out/zero-client/src/client/mutator-proxy.js +1 -2
- package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
- package/out/zero-client/src/client/options.d.ts +0 -3
- package/out/zero-client/src/client/options.d.ts.map +1 -1
- package/out/zero-client/src/client/options.js.map +1 -1
- package/out/zero-client/src/client/query-manager.d.ts +0 -2
- package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/query-manager.js +14 -50
- package/out/zero-client/src/client/query-manager.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero-rep.d.ts +0 -1
- package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
- package/out/zero-client/src/client/zero-rep.js +6 -9
- package/out/zero-client/src/client/zero-rep.js.map +1 -1
- package/out/zero-client/src/client/zero.d.ts +3 -18
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +36 -123
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-client/src/types/query-result.d.ts +0 -2
- package/out/zero-client/src/types/query-result.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.d.ts +5 -5
- package/out/zero-protocol/src/analyze-query-result.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.js +1 -1
- package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
- package/out/zero-protocol/src/ast.d.ts +1 -64
- package/out/zero-protocol/src/ast.d.ts.map +1 -1
- package/out/zero-protocol/src/ast.js +54 -225
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/connect.d.ts +13 -0
- package/out/zero-protocol/src/connect.d.ts.map +1 -1
- package/out/zero-protocol/src/connect.js +30 -1
- package/out/zero-protocol/src/connect.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-protocol/src/error.d.ts +1 -1
- package/out/zero-protocol/src/inspect-down.d.ts +6 -6
- package/out/zero-protocol/src/poke.d.ts +11 -4
- package/out/zero-protocol/src/poke.d.ts.map +1 -1
- package/out/zero-protocol/src/poke.js +3 -2
- package/out/zero-protocol/src/poke.js.map +1 -1
- package/out/zero-protocol/src/protocol-flag-enum.d.ts +7 -0
- package/out/zero-protocol/src/protocol-flag-enum.d.ts.map +1 -0
- package/out/zero-protocol/src/protocol-flag-enum.js +7 -0
- package/out/zero-protocol/src/protocol-flag-enum.js.map +1 -0
- package/out/zero-protocol/src/protocol-flag.d.ts +14 -0
- package/out/zero-protocol/src/protocol-flag.d.ts.map +1 -0
- package/out/zero-protocol/src/protocol-flag.js +8 -0
- package/out/zero-protocol/src/protocol-flag.js.map +1 -0
- package/out/zero-protocol/src/protocol-version.d.ts +30 -6
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/query-hash.d.ts +2 -7
- package/out/zero-protocol/src/query-hash.d.ts.map +1 -1
- package/out/zero-protocol/src/query-hash.js +10 -10
- package/out/zero-protocol/src/query-hash.js.map +1 -1
- package/out/zero-react/src/use-query.d.ts +4 -5
- package/out/zero-react/src/use-query.d.ts.map +1 -1
- package/out/zero-react/src/use-query.js +9 -86
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-solid/src/solid-view.d.ts +0 -17
- package/out/zero-solid/src/solid-view.d.ts.map +1 -1
- package/out/zero-solid/src/solid-view.js +1 -39
- package/out/zero-solid/src/solid-view.js.map +1 -1
- package/out/zero-solid/src/use-query.js +3 -5
- package/out/zero-solid/src/use-query.js.map +1 -1
- package/out/zql/src/builder/builder.d.ts +0 -19
- package/out/zql/src/builder/builder.d.ts.map +1 -1
- package/out/zql/src/builder/builder.js +11 -28
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/builder/debug-delegate.d.ts +1 -6
- package/out/zql/src/builder/debug-delegate.d.ts.map +1 -1
- package/out/zql/src/builder/debug-delegate.js +2 -14
- package/out/zql/src/builder/debug-delegate.js.map +1 -1
- package/out/zql/src/ivm/array-view.d.ts +0 -29
- package/out/zql/src/ivm/array-view.d.ts.map +1 -1
- package/out/zql/src/ivm/array-view.js +12 -63
- package/out/zql/src/ivm/array-view.js.map +1 -1
- package/out/zql/src/ivm/cap.d.ts.map +1 -1
- package/out/zql/src/ivm/cap.js +3 -5
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/data.d.ts.map +1 -1
- package/out/zql/src/ivm/data.js +3 -8
- package/out/zql/src/ivm/data.js.map +1 -1
- package/out/zql/src/ivm/exists.d.ts +1 -1
- package/out/zql/src/ivm/exists.d.ts.map +1 -1
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/fan-in.d.ts +2 -2
- package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-in.js +5 -6
- package/out/zql/src/ivm/fan-in.js.map +1 -1
- package/out/zql/src/ivm/fan-out.d.ts +2 -2
- package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-out.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts +6 -7
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js +12 -29
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/filter.d.ts +2 -2
- package/out/zql/src/ivm/filter.d.ts.map +1 -1
- package/out/zql/src/ivm/filter.js +4 -7
- package/out/zql/src/ivm/filter.js.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +2 -2
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +4 -6
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts +3 -15
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +23 -57
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/operator.d.ts +0 -40
- package/out/zql/src/ivm/operator.d.ts.map +1 -1
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/ivm/take.d.ts.map +1 -1
- package/out/zql/src/ivm/take.js +4 -3
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/union-fan-in.js +7 -9
- package/out/zql/src/ivm/union-fan-in.js.map +1 -1
- package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
- package/out/zql/src/ivm/view-apply-change.js +4 -9
- package/out/zql/src/ivm/view-apply-change.js.map +1 -1
- package/out/zql/src/ivm/view.d.ts +0 -15
- package/out/zql/src/ivm/view.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator-registry.js +2 -2
- package/out/zql/src/mutate/mutator-registry.js.map +1 -1
- package/out/zql/src/planner/planner-builder.d.ts +3 -12
- package/out/zql/src/planner/planner-builder.d.ts.map +1 -1
- package/out/zql/src/planner/planner-builder.js +20 -40
- package/out/zql/src/planner/planner-builder.js.map +1 -1
- package/out/zql/src/planner/planner-connection.d.ts +2 -28
- package/out/zql/src/planner/planner-connection.d.ts.map +1 -1
- package/out/zql/src/planner/planner-connection.js +8 -108
- package/out/zql/src/planner/planner-connection.js.map +1 -1
- package/out/zql/src/planner/planner-debug.d.ts +1 -1
- package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
- package/out/zql/src/planner/planner-debug.js +8 -3
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/planner/planner-fan-out.d.ts +0 -1
- package/out/zql/src/planner/planner-fan-out.d.ts.map +1 -1
- package/out/zql/src/planner/planner-fan-out.js +0 -3
- package/out/zql/src/planner/planner-fan-out.js.map +1 -1
- package/out/zql/src/planner/planner-graph.d.ts +0 -2
- package/out/zql/src/planner/planner-graph.d.ts.map +1 -1
- package/out/zql/src/planner/planner-graph.js +0 -2
- package/out/zql/src/planner/planner-graph.js.map +1 -1
- package/out/zql/src/planner/planner-join.d.ts +0 -2
- package/out/zql/src/planner/planner-join.d.ts.map +1 -1
- package/out/zql/src/planner/planner-join.js +0 -7
- package/out/zql/src/planner/planner-join.js.map +1 -1
- package/out/zql/src/planner/planner-node.d.ts +1 -2
- package/out/zql/src/planner/planner-node.d.ts.map +1 -1
- package/out/zql/src/planner/planner-node.js.map +1 -1
- package/out/zql/src/planner/planner-source.d.ts +2 -2
- package/out/zql/src/planner/planner-source.d.ts.map +1 -1
- package/out/zql/src/planner/planner-source.js +2 -2
- package/out/zql/src/planner/planner-source.js.map +1 -1
- package/out/zql/src/query/query-delegate-base.d.ts +1 -9
- package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
- package/out/zql/src/query/query-delegate-base.js +36 -132
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-delegate.d.ts +1 -50
- package/out/zql/src/query/query-delegate.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +14 -25
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js +94 -397
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-internals.d.ts +11 -21
- package/out/zql/src/query/query-internals.d.ts.map +1 -1
- package/out/zql/src/query/query-internals.js.map +1 -1
- package/out/zql/src/query/query.d.ts +2 -11
- package/out/zql/src/query/query.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.d.ts +2 -3
- package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.js +2 -15
- package/out/zql/src/query/runnable-query-impl.js.map +1 -1
- package/out/zql/src/query/typed-view.d.ts +1 -1
- package/out/zql/src/query/typed-view.d.ts.map +1 -1
- package/out/zqlite/src/db.d.ts +1 -9
- package/out/zqlite/src/db.d.ts.map +1 -1
- package/out/zqlite/src/db.js +2 -8
- package/out/zqlite/src/db.js.map +1 -1
- package/out/zqlite/src/query-builder.d.ts +1 -1
- package/out/zqlite/src/query-builder.d.ts.map +1 -1
- package/out/zqlite/src/query-builder.js +2 -4
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/query-delegate.d.ts.map +1 -1
- package/out/zqlite/src/query-delegate.js +6 -5
- package/out/zqlite/src/query-delegate.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js +30 -2
- package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.js +5 -4
- package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts +3 -16
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +14 -33
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +3 -2
- package/out/replicache/src/dag/invalid-ref-count-error.d.ts +0 -12
- package/out/replicache/src/dag/invalid-ref-count-error.d.ts.map +0 -1
- package/out/replicache/src/dag/invalid-ref-count-error.js +0 -19
- package/out/replicache/src/dag/invalid-ref-count-error.js.map +0 -1
- package/out/shared/src/xxhash32.d.ts +0 -36
- package/out/shared/src/xxhash32.d.ts.map +0 -1
- package/out/shared/src/xxhash32.js +0 -51
- package/out/shared/src/xxhash32.js.map +0 -1
- package/out/zero-cache/src/db/index-predicate.d.ts +0 -4
- package/out/zero-cache/src/db/index-predicate.d.ts.map +0 -1
- package/out/zero-cache/src/db/index-predicate.js +0 -46
- package/out/zero-cache/src/db/index-predicate.js.map +0 -1
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts +0 -19
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js +0 -581
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +0 -131
- package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-controller.d.ts +0 -70
- package/out/zero-cache/src/services/litestream/litestream-controller.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-controller.js +0 -101
- package/out/zero-cache/src/services/litestream/litestream-controller.js.map +0 -1
- package/out/zero-cache/src/services/profz.d.ts +0 -7
- package/out/zero-cache/src/services/profz.d.ts.map +0 -1
- package/out/zero-cache/src/services/profz.js +0 -103
- package/out/zero-cache/src/services/profz.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts +0 -33
- package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-budget.js +0 -62
- package/out/zero-cache/src/services/view-syncer/hydration-budget.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts +0 -51
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js +0 -78
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts +0 -95
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +0 -155
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +0 -1
- package/out/zero-protocol/src/query-hash-visitor.d.ts +0 -81
- package/out/zero-protocol/src/query-hash-visitor.d.ts.map +0 -1
- package/out/zero-protocol/src/query-hash-visitor.js +0 -324
- package/out/zero-protocol/src/query-hash-visitor.js.map +0 -1
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts +0 -43
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts.map +0 -1
- package/out/zql/src/builder/correlated-predicate-pushdown.js +0 -161
- package/out/zql/src/builder/correlated-predicate-pushdown.js.map +0 -1
- package/out/zql/src/ivm/connection-index.d.ts +0 -68
- package/out/zql/src/ivm/connection-index.d.ts.map +0 -1
- package/out/zql/src/ivm/connection-index.js +0 -149
- package/out/zql/src/ivm/connection-index.js.map +0 -1
- package/out/zql/src/ivm/deferred-input.d.ts +0 -44
- package/out/zql/src/ivm/deferred-input.d.ts.map +0 -1
- package/out/zql/src/ivm/deferred-input.js +0 -89
- package/out/zql/src/ivm/deferred-input.js.map +0 -1
- package/out/zql/src/planner/planner-filter.d.ts +0 -59
- package/out/zql/src/planner/planner-filter.d.ts.map +0 -1
- package/out/zql/src/planner/planner-filter.js +0 -116
- package/out/zql/src/planner/planner-filter.js.map +0 -1
- package/out/zql/src/query/query-transitions.d.ts +0 -171
- package/out/zql/src/query/query-transitions.d.ts.map +0 -1
- package/out/zql/src/query/query-transitions.js +0 -204
- package/out/zql/src/query/query-transitions.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ivm-branch.js","names":["#sources","#tables","#throwIfInvalid","#advanceError"],"sources":["../../../../../zero-client/src/client/ivm-branch.ts"],"sourcesContent":["import type {\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from '../../../replicache/src/btree/node.ts';\nimport type {LazyStore} from '../../../replicache/src/dag/lazy-store.ts';\nimport {type Read, type Store} from '../../../replicache/src/dag/store.ts';\nimport {readFromHash} from '../../../replicache/src/db/read.ts';\nimport * as FormatVersion from '../../../replicache/src/format-version-enum.ts';\nimport type {Hash} from '../../../replicache/src/hash.ts';\nimport type {ZeroReadOptions} from '../../../replicache/src/replicache-options.ts';\nimport {diffBinarySearch} from '../../../replicache/src/subscriptions.ts';\nimport type {DiffsMap} from '../../../replicache/src/sync/diff.ts';\nimport {diff} from '../../../replicache/src/sync/diff.ts';\nimport {using, withRead} from '../../../replicache/src/with-transactions.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {wrapIterable} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport {MemorySource} from '../../../zql/src/ivm/memory-source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {ENTITIES_KEY_PREFIX, sourceNameFromKey} from './keys.ts';\n\nimport {\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\n/**\n * Replicache needs to rebase mutations onto different\n * commits of it's b-tree. These mutations can have reads\n * in them and those reads must be run against the IVM sources.\n *\n * To ensure the reads get the correct state, the IVM\n * sources need to reflect the state of the commit\n * being rebased onto. `IVMSourceBranch` allows us to:\n * 1. fork the IVM sources\n * 2. patch them up to match the desired head\n * 3. run the reads against the forked sources\n *\n * (2) is expected to be a cheap operation as there should only\n * ever be a few outstanding diffs to apply given Zero is meant\n * to be run in a connected state.\n */\nexport class IVMSourceBranch {\n readonly #sources: Map<string, MemorySource | undefined>;\n readonly #tables: Record<string, TableSchema>;\n #advanceError: unknown;\n hash: Hash | undefined;\n\n constructor(\n tables: Record<string, TableSchema>,\n hash?: Hash,\n sources: Map<string, MemorySource | undefined> = new Map(),\n ) {\n this.#tables = tables;\n this.#sources = sources;\n this.hash = hash;\n }\n\n getSource(name: string): MemorySource | undefined {\n this.#throwIfInvalid();\n\n if (this.#sources.has(name)) {\n return this.#sources.get(name);\n }\n\n const schema = this.#tables[name];\n const source = schema\n ? new MemorySource(name, schema.columns, schema.primaryKey)\n : undefined;\n this.#sources.set(name, source);\n return source;\n }\n\n clear() {\n this.#sources.clear();\n }\n\n #throwIfInvalid() {\n if (this.#advanceError) {\n throw this.#advanceError;\n }\n }\n\n /**\n * Mutates the current branch, advancing it to the new head\n * by applying the given diffs.\n */\n advance(expectedHead: Hash | undefined, newHead: Hash, diffs: NoIndexDiff) {\n this.#throwIfInvalid();\n\n assert(\n this.hash === expectedHead,\n () =>\n `Expected head must match the main head. Got: ${this.hash}, expected: ${expectedHead}`,\n );\n\n try {\n applyDiffs(diffs, this);\n this.hash = newHead;\n } catch (e) {\n this.#advanceError = e;\n this.clear();\n throw e;\n }\n }\n\n /**\n * Fork the branch and patch it up to match the desired head.\n */\n async forkToHead(\n store: LazyStore,\n desiredHead: Hash,\n readOptions?: ZeroReadOptions,\n ): Promise<IVMSourceBranch> {\n this.#throwIfInvalid();\n\n const fork = this.fork();\n\n if (fork.hash === desiredHead) {\n return fork;\n }\n\n await patchBranch(desiredHead, store, fork, readOptions);\n fork.hash = desiredHead;\n return fork;\n }\n\n /**\n * Creates a new IVMSourceBranch that is a copy of the current one.\n * This is a cheap operation since the b-trees are shared until a write is performed\n * and then only the modified nodes are copied.\n *\n * IVM branches are forked when we need to rebase mutations.\n * The mutations modify the fork rather than original branch.\n */\n fork() {\n this.#throwIfInvalid();\n\n return new IVMSourceBranch(\n this.#tables,\n this.hash,\n new Map(\n wrapIterable(this.#sources.entries()).map(([name, source]) => [\n name,\n source?.fork(),\n ]),\n ),\n );\n }\n}\n\nexport async function initFromStore(\n branch: IVMSourceBranch,\n hash: Hash,\n store: Store,\n) {\n const diffs: InternalDiffOperation[] = [];\n await withRead(store, async dagRead => {\n const read = await readFromHash(hash, dagRead, FormatVersion.Latest);\n for await (const entry of read.map.scan(ENTITIES_KEY_PREFIX, true)) {\n if (!entry[0].startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n diffs.push({\n op: 'add',\n key: entry[0],\n newValue: entry[1],\n });\n }\n });\n\n branch.advance(undefined, hash, diffs);\n}\n\nasync function patchBranch(\n desiredHead: Hash,\n store: LazyStore,\n fork: IVMSourceBranch,\n readOptions: ZeroReadOptions | undefined,\n) {\n const diffs = await computeDiffs(\n must(fork.hash),\n desiredHead,\n store,\n readOptions,\n );\n if (!diffs) {\n return;\n }\n applyDiffs(diffs, fork);\n}\n\nasync function computeDiffs(\n startHash: Hash,\n endHash: Hash,\n store: LazyStore,\n readOptions: ZeroReadOptions | undefined,\n): Promise<InternalDiff | undefined> {\n const readFn = (dagRead: Read) =>\n diff(\n startHash,\n endHash,\n dagRead,\n {\n shouldComputeDiffs: () => true,\n shouldComputeDiffsForIndex(_name) {\n return false;\n },\n },\n FormatVersion.Latest,\n );\n\n let diffs: DiffsMap;\n if (readOptions?.openLazySourceRead) {\n diffs = await using(store.read(readOptions.openLazySourceRead), readFn);\n } else if (readOptions?.openLazyRead) {\n diffs = await readFn(readOptions.openLazyRead);\n } else {\n diffs = await withRead(store, readFn);\n }\n\n return diffs.get('');\n}\n\nfunction applyDiffs(diffs: NoIndexDiff, branch: IVMSourceBranch) {\n for (\n let i = diffBinarySearch(diffs, ENTITIES_KEY_PREFIX, diff => diff.key);\n i < diffs.length;\n i++\n ) {\n const diff = diffs[i];\n const {key} = diff;\n if (!key.startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n const name = sourceNameFromKey(key);\n const source = must(branch.getSource(name));\n switch (diff.op) {\n case 'del':\n consume(source.push(makeSourceChangeRemove(diff.oldValue as Row)));\n break;\n case 'add': {\n const rows = takeAddsForSource(diffs, i, name);\n i += rows.length - 1;\n source.pushAdds(rows);\n break;\n }\n case 'change':\n consume(\n source.push(\n makeSourceChangeEdit(diff.newValue as Row, diff.oldValue as Row),\n ),\n );\n break;\n }\n }\n}\n\n/**\n * Returns the rows of the run of `add` diffs for the source `name` that starts\n * at `start`. Diffs are ordered by key so a table's rows are contiguous.\n */\nfunction takeAddsForSource(\n diffs: NoIndexDiff,\n start: number,\n name: string,\n): Row[] {\n const prefix = ENTITIES_KEY_PREFIX + name + '/';\n const rows: Row[] = [];\n for (let i = start; i < diffs.length; i++) {\n const diff = diffs[i];\n if (diff.op !== 'add' || !diff.key.startsWith(prefix)) {\n break;\n }\n rows.push(diff.newValue as Row);\n }\n return rows;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,kBAAb,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CAEA,YACE,QACA,MACA,0BAAiD,IAAI,IAAI,GACzD;EACA,KAAKC,UAAU;EACf,KAAKD,WAAW;EAChB,KAAK,OAAO;CACd;CAEA,UAAU,MAAwC;EAChD,KAAKE,gBAAgB;EAErB,IAAI,KAAKF,SAAS,IAAI,IAAI,GACxB,OAAO,KAAKA,SAAS,IAAI,IAAI;EAG/B,MAAM,SAAS,KAAKC,QAAQ;EAC5B,MAAM,SAAS,SACX,IAAI,aAAa,MAAM,OAAO,SAAS,OAAO,UAAU,IACxD,KAAA;EACJ,KAAKD,SAAS,IAAI,MAAM,MAAM;EAC9B,OAAO;CACT;CAEA,QAAQ;EACN,KAAKA,SAAS,MAAM;CACtB;CAEA,kBAAkB;EAChB,IAAI,KAAKG,eACP,MAAM,KAAKA;CAEf;;;;;CAMA,QAAQ,cAAgC,SAAe,OAAoB;EACzE,KAAKD,gBAAgB;EAErB,OACE,KAAK,SAAS,oBAEZ,gDAAgD,KAAK,KAAK,cAAc,cAC5E;EAEA,IAAI;GACF,WAAW,OAAO,IAAI;GACtB,KAAK,OAAO;EACd,SAAS,GAAG;GACV,KAAKC,gBAAgB;GACrB,KAAK,MAAM;GACX,MAAM;EACR;CACF;;;;CAKA,MAAM,WACJ,OACA,aACA,aAC0B;EAC1B,KAAKD,gBAAgB;EAErB,MAAM,OAAO,KAAK,KAAK;EAEvB,IAAI,KAAK,SAAS,aAChB,OAAO;EAGT,MAAM,YAAY,aAAa,OA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OAAO,GAAG,IAAI;IAC7C,KAAK,KAAK,SAAS;IACnB,OAAO,SAAS,IAAI;IACpB;GACF;GACA,KAAK;IACH,QACE,OAAO,KACL,qBAAqB,KAAK,UAAiB,KAAK,QAAe,CACjE,CACF;IACA;EACJ;CACF;AACF;;;;;AAMA,SAAS,kBACP,OACA,OACA,MACO;CACP,MAAM,SAAA,OAA+B,OAAO;CAC5C,MAAM,OAAc,CAAC;CACrB,KAAK,IAAI,IAAI,OAAO,IAAI,MAAM,QAAQ,KAAK;EACzC,MAAM,OAAO,MAAM;EACnB,IAAI,KAAK,OAAO,SAAS,CAAC,KAAK,IAAI,WAAW,MAAM,GAClD;EAEF,KAAK,KAAK,KAAK,QAAe;CAChC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"ivm-branch.js","names":["#sources","#tables","#throwIfInvalid","#advanceError"],"sources":["../../../../../zero-client/src/client/ivm-branch.ts"],"sourcesContent":["import type {\n InternalDiff,\n InternalDiffOperation,\n NoIndexDiff,\n} from '../../../replicache/src/btree/node.ts';\nimport type {LazyStore} from '../../../replicache/src/dag/lazy-store.ts';\nimport {type Read, type Store} from '../../../replicache/src/dag/store.ts';\nimport {readFromHash} from '../../../replicache/src/db/read.ts';\nimport * as FormatVersion from '../../../replicache/src/format-version-enum.ts';\nimport type {Hash} from '../../../replicache/src/hash.ts';\nimport type {ZeroReadOptions} from '../../../replicache/src/replicache-options.ts';\nimport {diffBinarySearch} from '../../../replicache/src/subscriptions.ts';\nimport type {DiffsMap} from '../../../replicache/src/sync/diff.ts';\nimport {diff} from '../../../replicache/src/sync/diff.ts';\nimport {using, withRead} from '../../../replicache/src/with-transactions.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {wrapIterable} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport {MemorySource} from '../../../zql/src/ivm/memory-source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {ENTITIES_KEY_PREFIX, sourceNameFromKey} from './keys.ts';\n\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\n/**\n * Replicache needs to rebase mutations onto different\n * commits of it's b-tree. These mutations can have reads\n * in them and those reads must be run against the IVM sources.\n *\n * To ensure the reads get the correct state, the IVM\n * sources need to reflect the state of the commit\n * being rebased onto. `IVMSourceBranch` allows us to:\n * 1. fork the IVM sources\n * 2. patch them up to match the desired head\n * 3. run the reads against the forked sources\n *\n * (2) is expected to be a cheap operation as there should only\n * ever be a few outstanding diffs to apply given Zero is meant\n * to be run in a connected state.\n */\nexport class IVMSourceBranch {\n readonly #sources: Map<string, MemorySource | undefined>;\n readonly #tables: Record<string, TableSchema>;\n #advanceError: unknown;\n hash: Hash | undefined;\n\n constructor(\n tables: Record<string, TableSchema>,\n hash?: Hash,\n sources: Map<string, MemorySource | undefined> = new Map(),\n ) {\n this.#tables = tables;\n this.#sources = sources;\n this.hash = hash;\n }\n\n getSource(name: string): MemorySource | undefined {\n this.#throwIfInvalid();\n\n if (this.#sources.has(name)) {\n return this.#sources.get(name);\n }\n\n const schema = this.#tables[name];\n const source = schema\n ? new MemorySource(name, schema.columns, schema.primaryKey)\n : undefined;\n this.#sources.set(name, source);\n return source;\n }\n\n clear() {\n this.#sources.clear();\n }\n\n #throwIfInvalid() {\n if (this.#advanceError) {\n throw this.#advanceError;\n }\n }\n\n /**\n * Mutates the current branch, advancing it to the new head\n * by applying the given diffs.\n */\n advance(expectedHead: Hash | undefined, newHead: Hash, diffs: NoIndexDiff) {\n this.#throwIfInvalid();\n\n assert(\n this.hash === expectedHead,\n () =>\n `Expected head must match the main head. Got: ${this.hash}, expected: ${expectedHead}`,\n );\n\n try {\n applyDiffs(diffs, this);\n this.hash = newHead;\n } catch (e) {\n this.#advanceError = e;\n this.clear();\n throw e;\n }\n }\n\n /**\n * Fork the branch and patch it up to match the desired head.\n */\n async forkToHead(\n store: LazyStore,\n desiredHead: Hash,\n readOptions?: ZeroReadOptions,\n ): Promise<IVMSourceBranch> {\n this.#throwIfInvalid();\n\n const fork = this.fork();\n\n if (fork.hash === desiredHead) {\n return fork;\n }\n\n await patchBranch(desiredHead, store, fork, readOptions);\n fork.hash = desiredHead;\n return fork;\n }\n\n /**\n * Creates a new IVMSourceBranch that is a copy of the current one.\n * This is a cheap operation since the b-trees are shared until a write is performed\n * and then only the modified nodes are copied.\n *\n * IVM branches are forked when we need to rebase mutations.\n * The mutations modify the fork rather than original branch.\n */\n fork() {\n this.#throwIfInvalid();\n\n return new IVMSourceBranch(\n this.#tables,\n this.hash,\n new Map(\n wrapIterable(this.#sources.entries()).map(([name, source]) => [\n name,\n source?.fork(),\n ]),\n ),\n );\n }\n}\n\nexport async function initFromStore(\n branch: IVMSourceBranch,\n hash: Hash,\n store: Store,\n) {\n const diffs: InternalDiffOperation[] = [];\n await withRead(store, async dagRead => {\n const read = await readFromHash(hash, dagRead, FormatVersion.Latest);\n for await (const entry of read.map.scan(ENTITIES_KEY_PREFIX)) {\n if (!entry[0].startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n diffs.push({\n op: 'add',\n key: entry[0],\n newValue: entry[1],\n });\n }\n });\n\n branch.advance(undefined, hash, diffs);\n}\n\nasync function patchBranch(\n desiredHead: Hash,\n store: LazyStore,\n fork: IVMSourceBranch,\n readOptions: ZeroReadOptions | undefined,\n) {\n const diffs = await computeDiffs(\n must(fork.hash),\n desiredHead,\n store,\n readOptions,\n );\n if (!diffs) {\n return;\n }\n applyDiffs(diffs, fork);\n}\n\nasync function computeDiffs(\n startHash: Hash,\n endHash: Hash,\n store: LazyStore,\n readOptions: ZeroReadOptions | undefined,\n): Promise<InternalDiff | undefined> {\n const readFn = (dagRead: Read) =>\n diff(\n startHash,\n endHash,\n dagRead,\n {\n shouldComputeDiffs: () => true,\n shouldComputeDiffsForIndex(_name) {\n return false;\n },\n },\n FormatVersion.Latest,\n );\n\n let diffs: DiffsMap;\n if (readOptions?.openLazySourceRead) {\n diffs = await using(store.read(readOptions.openLazySourceRead), readFn);\n } else if (readOptions?.openLazyRead) {\n diffs = await readFn(readOptions.openLazyRead);\n } else {\n diffs = await withRead(store, readFn);\n }\n\n return diffs.get('');\n}\n\nfunction applyDiffs(diffs: NoIndexDiff, branch: IVMSourceBranch) {\n for (\n let i = diffBinarySearch(diffs, ENTITIES_KEY_PREFIX, diff => diff.key);\n i < diffs.length;\n i++\n ) {\n const diff = diffs[i];\n const {key} = diff;\n if (!key.startsWith(ENTITIES_KEY_PREFIX)) {\n break;\n }\n const name = sourceNameFromKey(key);\n const source = must(branch.getSource(name));\n switch (diff.op) {\n case 'del':\n consume(source.push(makeSourceChangeRemove(diff.oldValue as Row)));\n break;\n case 'add':\n consume(source.push(makeSourceChangeAdd(diff.newValue as Row)));\n break;\n case 'change':\n consume(\n source.push(\n makeSourceChangeEdit(diff.newValue as Row, diff.oldValue as Row),\n ),\n );\n break;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,kBAAb,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CAEA,YACE,QACA,MACA,0BAAiD,IAAI,IAAI,GACzD;EACA,KAAKC,UAAU;EACf,KAAKD,WAAW;EAChB,KAAK,OAAO;CACd;CAEA,UAAU,MAAwC;EAChD,KAAKE,gBAAgB;EAErB,IAAI,KAAKF,SAAS,IAAI,IAAI,GACxB,OAAO,KAAKA,SAAS,IAAI,IAAI;EAG/B,MAAM,SAAS,KAAKC,QAAQ;EAC5B,MAAM,SAAS,SACX,IAAI,aAAa,MAAM,OAAO,SAAS,OAAO,UAAU,IACxD,KAAA;EACJ,KAAKD,SAAS,IAAI,MAAM,MAAM;EAC9B,OAAO;CACT;CAEA,QAAQ;EACN,KAAKA,SAAS,MAAM;CACtB;CAEA,kBAAkB;EAChB,IAAI,KAAKG,eACP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AAS,WAAW,OAAoB,QAAyB;CAC/D,KACE,IAAI,IAAI,iBAAiB,OAAA,OAA4B,SAAQ,KAAK,GAAG,GACrE,IAAI,MAAM,QACV,KACA;EACA,MAAM,OAAO,MAAM;EACnB,MAAM,EAAC,QAAO;EACd,IAAI,CAAC,IAAI,WAAA,IAA8B,GACrC;EAEF,MAAM,OAAO,kBAAkB,GAAG;EAClC,MAAM,SAAS,KAAK,OAAO,UAAU,IAAI,CAAC;EAC1C,QAAQ,KAAK,IAAb;GACE,KAAK;IACH,QAAQ,OAAO,KAAK,uBAAuB,KAAK,QAAe,CAAC,CAAC;IACjE;GACF,KAAK;IACH,QAAQ,OAAO,KAAK,oBAAoB,KAAK,QAAe,CAAC,CAAC;IAC9D;GACF,KAAK;IACH,QACE,OAAO,KACL,qBAAqB,KAAK,UAAiB,KAAK,QAAe,CACjE,CACF;IACA;EACJ;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutation-tracker.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/mutation-tracker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAGjD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,iCAAiC,CAAC;AACpE,OAAO,KAAK,EACV,WAAW,EACX,oBAAoB,EACrB,MAAM,+CAA+C,CAAC;AAevD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,2CAA2C,CAAC;AAM1E,OAAO,KAAK,EAGV,gBAAgB,EACjB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAc,KAAK,SAAS,EAAC,MAAM,YAAY,CAAC;AAGvD,KAAK,mBAAmB,GAAG,2BAA2B,CAAC;AAUvD;;GAEG;AACH,qBAAa,eAAe;;gBAoBxB,EAAE,EAAE,UAAU,EACd,YAAY,EAAE,CAAC,IAAI,EAAE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,mBAAmB,CAAC;IAexD,aAAa,IAAI,oBAAoB,CAAC,mBAAmB,CAAC;IAU1D,kBAAkB,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI;IAY7D;;;OAGG;IACH,cAAc,CAAC,EAAE,EAAE,WAAW,EAAE,CAAC,EAAE,OAAO,GAAG,IAAI;IAOjD;;;OAGG;IACH,6BAA6B,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IA0DrD,mBAAmB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI;IAuDrD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,WAAW,CAAC,cAAc,EAAE,MAAM;IAIlC;;;;;;OAMG;IACH,YAAY,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IAoB1C,IAAI,IAAI,WAEP;IAwJD;;;;;;;;;OASG;IACH,qBAAqB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;CASlD"}
|
|
@@ -98,7 +98,7 @@ var MutationTracker = class {
|
|
|
98
98
|
largestLmid = Math.max(largestLmid, mutationID);
|
|
99
99
|
switch (diff.op) {
|
|
100
100
|
case "add": {
|
|
101
|
-
const result = parse(diff.newValue, mutationResultSchema);
|
|
101
|
+
const result = parse(diff.newValue, mutationResultSchema, "passthrough");
|
|
102
102
|
if ("error" in result) this.#processMutationError(clientID, mutationID, result);
|
|
103
103
|
else this.#processMutationOk(clientID, mutationID, result);
|
|
104
104
|
break;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutation-tracker.js","names":["#outstandingMutations","#ephemeralIDsByMutationID","#allMutationsAppliedListeners","#lc","#ackMutations","#onFatalError","#largestOutstandingMutationID","#currentMutationID","#clientID","#processMutationResponses","#settleMutation","#notifyAllMutationsAppliedListeners","#processMutationError","#processMutationOk","#fatalErrorFromPushError","#processPushOk","#resolveMutations"],"sources":["../../../../../zero-client/src/client/mutation-tracker.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport type {NoIndexDiff} from '../../../replicache/src/btree/node.ts';\nimport type {ReplicacheImpl} from '../../../replicache/src/impl.ts';\nimport type {\n EphemeralID,\n MutationTrackingData,\n} from '../../../replicache/src/replicache-options.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorDetails} from '../../../shared/src/error.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {emptyObject} from '../../../shared/src/sentinels.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {\n ApplicationError,\n isApplicationError,\n wrapWithApplicationError,\n} from '../../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {MutationID} from '../../../zero-protocol/src/mutation-id.ts';\nimport {\n mutationResultSchema,\n type MutationError,\n type MutationOk,\n} from '../../../zero-protocol/src/mutation.ts';\nimport type {\n PushError,\n PushOk,\n PushResponseBody,\n} from '../../../zero-protocol/src/push.ts';\nimport type {MutatorResultSuccessDetails} from './custom.ts';\nimport {isZeroError, type ZeroError} from './error.ts';\nimport {MUTATIONS_KEY_PREFIX} from './keys.ts';\n\ntype MutationSuccessType = MutatorResultSuccessDetails;\ntype MutationErrorType = ApplicationError | ZeroError;\n\nlet currentEphemeralID = 0;\nfunction nextEphemeralID(): EphemeralID {\n return ++currentEphemeralID as EphemeralID;\n}\n\nconst successResultDetails: MutationSuccessType = {type: 'success'};\n\n/**\n * Tracks what pushes are in-flight and resolves promises when they're acked.\n */\nexport class MutationTracker {\n readonly #outstandingMutations: Map<\n EphemeralID,\n {\n mutationID?: number | undefined;\n resolver: Resolver<MutationSuccessType, MutationErrorType>;\n }\n >;\n readonly #ephemeralIDsByMutationID: Map<number, EphemeralID>;\n readonly #allMutationsAppliedListeners: Set<() => void>;\n readonly #lc: LogContext;\n\n readonly #ackMutations: (upTo: MutationID) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n\n #clientID: string | undefined;\n #largestOutstandingMutationID: number;\n #currentMutationID: number;\n\n constructor(\n lc: LogContext,\n ackMutations: (upTo: MutationID) => void,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('MutationTracker');\n this.#outstandingMutations = new Map();\n this.#ephemeralIDsByMutationID = new Map();\n this.#allMutationsAppliedListeners = new Set();\n this.#largestOutstandingMutationID = 0;\n this.#currentMutationID = 0;\n this.#ackMutations = ackMutations;\n this.#onFatalError = onFatalError;\n }\n\n setClientIDAndWatch(\n clientID: string,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n ) {\n assert(this.#clientID === undefined, 'clientID already set');\n this.#clientID = clientID;\n experimentalWatch(\n diffs => {\n this.#processMutationResponses(diffs);\n },\n {\n prefix: MUTATIONS_KEY_PREFIX + clientID + '/',\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n trackMutation(): MutationTrackingData<MutationSuccessType> {\n const id = nextEphemeralID();\n const mutationResolver = resolver<MutationSuccessType, MutationErrorType>();\n\n this.#outstandingMutations.set(id, {\n resolver: mutationResolver,\n });\n return {ephemeralID: id, serverPromise: mutationResolver.promise};\n }\n\n mutationIDAssigned(id: EphemeralID, mutationID: number): void {\n const entry = this.#outstandingMutations.get(id);\n if (entry) {\n entry.mutationID = mutationID;\n this.#ephemeralIDsByMutationID.set(mutationID, id);\n this.#largestOutstandingMutationID = Math.max(\n this.#largestOutstandingMutationID,\n mutationID,\n );\n }\n }\n\n /**\n * Reject the mutation due to an unhandled exception on the client.\n * The mutation must not have been persisted to the client store.\n */\n rejectMutation(id: EphemeralID, e: unknown): void {\n const entry = this.#outstandingMutations.get(id);\n if (entry) {\n this.#settleMutation(id, entry, wrapWithApplicationError(e));\n }\n }\n\n /**\n * Reject all outstanding mutations. Called when the client is in a state\n * that prevents mutations from being applied, such as offline or closed.\n */\n rejectAllOutstandingMutations(error: ZeroError): void {\n if (this.#outstandingMutations.size === 0) {\n return;\n }\n for (const [id, entry] of this.#outstandingMutations) {\n this.#settleMutation(id, entry, error);\n }\n this.#largestOutstandingMutationID = this.#currentMutationID;\n this.#notifyAllMutationsAppliedListeners();\n }\n\n /**\n * Used when zero-cache pokes down mutation results.\n */\n #processMutationResponses(diffs: NoIndexDiff): void {\n const clientID = must(this.#clientID);\n let largestLmid = 0;\n for (const diff of diffs) {\n const mutationID = Number(\n diff.key.slice(MUTATIONS_KEY_PREFIX.length + clientID.length + 1),\n );\n assert(\n !isNaN(mutationID),\n `MutationTracker received a diff with an invalid mutation ID: ${diff.key}`,\n );\n largestLmid = Math.max(largestLmid, mutationID);\n switch (diff.op) {\n case 'add': {\n const result = v.parse(diff.newValue, mutationResultSchema);\n if ('error' in result) {\n this.#processMutationError(clientID, mutationID, result);\n } else {\n this.#processMutationOk(clientID, mutationID, result);\n }\n break;\n }\n case 'del':\n break;\n case 'change':\n throw new Error('MutationTracker does not expect change operations');\n }\n }\n\n if (largestLmid > 0) {\n this.#ackMutations({\n clientID: must(this.#clientID),\n id: largestLmid,\n });\n }\n }\n\n processPushResponse(response: PushResponseBody): void {\n if ('error' in response) {\n this.#lc.error?.(\n 'Received an error response when pushing mutations',\n response,\n );\n const fatalError = this.#fatalErrorFromPushError(response);\n if (fatalError) {\n this.#onFatalError(fatalError);\n }\n } else {\n this.#processPushOk(response);\n }\n }\n\n #fatalErrorFromPushError(error: PushError): ZeroError | undefined {\n switch (error.error) {\n case 'unsupportedPushVersion':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unsupported push version`,\n mutationIDs: [],\n });\n case 'unsupportedSchemaVersion':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unsupported schema version`,\n mutationIDs: [],\n });\n case 'http':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: error.status,\n message: `Fetch from API server returned non-OK status ${error.status}: ${error.details ?? 'unknown'}`,\n mutationIDs: [],\n });\n case 'zeroPusher':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `ZeroPusher error: ${error.details ?? 'unknown'}`,\n mutationIDs: [],\n });\n default:\n unreachable(error);\n }\n }\n\n /**\n * DEPRECATED: to be removed when we switch to fully driving\n * mutation resolution via poke.\n *\n * When we reconnect to zero-cache, we resolve all outstanding mutations\n * whose ID is less than or equal to the lastMutationID.\n *\n * The reason is that any responses the API server sent\n * to those mutations have been lost.\n *\n * An example case: the API server responds while the connection\n * is down. Those responses are lost.\n *\n * Mutations whose LMID is > the lastMutationID are not resolved\n * since they will be retried by the client, giving us another chance\n * at getting a response.\n *\n * The only way to ensure that all API server responses are\n * received would be to have the API server write them\n * to the DB while writing the LMID.\n */\n onConnected(lastMutationID: number) {\n this.lmidAdvanced(lastMutationID);\n }\n\n /**\n * lmid advance will:\n * 1. notify \"allMutationsApplied\" listeners if the lastMutationID\n * is greater than or equal to the largest outstanding mutation ID.\n * 2. resolve all mutations whose mutation ID is less than or equal to\n * the lastMutationID.\n */\n lmidAdvanced(lastMutationID: number): void {\n assert(\n lastMutationID >= this.#currentMutationID,\n 'lmid must be greater than or equal to current lmid',\n );\n if (lastMutationID === this.#currentMutationID) {\n return;\n }\n\n try {\n this.#currentMutationID = lastMutationID;\n this.#resolveMutations(lastMutationID);\n } finally {\n if (lastMutationID >= this.#largestOutstandingMutationID) {\n // this is very important otherwise we hang query de-registration\n this.#notifyAllMutationsAppliedListeners();\n }\n }\n }\n\n get size() {\n return this.#outstandingMutations.size;\n }\n\n #resolveMutations(upTo: number): void {\n // We resolve all mutations whose mutation ID is less than or equal to\n // the upTo mutation ID.\n for (const [id, entry] of this.#outstandingMutations) {\n if (entry.mutationID && entry.mutationID <= upTo) {\n this.#settleMutation(id, entry, emptyObject);\n } else {\n break; // the map is in insertion order which is in mutation ID order\n }\n }\n }\n\n #processPushOk(success: PushOk): void {\n for (const mutation of success.mutations) {\n if ('error' in mutation.result) {\n this.#processMutationError(\n mutation.id.clientID,\n mutation.id.id,\n mutation.result,\n );\n } else {\n this.#processMutationOk(\n mutation.id.clientID,\n mutation.id.id,\n mutation.result,\n );\n }\n }\n }\n\n #processMutationError(\n clientID: string,\n mid: number,\n error: MutationError | Omit<PushError, 'mutationIDs'>,\n ): void {\n assert(\n clientID === this.#clientID,\n 'received mutation for the wrong client',\n );\n\n // Each tab sends all mutations for the client group\n // and the server responds back to the individual client that actually\n // ran the mutation. This means that N clients can send the same\n // mutation concurrently. If that happens, the promise for the mutation tracked\n // by this class will try to be resolved N times.\n // Every time after the first, the ephemeral ID will not be found.\n //\n // We also reject all outstanding mutations when the client is in a state\n // that prevents mutations from being applied, such as offline or closed.\n // In this case, the ephemeral ID will also not be found.\n const ephemeralID = this.#ephemeralIDsByMutationID.get(mid);\n if (!ephemeralID) {\n this.#lc.debug?.(\n 'Mutation already resolved or rejected (e.g. due to disconnect); ignore late reject.',\n );\n return;\n }\n\n const entry = this.#outstandingMutations.get(ephemeralID);\n assert(\n entry && entry.mutationID === mid,\n `outstanding mutation not found for mutation ID ${mid} and ephemeral ID ${ephemeralID}`,\n );\n\n if (error.error === 'alreadyProcessed') {\n this.#settleMutation(ephemeralID, entry, emptyObject);\n return;\n }\n\n this.#settleMutation(\n ephemeralID,\n entry,\n error.error === 'app'\n ? new ApplicationError(\n error.message ?? `Unknown application error: ${error.error}`,\n error.details ? {details: error.details} : undefined,\n )\n : new ProtocolError({\n kind: ErrorKind.InvalidPush,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message:\n error.error === 'oooMutation'\n ? 'Server reported an out-of-order mutation'\n : `Unknown fallback error with mutation ID ${mid}: ${error.error}`,\n details: getErrorDetails(error),\n }),\n );\n\n // this is included for backwards compatibility with the per-mutation fatal error responses\n if (error.error === 'oooMutation') {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.InvalidPush,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message: 'Server reported an out-of-order mutation',\n details: error.details,\n }),\n );\n }\n }\n\n #processMutationOk(clientID: string, mid: number, result: MutationOk): void {\n assert(\n clientID === this.#clientID,\n 'received mutation for the wrong client',\n );\n\n // We reject all outstanding mutations when the client is in a state\n // that prevents mutations from being applied, such as offline or closed.\n // In this case, the ephemeral ID will not be found.\n const ephemeralID = this.#ephemeralIDsByMutationID.get(mid);\n if (!ephemeralID) {\n this.#lc.debug?.(\n 'Mutation already resolved or rejected (e.g. due to disconnect); ignore late resolve.',\n );\n return;\n }\n\n const entry = this.#outstandingMutations.get(ephemeralID);\n assert(\n entry && entry.mutationID === mid,\n `outstanding mutation not found for mutation ID ${mid} and ephemeral ID ${ephemeralID}`,\n );\n this.#settleMutation(ephemeralID, entry, result);\n }\n\n #settleMutation<Result extends MutationOk | ApplicationError | ZeroError>(\n ephemeralID: EphemeralID,\n entry: {\n mutationID?: number | undefined;\n resolver: Resolver<MutationSuccessType, MutationErrorType>;\n },\n result: Result,\n ): void {\n if (isApplicationError(result) || isZeroError(result)) {\n // we reject here and catch in the mutator proxy\n // the mutator proxy catches both client and server errors\n entry.resolver.reject(result);\n } else {\n entry.resolver.resolve(successResultDetails);\n }\n\n this.#outstandingMutations.delete(ephemeralID);\n if (entry.mutationID) {\n this.#ephemeralIDsByMutationID.delete(entry.mutationID);\n }\n }\n\n /**\n * Be notified when all mutations have been included in the server snapshot.\n *\n * The query manager will not de-register queries from the server until there\n * are no pending mutations.\n *\n * The reason is that a mutation may need to be rebased. We do not want\n * data that was available the first time it was run to not be available\n * on a rebase.\n */\n onAllMutationsApplied(listener: () => void): void {\n this.#allMutationsAppliedListeners.add(listener);\n }\n\n #notifyAllMutationsAppliedListeners() {\n for (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SAAS,QAAQ,oBAAoB;EAG7C,KAAKV,sBAAsB,OAAO,WAAW;EAC7C,IAAI,MAAM,YACR,KAAKC,0BAA0B,OAAO,MAAM,UAAU;CAE1D;;;;;;;;;;;CAYA,sBAAsB,UAA4B;EAChD,KAAKC,8BAA8B,IAAI,QAAQ;CACjD;CAEA,sCAAsC;EACpC,KAAK,MAAM,YAAY,KAAKA,+BAC1B,SAAS;CAEb;AACF"}
|
|
1
|
+
{"version":3,"file":"mutation-tracker.js","names":["#outstandingMutations","#ephemeralIDsByMutationID","#allMutationsAppliedListeners","#lc","#ackMutations","#onFatalError","#largestOutstandingMutationID","#currentMutationID","#clientID","#processMutationResponses","#settleMutation","#notifyAllMutationsAppliedListeners","#processMutationError","#processMutationOk","#fatalErrorFromPushError","#processPushOk","#resolveMutations"],"sources":["../../../../../zero-client/src/client/mutation-tracker.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {resolver, type Resolver} from '@rocicorp/resolver';\nimport type {NoIndexDiff} from '../../../replicache/src/btree/node.ts';\nimport type {ReplicacheImpl} from '../../../replicache/src/impl.ts';\nimport type {\n EphemeralID,\n MutationTrackingData,\n} from '../../../replicache/src/replicache-options.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorDetails} from '../../../shared/src/error.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {emptyObject} from '../../../shared/src/sentinels.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport {\n ApplicationError,\n isApplicationError,\n wrapWithApplicationError,\n} from '../../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {MutationID} from '../../../zero-protocol/src/mutation-id.ts';\nimport {\n mutationResultSchema,\n type MutationError,\n type MutationOk,\n} from '../../../zero-protocol/src/mutation.ts';\nimport type {\n PushError,\n PushOk,\n PushResponseBody,\n} from '../../../zero-protocol/src/push.ts';\nimport type {MutatorResultSuccessDetails} from './custom.ts';\nimport {isZeroError, type ZeroError} from './error.ts';\nimport {MUTATIONS_KEY_PREFIX} from './keys.ts';\n\ntype MutationSuccessType = MutatorResultSuccessDetails;\ntype MutationErrorType = ApplicationError | ZeroError;\n\nlet currentEphemeralID = 0;\nfunction nextEphemeralID(): EphemeralID {\n return ++currentEphemeralID as EphemeralID;\n}\n\nconst successResultDetails: MutationSuccessType = {type: 'success'};\n\n/**\n * Tracks what pushes are in-flight and resolves promises when they're acked.\n */\nexport class MutationTracker {\n readonly #outstandingMutations: Map<\n EphemeralID,\n {\n mutationID?: number | undefined;\n resolver: Resolver<MutationSuccessType, MutationErrorType>;\n }\n >;\n readonly #ephemeralIDsByMutationID: Map<number, EphemeralID>;\n readonly #allMutationsAppliedListeners: Set<() => void>;\n readonly #lc: LogContext;\n\n readonly #ackMutations: (upTo: MutationID) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n\n #clientID: string | undefined;\n #largestOutstandingMutationID: number;\n #currentMutationID: number;\n\n constructor(\n lc: LogContext,\n ackMutations: (upTo: MutationID) => void,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('MutationTracker');\n this.#outstandingMutations = new Map();\n this.#ephemeralIDsByMutationID = new Map();\n this.#allMutationsAppliedListeners = new Set();\n this.#largestOutstandingMutationID = 0;\n this.#currentMutationID = 0;\n this.#ackMutations = ackMutations;\n this.#onFatalError = onFatalError;\n }\n\n setClientIDAndWatch(\n clientID: string,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n ) {\n assert(this.#clientID === undefined, 'clientID already set');\n this.#clientID = clientID;\n experimentalWatch(\n diffs => {\n this.#processMutationResponses(diffs);\n },\n {\n prefix: MUTATIONS_KEY_PREFIX + clientID + '/',\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n trackMutation(): MutationTrackingData<MutationSuccessType> {\n const id = nextEphemeralID();\n const mutationResolver = resolver<MutationSuccessType, MutationErrorType>();\n\n this.#outstandingMutations.set(id, {\n resolver: mutationResolver,\n });\n return {ephemeralID: id, serverPromise: mutationResolver.promise};\n }\n\n mutationIDAssigned(id: EphemeralID, mutationID: number): void {\n const entry = this.#outstandingMutations.get(id);\n if (entry) {\n entry.mutationID = mutationID;\n this.#ephemeralIDsByMutationID.set(mutationID, id);\n this.#largestOutstandingMutationID = Math.max(\n this.#largestOutstandingMutationID,\n mutationID,\n );\n }\n }\n\n /**\n * Reject the mutation due to an unhandled exception on the client.\n * The mutation must not have been persisted to the client store.\n */\n rejectMutation(id: EphemeralID, e: unknown): void {\n const entry = this.#outstandingMutations.get(id);\n if (entry) {\n this.#settleMutation(id, entry, wrapWithApplicationError(e));\n }\n }\n\n /**\n * Reject all outstanding mutations. Called when the client is in a state\n * that prevents mutations from being applied, such as offline or closed.\n */\n rejectAllOutstandingMutations(error: ZeroError): void {\n if (this.#outstandingMutations.size === 0) {\n return;\n }\n for (const [id, entry] of this.#outstandingMutations) {\n this.#settleMutation(id, entry, error);\n }\n this.#largestOutstandingMutationID = this.#currentMutationID;\n this.#notifyAllMutationsAppliedListeners();\n }\n\n /**\n * Used when zero-cache pokes down mutation results.\n */\n #processMutationResponses(diffs: NoIndexDiff): void {\n const clientID = must(this.#clientID);\n let largestLmid = 0;\n for (const diff of diffs) {\n const mutationID = Number(\n diff.key.slice(MUTATIONS_KEY_PREFIX.length + clientID.length + 1),\n );\n assert(\n !isNaN(mutationID),\n `MutationTracker received a diff with an invalid mutation ID: ${diff.key}`,\n );\n largestLmid = Math.max(largestLmid, mutationID);\n switch (diff.op) {\n case 'add': {\n // Results are stored as the server sent them, so a newer server can\n // add fields. Don't use 'strip': mutationResultSchema's OK branch\n // has no discriminator, so it would turn every error into `{}`.\n const result = v.parse(\n diff.newValue,\n mutationResultSchema,\n 'passthrough',\n );\n if ('error' in result) {\n this.#processMutationError(clientID, mutationID, result);\n } else {\n this.#processMutationOk(clientID, mutationID, result);\n }\n break;\n }\n case 'del':\n break;\n case 'change':\n throw new Error('MutationTracker does not expect change operations');\n }\n }\n\n if (largestLmid > 0) {\n this.#ackMutations({\n clientID: must(this.#clientID),\n id: largestLmid,\n });\n }\n }\n\n processPushResponse(response: PushResponseBody): void {\n if ('error' in response) {\n this.#lc.error?.(\n 'Received an error response when pushing mutations',\n response,\n );\n const fatalError = this.#fatalErrorFromPushError(response);\n if (fatalError) {\n this.#onFatalError(fatalError);\n }\n } else {\n this.#processPushOk(response);\n }\n }\n\n #fatalErrorFromPushError(error: PushError): ZeroError | undefined {\n switch (error.error) {\n case 'unsupportedPushVersion':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unsupported push version`,\n mutationIDs: [],\n });\n case 'unsupportedSchemaVersion':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unsupported schema version`,\n mutationIDs: [],\n });\n case 'http':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.HTTP,\n status: error.status,\n message: `Fetch from API server returned non-OK status ${error.status}: ${error.details ?? 'unknown'}`,\n mutationIDs: [],\n });\n case 'zeroPusher':\n return new ProtocolError({\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `ZeroPusher error: ${error.details ?? 'unknown'}`,\n mutationIDs: [],\n });\n default:\n unreachable(error);\n }\n }\n\n /**\n * DEPRECATED: to be removed when we switch to fully driving\n * mutation resolution via poke.\n *\n * When we reconnect to zero-cache, we resolve all outstanding mutations\n * whose ID is less than or equal to the lastMutationID.\n *\n * The reason is that any responses the API server sent\n * to those mutations have been lost.\n *\n * An example case: the API server responds while the connection\n * is down. Those responses are lost.\n *\n * Mutations whose LMID is > the lastMutationID are not resolved\n * since they will be retried by the client, giving us another chance\n * at getting a response.\n *\n * The only way to ensure that all API server responses are\n * received would be to have the API server write them\n * to the DB while writing the LMID.\n */\n onConnected(lastMutationID: number) {\n this.lmidAdvanced(lastMutationID);\n }\n\n /**\n * lmid advance will:\n * 1. notify \"allMutationsApplied\" listeners if the lastMutationID\n * is greater than or equal to the largest outstanding mutation ID.\n * 2. resolve all mutations whose mutation ID is less than or equal to\n * the lastMutationID.\n */\n lmidAdvanced(lastMutationID: number): void {\n assert(\n lastMutationID >= this.#currentMutationID,\n 'lmid must be greater than or equal to current lmid',\n );\n if (lastMutationID === this.#currentMutationID) {\n return;\n }\n\n try {\n this.#currentMutationID = lastMutationID;\n this.#resolveMutations(lastMutationID);\n } finally {\n if (lastMutationID >= this.#largestOutstandingMutationID) {\n // this is very important otherwise we hang query de-registration\n this.#notifyAllMutationsAppliedListeners();\n }\n }\n }\n\n get size() {\n return this.#outstandingMutations.size;\n }\n\n #resolveMutations(upTo: number): void {\n // We resolve all mutations whose mutation ID is less than or equal to\n // the upTo mutation ID.\n for (const [id, entry] of this.#outstandingMutations) {\n if (entry.mutationID && entry.mutationID <= upTo) {\n this.#settleMutation(id, entry, emptyObject);\n } else {\n break; // the map is in insertion order which is in mutation ID order\n }\n }\n }\n\n #processPushOk(success: PushOk): void {\n for (const mutation of success.mutations) {\n if ('error' in mutation.result) {\n this.#processMutationError(\n mutation.id.clientID,\n mutation.id.id,\n mutation.result,\n );\n } else {\n this.#processMutationOk(\n mutation.id.clientID,\n mutation.id.id,\n mutation.result,\n );\n }\n }\n }\n\n #processMutationError(\n clientID: string,\n mid: number,\n error: MutationError | Omit<PushError, 'mutationIDs'>,\n ): void {\n assert(\n clientID === this.#clientID,\n 'received mutation for the wrong client',\n );\n\n // Each tab sends all mutations for the client group\n // and the server responds back to the individual client that actually\n // ran the mutation. This means that N clients can send the same\n // mutation concurrently. If that happens, the promise for the mutation tracked\n // by this class will try to be resolved N times.\n // Every time after the first, the ephemeral ID will not be found.\n //\n // We also reject all outstanding mutations when the client is in a state\n // that prevents mutations from being applied, such as offline or closed.\n // In this case, the ephemeral ID will also not be found.\n const ephemeralID = this.#ephemeralIDsByMutationID.get(mid);\n if (!ephemeralID) {\n this.#lc.debug?.(\n 'Mutation already resolved or rejected (e.g. due to disconnect); ignore late reject.',\n );\n return;\n }\n\n const entry = this.#outstandingMutations.get(ephemeralID);\n assert(\n entry && entry.mutationID === mid,\n `outstanding mutation not found for mutation ID ${mid} and ephemeral ID ${ephemeralID}`,\n );\n\n if (error.error === 'alreadyProcessed') {\n this.#settleMutation(ephemeralID, entry, emptyObject);\n return;\n }\n\n this.#settleMutation(\n ephemeralID,\n entry,\n error.error === 'app'\n ? new ApplicationError(\n error.message ?? `Unknown application error: ${error.error}`,\n error.details ? {details: error.details} : undefined,\n )\n : new ProtocolError({\n kind: ErrorKind.InvalidPush,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message:\n error.error === 'oooMutation'\n ? 'Server reported an out-of-order mutation'\n : `Unknown fallback error with mutation ID ${mid}: ${error.error}`,\n details: getErrorDetails(error),\n }),\n );\n\n // this is included for backwards compatibility with the per-mutation fatal error responses\n if (error.error === 'oooMutation') {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.InvalidPush,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Internal,\n message: 'Server reported an out-of-order mutation',\n details: error.details,\n }),\n );\n }\n }\n\n #processMutationOk(clientID: string, mid: number, result: MutationOk): void {\n assert(\n clientID === this.#clientID,\n 'received mutation for the wrong client',\n );\n\n // We reject all outstanding mutations when the client is in a state\n // that prevents mutations from being applied, such as offline or closed.\n // In this case, the ephemeral ID will not be found.\n const ephemeralID = this.#ephemeralIDsByMutationID.get(mid);\n if (!ephemeralID) {\n this.#lc.debug?.(\n 'Mutation already resolved or rejected (e.g. due to disconnect); ignore late resolve.',\n );\n return;\n }\n\n const entry = this.#outstandingMutations.get(ephemeralID);\n assert(\n entry && entry.mutationID === mid,\n `outstanding mutation not found for mutation ID ${mid} and ephemeral ID ${ephemeralID}`,\n );\n this.#settleMutation(ephemeralID, entry, result);\n }\n\n #settleMutation<Result extends MutationOk | ApplicationError | ZeroError>(\n ephemeralID: EphemeralID,\n entry: {\n mutationID?: number | undefined;\n resolver: Resolver<MutationSuccessType, MutationErrorType>;\n },\n result: Result,\n ): void {\n if (isApplicationError(result) || isZeroError(result)) {\n // we reject here and catch in the mutator proxy\n // the mutator proxy catches both client and server errors\n entry.resolver.reject(result);\n } else {\n entry.resolver.resolve(successResultDetails);\n }\n\n this.#outstandingMutations.delete(ephemeralID);\n if (entry.mutationID) {\n this.#ephemeralIDsByMutationID.delete(entry.mutationID);\n }\n }\n\n /**\n * Be notified when all mutations have been included in the server snapshot.\n *\n * The query manager will not de-register queries from the server until there\n * are no pending mutations.\n *\n * The reason is that a mutation may need to be rebased. We do not want\n * data that was available the first time it was run to not be available\n * on a rebase.\n */\n onAllMutationsApplied(listener: () => void): void {\n this.#allMutationsAppliedListeners.add(listener);\n }\n\n #notifyAllMutationsAppliedListeners() {\n for (const listener of this.#allMutationsAppliedListeners) {\n listener();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,IAAI,qBAAqB;AACzB,SAAS,kBAA+B;CACtC,OAAO,EAAE;AACX;AAEA,IAAM,uBAA4C,EAAC,MAAM,UAAS;;;;AAKlE,IAAa,kBAAb,MAA6B;CAC3B;CAOA;CACA;CACA;CAEA;CACA;CAEA;CACA;CACA;CAEA,YACE,IACA,cACA,cACA;EACA,KAAKG,MAAM,GAAG,YAAY,iBAAiB;EAC3C,KAAKH,wCAAwB,IAAI,IAAI;EACrC,KAAKC,4CAA4B,IAAI,IAAI;EACzC,KAAKC,gDAAgC,IAAI,IAAI;EAC7C,KAAKI,gCAAgC;EACrC,KAAKC,qBAAqB;EAC1B,KAAKH,gBAAgB;EACrB,KAAKC,gBAAgB;CACvB;CAEA,oBACE,UACA,mBACA;EACA,OAAO,KAAKG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CACA,2CAA2C,IAAI,IAAI,MAAM;GAC/D,SAAS,gBAAgB,KAAK;EAChC,CAAC,CACP;EAGA,IAAI,MAAM,UAAU,eAClB,KAAKL,cACH,IAAI,cAAc;GAChB,MAAM;GACN,QAAQ;GACR,QAAQ;GACR,SAAS;GACT,SAAS,MAAM;EACjB,CAAC,CACH;CAEJ;CAEA,mBAAmB,UAAkB,KAAa,QAA0B;EAC1E,OACE,aAAa,KAAKG,WAClB,wCACF;EAKA,MAAM,cAAc,KAAKP,0BAA0B,IAAI,GAAG;EAC1D,IAAI,CAAC,aAAa;GAChB,KAAKE,IAAI,QACP,sFACF;GACA;EACF;EAEA,MAAM,QAAQ,KAAKH,sBAAsB,IAAI,WAAW;EACxD,OACE,SAAS,MAAM,eAAe,KAC9B,kDAAkD,IAAI,oBAAoB,aAC5E;EACA,KAAKU,gBAAgB,aAAa,OAAO,MAAM;CACjD;CAEA,gBACE,aACA,OAIA,QACM;EACN,IAAI,mBAAmB,MAAM,KAAK,YAAY,MAAM,GAGlD,MAAM,SAAS,OAAO,MAAM;OAE5B,MAAM,SAAS,QAAQ,oBAAoB;EAG7C,KAAKV,sBAAsB,OAAO,WAAW;EAC7C,IAAI,MAAM,YACR,KAAKC,0BAA0B,OAAO,MAAM,UAAU;CAE1D;;;;;;;;;;;CAYA,sBAAsB,UAA4B;EAChD,KAAKC,8BAA8B,IAAI,QAAQ;CACjD;CAEA,sCAAsC;EACpC,KAAK,MAAM,YAAY,KAAKA,+BAC1B,SAAS;CAEb;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator-proxy.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/mutator-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAInE,OAAO,KAAK,EACV,iBAAiB,EAElB,MAAM,yBAAyB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A4GjE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { unreachable } from "../../../shared/src/asserts.js";
|
|
2
2
|
import { wrapWithApplicationError } from "../../../zero-protocol/src/application-error.js";
|
|
3
|
-
import { Closed, Connected, Connecting, Disconnected, Error,
|
|
3
|
+
import { Closed, Connected, Connecting, Disconnected, Error, NeedsAuth } from "./connection-status-enum.js";
|
|
4
4
|
import { ClientClosed, Offline } from "./client-error-kind-enum.js";
|
|
5
5
|
import { isZeroError } from "./error.js";
|
|
6
6
|
//#region ../zero-client/src/client/mutator-proxy.ts
|
|
@@ -50,7 +50,6 @@ var MutatorProxy = class {
|
|
|
50
50
|
};
|
|
51
51
|
this.#mutationTracker.rejectAllOutstandingMutations(state.reason);
|
|
52
52
|
break;
|
|
53
|
-
case Initializing:
|
|
54
53
|
case Connected:
|
|
55
54
|
case Connecting:
|
|
56
55
|
case NeedsAuth:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator-proxy.js","names":["#lc","#connectionManager","#mutationTracker","#onConnectionStateChange","#mutationRejection","#makeZeroErrorResultDetails","#makeApplicationErrorResultDetails","#normalizeResultPromise"],"sources":["../../../../../zero-client/src/client/mutator-proxy.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport type {ApplicationError} from '../../../zero-protocol/src/application-error.ts';\nimport {wrapWithApplicationError} from '../../../zero-protocol/src/application-error.ts';\nimport {ClientErrorKind} from './client-error-kind.ts';\nimport type {\n ConnectionManager,\n ConnectionManagerState,\n} from './connection-manager.ts';\nimport {ConnectionStatus} from './connection-status.ts';\nimport type {\n MutatorResult,\n MutatorResultErrorDetails,\n MutatorResultSuccessDetails,\n} from './custom.ts';\nimport {isZeroError, type ZeroError} from './error.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\n\nconst successResultDetails = {\n type: 'success',\n} as const satisfies MutatorResultSuccessDetails;\nconst successResult = () => successResultDetails;\n\nfunction getStateDescription(error: ZeroError): string {\n switch (error.kind) {\n case ClientErrorKind.Offline:\n return 'offline';\n case ClientErrorKind.ClientClosed:\n return 'closed';\n default:\n return 'in error state';\n }\n}\n\ntype CachedMutationRejection = {\n readonly error: ZeroError;\n readonly promise: Promise<MutatorResultErrorDetails>;\n};\n\nexport class MutatorProxy {\n readonly #lc: LogContext;\n readonly #connectionManager: ConnectionManager;\n readonly #mutationTracker: MutationTracker;\n #mutationRejection: CachedMutationRejection | undefined;\n\n constructor(\n lc: LogContext,\n connectionManager: ConnectionManager,\n mutationTracker: MutationTracker,\n ) {\n this.#lc = lc;\n this.#connectionManager = connectionManager;\n this.#mutationTracker = mutationTracker;\n\n this.#connectionManager.subscribe(state =>\n this.#onConnectionStateChange(state),\n );\n this.#onConnectionStateChange(connectionManager.state);\n }\n\n get mutationRejectionError(): ZeroError | undefined {\n return this.#mutationRejection?.error;\n }\n\n /**\n * Called when the connection state changes.\n *\n * If the connection state is disconnected, error, or closed, the\n * mutation rejection error is set and all outstanding `.server` promises in\n * the mutation tracker are rejected with the error.\n */\n #onConnectionStateChange(state: ConnectionManagerState) {\n // we short circuit the rejection if the error is due to a missing cacheURL\n // this allows local writes to continue\n if (\n state.name === ConnectionStatus.Disconnected &&\n state.reason.kind === ClientErrorKind.NoSocketOrigin\n ) {\n this.#mutationRejection = undefined;\n return;\n }\n\n switch (state.name) {\n case ConnectionStatus.Disconnected:\n case ConnectionStatus.Error:\n case ConnectionStatus.Closed:\n this.#mutationRejection = {\n error: state.reason,\n promise: Promise.resolve(\n this.#makeZeroErrorResultDetails(state.reason),\n ),\n };\n this.#mutationTracker.rejectAllOutstandingMutations(state.reason);\n break;\n case ConnectionStatus.
|
|
1
|
+
{"version":3,"file":"mutator-proxy.js","names":["#lc","#connectionManager","#mutationTracker","#onConnectionStateChange","#mutationRejection","#makeZeroErrorResultDetails","#makeApplicationErrorResultDetails","#normalizeResultPromise"],"sources":["../../../../../zero-client/src/client/mutator-proxy.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport type {ApplicationError} from '../../../zero-protocol/src/application-error.ts';\nimport {wrapWithApplicationError} from '../../../zero-protocol/src/application-error.ts';\nimport {ClientErrorKind} from './client-error-kind.ts';\nimport type {\n ConnectionManager,\n ConnectionManagerState,\n} from './connection-manager.ts';\nimport {ConnectionStatus} from './connection-status.ts';\nimport type {\n MutatorResult,\n MutatorResultErrorDetails,\n MutatorResultSuccessDetails,\n} from './custom.ts';\nimport {isZeroError, type ZeroError} from './error.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\n\nconst successResultDetails = {\n type: 'success',\n} as const satisfies MutatorResultSuccessDetails;\nconst successResult = () => successResultDetails;\n\nfunction getStateDescription(error: ZeroError): string {\n switch (error.kind) {\n case ClientErrorKind.Offline:\n return 'offline';\n case ClientErrorKind.ClientClosed:\n return 'closed';\n default:\n return 'in error state';\n }\n}\n\ntype CachedMutationRejection = {\n readonly error: ZeroError;\n readonly promise: Promise<MutatorResultErrorDetails>;\n};\n\nexport class MutatorProxy {\n readonly #lc: LogContext;\n readonly #connectionManager: ConnectionManager;\n readonly #mutationTracker: MutationTracker;\n #mutationRejection: CachedMutationRejection | undefined;\n\n constructor(\n lc: LogContext,\n connectionManager: ConnectionManager,\n mutationTracker: MutationTracker,\n ) {\n this.#lc = lc;\n this.#connectionManager = connectionManager;\n this.#mutationTracker = mutationTracker;\n\n this.#connectionManager.subscribe(state =>\n this.#onConnectionStateChange(state),\n );\n this.#onConnectionStateChange(connectionManager.state);\n }\n\n get mutationRejectionError(): ZeroError | undefined {\n return this.#mutationRejection?.error;\n }\n\n /**\n * Called when the connection state changes.\n *\n * If the connection state is disconnected, error, or closed, the\n * mutation rejection error is set and all outstanding `.server` promises in\n * the mutation tracker are rejected with the error.\n */\n #onConnectionStateChange(state: ConnectionManagerState) {\n // we short circuit the rejection if the error is due to a missing cacheURL\n // this allows local writes to continue\n if (\n state.name === ConnectionStatus.Disconnected &&\n state.reason.kind === ClientErrorKind.NoSocketOrigin\n ) {\n this.#mutationRejection = undefined;\n return;\n }\n\n switch (state.name) {\n case ConnectionStatus.Disconnected:\n case ConnectionStatus.Error:\n case ConnectionStatus.Closed:\n this.#mutationRejection = {\n error: state.reason,\n promise: Promise.resolve(\n this.#makeZeroErrorResultDetails(state.reason),\n ),\n };\n this.#mutationTracker.rejectAllOutstandingMutations(state.reason);\n break;\n case ConnectionStatus.Connected:\n case ConnectionStatus.Connecting:\n case ConnectionStatus.NeedsAuth:\n this.#mutationRejection = undefined;\n return;\n default:\n unreachable(state);\n }\n }\n\n wrapCustomMutator<\n F extends (...args: [] | [ReadonlyJSONValue]) => {\n client: Promise<unknown>;\n server: Promise<unknown>;\n },\n >(name: string, f: F): (...args: Parameters<F>) => MutatorResult {\n return (...args) => {\n if (this.#mutationRejection) {\n const error = this.#mutationRejection.error;\n this.#lc.warn?.(\n `Mutation \"${name}\" rejected because Zero is ${getStateDescription(error)}. Details: ${error.message}. See also: https://zero.rocicorp.dev/docs/connection.`,\n );\n return {\n client: this.#mutationRejection.promise,\n server: this.#mutationRejection.promise,\n } as const satisfies MutatorResult;\n }\n\n let result: {\n client: Promise<unknown>;\n server: Promise<unknown>;\n };\n\n const cachedMutationPromises: Partial<\n Record<'client' | 'server', Promise<MutatorResultErrorDetails>>\n > = {};\n\n const wrapErrorFor =\n (origin: 'client' | 'server') =>\n (error: unknown): Promise<MutatorResultErrorDetails> => {\n const cachedPromise = cachedMutationPromises[origin];\n if (cachedPromise) {\n return cachedPromise;\n }\n\n if (isZeroError(error)) {\n this.#lc.error?.(`Mutator \"${name}\" error on ${origin}`, error);\n\n const zeroErrorPromise = this.#makeZeroErrorResultDetails(error);\n cachedMutationPromises[origin] = zeroErrorPromise;\n return zeroErrorPromise;\n }\n\n const applicationError = wrapWithApplicationError(error);\n this.#lc.error?.(\n `Mutator \"${name}\" app error on ${origin}`,\n applicationError,\n );\n\n const applicationErrorPromise =\n this.#makeApplicationErrorResultDetails(applicationError);\n cachedMutationPromises[origin] = applicationErrorPromise;\n return applicationErrorPromise;\n };\n\n try {\n result = f(...args);\n } catch (error) {\n const clientPromise = wrapErrorFor('client')(error);\n const serverPromise = wrapErrorFor('server')(error);\n\n return {\n client: clientPromise,\n server: serverPromise,\n } as const satisfies MutatorResult;\n }\n\n const client = this.#normalizeResultPromise(\n result.client,\n wrapErrorFor('client'),\n );\n const server = this.#normalizeResultPromise(\n result.server,\n wrapErrorFor('server'),\n );\n\n return {\n client,\n server,\n };\n };\n }\n\n #normalizeResultPromise(\n promise: Promise<unknown>,\n wrapError: (error: unknown) => Promise<MutatorResultErrorDetails>,\n ) {\n return promise.then<MutatorResultSuccessDetails, MutatorResultErrorDetails>(\n successResult,\n wrapError,\n );\n }\n\n #makeZeroErrorResultDetails(zeroError: ZeroError) {\n return Promise.resolve({\n type: 'error',\n error: {\n type: 'zero',\n message: zeroError.message,\n },\n } as const satisfies MutatorResultErrorDetails);\n }\n\n #makeApplicationErrorResultDetails(applicationError: ApplicationError) {\n return Promise.resolve({\n type: 'error',\n error: {\n type: 'app',\n message: applicationError.message,\n details: applicationError.details,\n },\n } as const satisfies MutatorResultErrorDetails);\n }\n}\n"],"mappings":";;;;;;AAmBA,IAAM,uBAAuB,EAC3B,MAAM,UACR;AACA,IAAM,sBAAsB;AAE5B,SAAS,oBAAoB,OAA0B;CACrD,QAAQ,MAAM,MAAd;EACE,KAAK,SACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAOA,IAAa,eAAb,MAA0B;CACxB;CACA;CACA;CACA;CAEA,YACE,IACA,mBACA,iBACA;EACA,KAAKA,MAAM;EACX,KAAKC,qBAAqB;EAC1B,KAAKC,mBAAmB;EAExB,KAAKD,mBAAmB,WAAU,UAChC,KAAKE,yBAAyB,KAAK,CACrC;EAC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;IAC1D,uBAAuB,UAAU;IACjC,OAAO;GACT;GAEF,IAAI;IACF,SAAS,EAAE,GAAG,IAAI;GACpB,SAAS,OAAO;IAId,OAAO;KACL,QAJoB,aAAa,QAAQ,EAAE,KAInC;KACR,QAJoB,aAAa,QAAQ,EAAE,KAInC;IACV;GACF;GAWA,OAAO;IACL,QAVa,KAAKC,wBAClB,OAAO,QACP,aAAa,QAAQ,CAQrB;IACA,QAPa,KAAKA,wBAClB,OAAO,QACP,aAAa,QAAQ,CAKrB;GACF;EACF;CACF;CAEA,wBACE,SACA,WACA;EACA,OAAO,QAAQ,KACb,eACA,SACF;CACF;CAEA,4BAA4B,WAAsB;EAChD,OAAO,QAAQ,QAAQ;GACrB,MAAM;GACN,OAAO;IACL,MAAM;IACN,SAAS,UAAU;GACrB;EACF,CAA8C;CAChD;CAEA,mCAAmC,kBAAoC;EACrE,OAAO,QAAQ,QAAQ;GACrB,MAAM;GACN,OAAO;IACL,MAAM;IACN,SAAS,iBAAiB;IAC1B,SAAS,iBAAiB;GAC5B;EACF,CAA8C;CAChD;AACF"}
|
|
@@ -213,9 +213,6 @@ export type ZeroOptions<S extends BaseDefaultSchema = DefaultSchema, MD extends
|
|
|
213
213
|
* - the local persistent synchronization state has been garbage collected.
|
|
214
214
|
* This can happen if the client has no pending mutations and has not been
|
|
215
215
|
* used for a while (e.g. the client's tab has been hidden for a long time).
|
|
216
|
-
* - the local persistent synchronization state was found to be corrupt.
|
|
217
|
-
* Replicache tries to drop the local database so that a reload starts
|
|
218
|
-
* fresh. The callback is called even if that fails.
|
|
219
216
|
* - zero-cache fails to find the server side synchronization state for
|
|
220
217
|
* this client.
|
|
221
218
|
* - zero-cache rejects this client's persisted synchronization state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAE,OAAO,EAAC,MAAM,kBAAkB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C,EAAE,MAAM,GAAG,SAAS,CAAC;IAE3C;;OAEG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC;CACzB,GAAG,CAAC,OAAO,SAAS,cAAc,GAC/B,EAAE,GACF;IACE,OAAO,EAAE,CAAC,CAAC;CACZ,CAAC,CAAC;AAEP;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAC7B,CAAC,SAAS,iBAAiB,EAC3B,EAAE,SAAS,iBAAiB,GAAG,SAAS,EACxC,OAAO,SAAS,kBAAkB,IAChC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;AAEhC,KAAK,sBAAsB,GAAG;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAC1B,CAAC;IAAC,IAAI,EAAE,sBAAsB,CAAC,cAAc,CAAA;CAAC,GAAG,sBAAsB,CAAC,GACxE,CAAC;IACC,IAAI,EAAE,sBAAsB,CAAC,mBAAmB,CAAC;CAClD,GAAG,sBAAsB,CAAC,GAC3B,CAAC;IACC,IAAI,EAAE,sBAAsB,CAAC,yBAAyB,CAAC;CACxD,GAAG,sBAAsB,CAAC,CAAC;AAEhC,eAAO,MAAM,4BAA4B,EAAE,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAKzE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel, LogSink} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * Destination for Zero's log output. When omitted, logs are written with\n * `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@linkcode LogSink} to redirect logs — for example, to\n * `process.stderr` in a CLI so that the tool's structured stdout output\n * isn't polluted by log lines.\n *\n * Note: this overrides only the console sink. When analytics logging is\n * enabled, the Datadog sink is still installed alongside this one.\n */\n logSink?: LogSink | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - the local persistent synchronization state was found to be corrupt.\n * Replicache tries to drop the local database so that a reload starts\n * fresh. The callback is called even if that fails.\n * - zero-cache fails to find the server side synchronization state for\n * this client.\n * - zero-cache rejects this client's persisted synchronization state,\n * requiring the local Replicache database to be reset.\n *\n * The current `Zero` instance should be treated as dead and replaced, not\n * reconnected.\n *\n * The default behavior for the Zero client is to reload the page\n * (using `location.reload()`). The React and SolidJS providers will replace\n * the client in-place, without a full page reload.\n *\n * Provide your own function to prevent this functionality.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AAkZA,IAAa,+BACX,aACE,gBACA,qBACA,yBACF"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../../../../zero-client/src/client/options.ts"],"sourcesContent":["import type {LogLevel, LogSink} from '@rocicorp/logger';\nimport type {StoreProvider} from '../../../replicache/src/kv/store.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {\n BaseDefaultContext,\n BaseDefaultSchema,\n DefaultContext,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {AnyMutatorRegistry} from '../../../zql/src/mutate/mutator-registry.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\nimport {UpdateNeededReasonType} from './update-needed-reason-type.ts';\n\n/**\n * Configuration for {@linkcode Zero}.\n */\nexport type ZeroOptions<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n C extends BaseDefaultContext = DefaultContext,\n> = {\n /**\n * URL to the zero-cache. This can be a simple hostname, e.g.\n * - \"https://myapp-myteam.zero.ms\"\n * or a prefix with a single path component, e.g.\n * - \"https://myapp-myteam.zero.ms/zero\"\n * - \"https://myapp-myteam.zero.ms/db\"\n *\n * The latter is useful for configuring routing rules (e.g. \"/zero/\\*\") when\n * the zero-cache is hosted on the same domain as the application. **Note that\n * only a single path segment is allowed (e.g. it cannot be \"/proxy/zero/\\*\")**.\n */\n cacheURL?: string | null | undefined;\n\n /**\n * @deprecated Use {@linkcode cacheURL} instead.\n */\n server?: string | null | undefined;\n\n /**\n * A token to identify and authenticate the user.\n *\n * Set `auth` to `null` or `undefined` if there is no logged in user.\n *\n * The call to `connect` is handled automatically by the ZeroProvider component\n * for React and SolidJS when the `auth` prop changes.\n *\n * Transitions between authenticated and logged-out states recreate the Zero\n * instance instead.\n *\n * When `auth` changes while connected, Zero refreshes server-side auth context\n * and re-transforms queries without reconnecting.\n *\n * When a 401 or 403 HTTP status code is received from your server, Zero will\n * transition to the `needs-auth` connection state. The app should call\n * `zero.connection.connect({auth: newToken})` with a new token to reconnect.\n */\n auth?: string | null | undefined;\n\n /**\n * A unique identifier for the user.\n *\n * Omit this, or set to `null`, for logged-out clients.\n *\n * Each userID gets its own client-side storage so that the app can switch\n * between users without losing state.\n */\n userID?: string | null | undefined;\n\n /**\n * Distinguishes the storage used by this Zero instance from that of other\n * instances with the same userID. Useful in the case where the app wants to\n * have multiple Zero instances for the same user for different parts of the\n * app.\n */\n storageKey?: string | undefined;\n\n /**\n * Determines the level of detail at which Zero logs messages about\n * its operation. Messages are logged to the `console`.\n *\n * When this is set to `'debug'`, `'info'` and `'error'` messages are also\n * logged. When set to `'info'`, `'info'` and `'error'` but not\n * `'debug'` messages are logged. When set to `'error'` only `'error'`\n * messages are logged.\n *\n * Default is `'error'`.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * Destination for Zero's log output. When omitted, logs are written with\n * `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@linkcode LogSink} to redirect logs — for example, to\n * `process.stderr` in a CLI so that the tool's structured stdout output\n * isn't polluted by log lines.\n *\n * Note: this overrides only the console sink. When analytics logging is\n * enabled, the Datadog sink is still installed alongside this one.\n */\n logSink?: LogSink | undefined;\n\n /**\n * This defines the schema of the tables used in Zero and their relationships\n * to one another.\n */\n schema: S;\n\n /**\n * `mutators` is a map of custom mutator definitions. The keys are\n * namespaces or names of the mutators. The values are the mutator\n * implementations. Client side mutators must be idempotent as a\n * mutation can be rebased multiple times when folding in authoritative\n * changes from the server to the client.\n *\n * Define mutators using the `defineMutator` function to create type-safe,\n * parameterized mutations. Mutators can be top-level or grouped in namespaces.\n *\n * @example\n * ```ts\n * import {defineMutator} from '@rocicorp/zero';\n *\n * const z = new Zero({\n * schema,\n * userID,\n * mutators: {\n * // Top-level mutator\n * increment: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.counter.update({id: args.id, value: tx.query.counter.where('id', '=', args.id).value + 1})\n * ),\n * // Namespace with multiple mutators\n * issues: {\n * create: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {title: string}}) =>\n * tx.mutate.issues.insert({id: nanoid(), title: args.title, status: 'open'})\n * ),\n * close: defineMutator(({tx, args}: {tx: Transaction<Schema>, args: {id: string}}) =>\n * tx.mutate.issues.update({id: args.id, status: 'closed'})\n * ),\n * },\n * },\n * });\n *\n * // Usage\n * await z.mutate.increment({id: 'counter-1'}).client;\n * await z.mutate.issues.create({title: 'New issue'}).client;\n * await z.mutate.issues.close({id: 'issue-123'}).client;\n * ```\n */\n mutators?: MD extends CustomMutatorDefs ? MD : AnyMutatorRegistry | undefined;\n\n /**\n * Custom URL for mutation requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n mutateURL?: string | undefined;\n\n /**\n * Custom headers to include in mutation requests sent to your API server.\n * These headers are passed through zero-cache to the mutate endpoint.\n */\n mutateHeaders?: Record<string, string> | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n *\n * @deprecated Use {@linkcode queryURL} instead.\n */\n getQueriesURL?: string | undefined;\n\n /**\n * Custom URL for query requests sent to your API server.\n * If not provided, uses the default configured in zero-cache.\n */\n queryURL?: string | undefined;\n\n /**\n * Custom headers to include in query requests sent to your API server.\n * These headers are passed through zero-cache to the query endpoint.\n */\n queryHeaders?: Record<string, string> | undefined;\n\n /**\n * Optional callback that returns a W3C `traceparent` header value for\n * distributed tracing. Called before sending WebSocket messages that\n * trigger API server calls (`push`, `changeDesiredQueries`,\n * `initConnection`).\n *\n * This enables end-to-end trace correlation from your frontend through\n * zero-cache to your API server.\n *\n * @example\n * ```ts\n * import {propagation, context} from '@opentelemetry/api';\n *\n * new Zero({\n * getTraceparent: () => {\n * const carrier: Record<string, string> = {};\n * propagation.inject(context.active(), carrier);\n * return carrier.traceparent;\n * },\n * });\n * ```\n */\n getTraceparent?: (() => string | undefined) | undefined;\n\n /**\n * `onOnlineChange` is called when the Zero instance's online status changes.\n *\n * @deprecated Use {@linkcode Connection.state.subscribe} on the Zero instance instead. e.g.\n * ```ts\n * const zero = new Zero({...});\n * zero.connection.state.subscribe((state) => {\n * console.log('Connection state:', state.name);\n * });\n * ```\n *\n * Or use a hook like {@linkcode useConnectionState} to subscribe to state changes.\n */\n onOnlineChange?: ((online: boolean) => void) | undefined;\n\n /**\n * `onUpdateNeeded` is called when a client code update is needed.\n *\n * See {@link UpdateNeededReason} for why updates can be needed.\n *\n * The default behavior is to reload the page (using `location.reload()`).\n * Provide your own function to prevent the page from\n * reloading automatically. You may want to display a toast to inform the end\n * user there is a new version of your app available and prompt them to\n * refresh.\n */\n onUpdateNeeded?: ((reason: UpdateNeededReason) => void) | undefined;\n\n /**\n * `onClientStateNotFound` is called when this client is no longer able\n * to sync with zero-cache due to missing synchronization state. This\n * can be because:\n * - the local persistent synchronization state has been garbage collected.\n * This can happen if the client has no pending mutations and has not been\n * used for a while (e.g. the client's tab has been hidden for a long time).\n * - zero-cache fails to find the server side synchronization state for\n * this client.\n * - zero-cache rejects this client's persisted synchronization state,\n * requiring the local Replicache database to be reset.\n *\n * The current `Zero` instance should be treated as dead and replaced, not\n * reconnected.\n *\n * The default behavior for the Zero client is to reload the page\n * (using `location.reload()`). The React and SolidJS providers will replace\n * the client in-place, without a full page reload.\n *\n * Provide your own function to prevent this functionality.\n */\n onClientStateNotFound?: (() => void) | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance whose tab has become hidden.\n *\n * Instances in hidden tabs are disconnected to save resources.\n *\n * Default is 5 minutes.\n */\n hiddenTabDisconnectDelay?: number | undefined;\n\n /**\n * The number of milliseconds to wait before disconnecting a Zero\n * instance when the connection to the server has timed out.\n *\n * Default is 1 minute.\n */\n disconnectTimeoutMs?: number | undefined;\n\n /**\n * The timeout in milliseconds for ping operations. This value is used for:\n * - How long to wait in idle before sending a ping to the server\n * - How long to wait for a pong response after sending a ping\n *\n * Total time to detect a dead connection is 2 × pingTimeoutMs.\n *\n * Default is 5_000.\n */\n pingTimeoutMs?: number | undefined;\n\n /**\n * Determines what kind of storage implementation to use on the client.\n *\n * Defaults to `'idb'` which means that Zero uses an IndexedDB storage\n * implementation. This allows the data to be persisted on the client and\n * enables faster syncs between application restarts.\n *\n * By setting this to `'mem'`, Zero uses an in memory storage and\n * the data is not persisted on the client.\n *\n * You can also set this to a function that is used to create new KV stores,\n * allowing a custom implementation of the underlying storage layer.\n */\n kvStore?: 'mem' | 'idb' | StoreProvider | undefined;\n\n /**\n * The maximum number of bytes to allow in a single header.\n *\n * Zero adds some extra information to headers on initialization if possible.\n * This speeds up data synchronization. This number should be kept less than\n * or equal to the maximum header size allowed by the zero-cache and any load\n * balancers.\n *\n * Default value: 8kb.\n */\n maxHeaderLength?: number | undefined;\n\n /**\n * The maximum amount of milliseconds to wait for a materialization to\n * complete (including network/server time) before printing a warning to the\n * console.\n *\n * Default value: 5_000.\n */\n slowMaterializeThreshold?: number | undefined;\n\n /**\n * UI rendering libraries will often provide a utility for batching multiple\n * state updates into a single render. Some examples are React's\n * `unstable_batchedUpdates`, and solid-js's `batch`.\n *\n * This option enables integrating these batch utilities with Zero.\n *\n * When `batchViewUpdates` is provided, Zero will call it whenever\n * it updates query view state with an `applyViewUpdates` function\n * that performs the actual state updates.\n *\n * Zero updates query view state when:\n * 1. creating a new view\n * 2. updating all existing queries' views to a new consistent state\n *\n * When creating a new view, that single view's creation will be wrapped\n * in a `batchViewUpdates` call.\n *\n * When updating existing queries, all queries will be updated in a single\n * `batchViewUpdates` call, so that the transition to the new consistent\n * state can be done in a single render.\n *\n * Implementations must always call `applyViewUpdates` synchronously.\n */\n batchViewUpdates?: ((applyViewUpdates: () => void) => void) | undefined;\n\n /**\n * The maximum number of recent queries, no longer subscribed to by a preload\n * or view, to continue syncing.\n *\n * Defaults is 0.\n *\n * @deprecated Use ttl instead\n */\n maxRecentQueries?: number | undefined;\n\n /**\n * Changes to queries are sent to server in batches. This option controls\n * the number of milliseconds to wait before sending the next batch.\n *\n * Defaults is 10.\n */\n queryChangeThrottleMs?: number | undefined;\n\n /**\n * Context is passed to queries when they are executed.\n */\n context?: C | undefined;\n} & (unknown extends DefaultContext\n ? {}\n : {\n context: C;\n });\n\n/**\n * @deprecated Use {@link ZeroOptions} instead.\n */\nexport type ZeroAdvancedOptions<\n S extends BaseDefaultSchema,\n MD extends CustomMutatorDefs | undefined,\n Context extends BaseDefaultContext,\n> = ZeroOptions<S, MD, Context>;\n\ntype UpdateNeededReasonBase = {\n message?: string;\n};\n\nexport type UpdateNeededReason =\n | ({type: UpdateNeededReasonType.NewClientGroup} & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.VersionNotSupported;\n } & UpdateNeededReasonBase)\n | ({\n type: UpdateNeededReasonType.SchemaVersionNotSupported;\n } & UpdateNeededReasonBase);\n\nexport const updateNeededReasonTypeSchema: v.Type<UpdateNeededReason['type']> =\n v.literalUnion(\n UpdateNeededReasonType.NewClientGroup,\n UpdateNeededReasonType.VersionNotSupported,\n UpdateNeededReasonType.SchemaVersionNotSupported,\n );\n"],"mappings":";;;AA+YA,IAAa,+BACX,aACE,gBACA,qBACA,yBACF"}
|
|
@@ -69,10 +69,8 @@ export declare class QueryManager implements InspectorDelegate {
|
|
|
69
69
|
message: string;
|
|
70
70
|
}>): void;
|
|
71
71
|
addCustom(ast: AST, { name, args }: CustomQueryID, ttl: TTL, gotCallback?: GotCallback): () => void;
|
|
72
|
-
/** @deprecated */
|
|
73
72
|
addLegacy(ast: AST, ttl: TTL, gotCallback?: GotCallback): () => void;
|
|
74
73
|
updateCustom({ name, args }: CustomQueryID, ttl: TTL): void;
|
|
75
|
-
/** @deprecated */
|
|
76
74
|
updateLegacy(ast: AST, ttl: TTL): void;
|
|
77
75
|
flushBatch(): void;
|
|
78
76
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-manager.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/query-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,4CAA4C,CAAC;AAC/E,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,qCAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"query-manager.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/query-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,4CAA4C,CAAC;AAC/E,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,qCAAqC,CAAC;AAKlE,OAAO,EAAC,OAAO,EAAC,MAAM,gCAAgC,CAAC;AACvD,OAAO,EAGL,KAAK,GAAG,EACT,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,sDAAsD,CAAC;AACtG,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8CAA8C,CAAC;AAK/E,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,6CAA6C,CAAC;AAUlF,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0CAA0C,CAAC;AAC1E,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,4CAA4C,CAAC;AAChF,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,iCAAiC,CAAC;AACnE,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0CAA0C,CAAC;AAC1E,OAAO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MAAM,GAAG,oBAAoB,GAAG,SAAS;IAIlE;;OAEG;IACH,uBAAuB,IAAI,QAAQ,CAAC,MAAM,CAAC;CAG5C"}
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
2
|
-
import { getOrInsertComputed } from "../../../shared/src/map.js";
|
|
3
2
|
import { must } from "../../../shared/src/must.js";
|
|
4
3
|
import { mapAST, normalizeAST } from "../../../zero-protocol/src/ast.js";
|
|
5
4
|
import { clientToServer, serverToClient } from "../../../zero-schema/src/name-mapper.js";
|
|
6
|
-
import {
|
|
5
|
+
import { hashOfAST, hashOfNameAndArgs } from "../../../zero-protocol/src/query-hash.js";
|
|
7
6
|
import { TransformFailed } from "../../../zero-protocol/src/error-kind-enum.js";
|
|
8
7
|
import { ZeroCache } from "../../../zero-protocol/src/error-origin-enum.js";
|
|
9
8
|
import { Internal } from "../../../zero-protocol/src/error-reason-enum.js";
|
|
10
9
|
import { ProtocolError } from "../../../zero-protocol/src/error.js";
|
|
11
10
|
import "./error.js";
|
|
12
|
-
import { hashOfAST } from "../../../zero-protocol/src/query-hash.js";
|
|
13
11
|
import { clampTTL, compareTTL } from "../../../zql/src/query/ttl.js";
|
|
14
12
|
import { desiredQueriesPrefixForClient } from "./keys.js";
|
|
15
13
|
import { difference } from "../../../shared/src/set-utils.js";
|
|
@@ -31,8 +29,6 @@ var QueryManager = class {
|
|
|
31
29
|
#recentQueries = /* @__PURE__ */ new Set();
|
|
32
30
|
#gotQueries = /* @__PURE__ */ new Set();
|
|
33
31
|
#gotQueriesAuthoritative = false;
|
|
34
|
-
#cachedQueries = /* @__PURE__ */ new Set();
|
|
35
|
-
#awaitingPersistedGotDiff = true;
|
|
36
32
|
#mutationTracker;
|
|
37
33
|
#pendingQueryChanges = [];
|
|
38
34
|
#queryChangeThrottleMs;
|
|
@@ -62,32 +58,19 @@ var QueryManager = class {
|
|
|
62
58
|
for (const removal of pendingRemovals) removal();
|
|
63
59
|
});
|
|
64
60
|
experimentalWatch((diff) => {
|
|
65
|
-
const persisted = this.#awaitingPersistedGotDiff;
|
|
66
|
-
this.#awaitingPersistedGotDiff = false;
|
|
67
|
-
let thrown;
|
|
68
|
-
const fire = (queryHash, got) => {
|
|
69
|
-
const e = this.#fireGotCallbacks(queryHash, got);
|
|
70
|
-
thrown ??= e;
|
|
71
|
-
};
|
|
72
61
|
for (const diffOp of diff) {
|
|
73
62
|
const queryHash = diffOp.key.substring(2);
|
|
74
63
|
switch (diffOp.op) {
|
|
75
64
|
case "add":
|
|
76
65
|
this.#gotQueries.add(queryHash);
|
|
77
|
-
if (this.#gotQueriesAuthoritative)
|
|
78
|
-
else if (persisted) {
|
|
79
|
-
this.#cachedQueries.add(queryHash);
|
|
80
|
-
fire(queryHash, "cached");
|
|
81
|
-
}
|
|
66
|
+
if (this.#gotQueriesAuthoritative) this.#fireGotCallbacks(queryHash, true);
|
|
82
67
|
break;
|
|
83
68
|
case "del":
|
|
84
69
|
this.#gotQueries.delete(queryHash);
|
|
85
|
-
this.#
|
|
86
|
-
fire(queryHash, false);
|
|
70
|
+
this.#fireGotCallbacks(queryHash, false);
|
|
87
71
|
break;
|
|
88
72
|
}
|
|
89
73
|
}
|
|
90
|
-
if (thrown) throw thrown.error;
|
|
91
74
|
}, {
|
|
92
75
|
prefix: "g/",
|
|
93
76
|
initialValuesInFirstDiff: true
|
|
@@ -103,21 +86,9 @@ var QueryManager = class {
|
|
|
103
86
|
mapClientASTToServer(ast) {
|
|
104
87
|
return mapAST(ast, this.#clientToServer);
|
|
105
88
|
}
|
|
106
|
-
/**
|
|
107
|
-
* Notifies every subscriber of the query. A throwing subscriber does not
|
|
108
|
-
* keep the others from being notified; the first error is returned so the
|
|
109
|
-
* caller can rethrow it once its own bookkeeping is consistent.
|
|
110
|
-
*/
|
|
111
89
|
#fireGotCallbacks(queryHash, got) {
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
let thrown;
|
|
115
|
-
for (const gotCallback of [...entry.gotCallbacks]) try {
|
|
116
|
-
gotCallback(got);
|
|
117
|
-
} catch (error) {
|
|
118
|
-
thrown ??= { error };
|
|
119
|
-
}
|
|
120
|
-
return thrown;
|
|
90
|
+
const gotCallbacks = this.#queries.get(queryHash)?.gotCallbacks ?? [];
|
|
91
|
+
for (const gotCallback of gotCallbacks) gotCallback(got);
|
|
121
92
|
}
|
|
122
93
|
/**
|
|
123
94
|
* Trust `#gotQueries`. Called once the first poke after a (re)connect has
|
|
@@ -129,20 +100,11 @@ var QueryManager = class {
|
|
|
129
100
|
markGotQueriesAuthoritative() {
|
|
130
101
|
if (this.#gotQueriesAuthoritative) return;
|
|
131
102
|
this.#gotQueriesAuthoritative = true;
|
|
132
|
-
this.#
|
|
133
|
-
this.#awaitingPersistedGotDiff = false;
|
|
134
|
-
let thrown;
|
|
135
|
-
for (const queryHash of this.#queries.keys()) if (this.#gotQueries.has(queryHash)) {
|
|
136
|
-
const e = this.#fireGotCallbacks(queryHash, true);
|
|
137
|
-
thrown ??= e;
|
|
138
|
-
}
|
|
139
|
-
if (thrown) throw thrown.error;
|
|
103
|
+
for (const queryHash of this.#queries.keys()) if (this.#gotQueries.has(queryHash)) this.#fireGotCallbacks(queryHash, true);
|
|
140
104
|
}
|
|
141
105
|
/** Called on disconnect. The next connect must re-confirm `#gotQueries`. */
|
|
142
106
|
clearGotQueriesAuthoritative() {
|
|
143
|
-
if (!this.#gotQueriesAuthoritative) return;
|
|
144
107
|
this.#gotQueriesAuthoritative = false;
|
|
145
|
-
for (const queryHash of this.#gotQueries) this.#cachedQueries.add(queryHash);
|
|
146
108
|
}
|
|
147
109
|
/**
|
|
148
110
|
* Get the queries that need to be registered with the server.
|
|
@@ -219,10 +181,9 @@ var QueryManager = class {
|
|
|
219
181
|
}
|
|
220
182
|
addCustom(ast, { name, args }, ttl, gotCallback) {
|
|
221
183
|
const normalized = normalizeAST(ast);
|
|
222
|
-
const queryId =
|
|
184
|
+
const queryId = hashOfNameAndArgs(name, args);
|
|
223
185
|
return this.#add(queryId, normalized, name, args, ttl, gotCallback);
|
|
224
186
|
}
|
|
225
|
-
/** @deprecated */
|
|
226
187
|
addLegacy(ast, ttl, gotCallback) {
|
|
227
188
|
const normalized = normalizeAST(ast);
|
|
228
189
|
const astHash = hashOfAST(normalized);
|
|
@@ -257,7 +218,7 @@ var QueryManager = class {
|
|
|
257
218
|
this.#updateEntry(entry, queryId, ttl);
|
|
258
219
|
if (gotCallback) entry.gotCallbacks.push(gotCallback);
|
|
259
220
|
}
|
|
260
|
-
if (gotCallback) gotCallback(this.#gotQueriesAuthoritative
|
|
221
|
+
if (gotCallback) gotCallback(this.#gotQueriesAuthoritative && this.#gotQueries.has(queryId));
|
|
261
222
|
let removed = false;
|
|
262
223
|
const cleanupCb = () => {
|
|
263
224
|
if (removed) return;
|
|
@@ -271,11 +232,10 @@ var QueryManager = class {
|
|
|
271
232
|
return cleanupCb;
|
|
272
233
|
}
|
|
273
234
|
updateCustom({ name, args }, ttl) {
|
|
274
|
-
const queryID =
|
|
235
|
+
const queryID = hashOfNameAndArgs(name, args);
|
|
275
236
|
const entry = must(this.#queries.get(queryID));
|
|
276
237
|
this.#updateEntry(entry, queryID, ttl);
|
|
277
238
|
}
|
|
278
|
-
/** @deprecated */
|
|
279
239
|
updateLegacy(ast, ttl) {
|
|
280
240
|
const queryID = hashOfAST(normalizeAST(ast));
|
|
281
241
|
const entry = must(this.#queries.get(queryID));
|
|
@@ -351,7 +311,11 @@ var QueryManager = class {
|
|
|
351
311
|
if (this.#slowMaterializeThreshold !== void 0 && value > this.#slowMaterializeThreshold) this.#lc.warn?.("Slow query materialization (including server/network)", queryID, ast, value);
|
|
352
312
|
else this.#lc.debug?.("Materialized query (including server/network)", queryID, ast, value);
|
|
353
313
|
}
|
|
354
|
-
|
|
314
|
+
let existing = this.#queryMetrics.get(queryID);
|
|
315
|
+
if (!existing) {
|
|
316
|
+
existing = newPerQueryMetrics();
|
|
317
|
+
this.#queryMetrics.set(queryID, existing);
|
|
318
|
+
}
|
|
355
319
|
switch (metric) {
|
|
356
320
|
case "query-update-client":
|
|
357
321
|
existing["query-update-client"].add(value);
|