@rocicorp/zero 1.10.0-canary.0 → 1.10.0-canary.10
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/replicache/src/db/commit.js +1 -4
- package/out/replicache/src/db/commit.js.map +1 -1
- package/out/replicache/src/db/read.d.ts +1 -0
- package/out/replicache/src/db/read.d.ts.map +1 -1
- package/out/replicache/src/db/read.js +1 -4
- package/out/replicache/src/db/read.js.map +1 -1
- package/out/replicache/src/db/write.d.ts +2 -1
- package/out/replicache/src/db/write.d.ts.map +1 -1
- package/out/replicache/src/db/write.js +4 -51
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/persist/clients.d.ts +1 -0
- package/out/replicache/src/persist/clients.d.ts.map +1 -1
- package/out/replicache/src/persist/clients.js +4 -31
- package/out/replicache/src/persist/clients.js.map +1 -1
- package/out/replicache/src/process-env.d.ts +28 -0
- package/out/replicache/src/process-env.d.ts.map +1 -0
- package/out/replicache/src/replicache-impl.d.ts.map +1 -1
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/scan-iterator.js +2 -14
- package/out/replicache/src/scan-iterator.js.map +1 -1
- package/out/replicache/src/subscriptions.d.ts +1 -0
- package/out/replicache/src/subscriptions.d.ts.map +1 -1
- package/out/replicache/src/subscriptions.js +2 -10
- package/out/replicache/src/subscriptions.js.map +1 -1
- package/out/replicache/src/transactions.d.ts +1 -0
- package/out/replicache/src/transactions.d.ts.map +1 -1
- package/out/replicache/src/transactions.js +2 -4
- package/out/replicache/src/transactions.js.map +1 -1
- package/out/shared/src/promise-race.d.ts +14 -0
- package/out/shared/src/promise-race.d.ts.map +1 -1
- package/out/shared/src/promise-race.js +32 -1
- package/out/shared/src/promise-race.js.map +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +1 -22
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +3 -3
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +8 -1
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts +6 -0
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +24 -2
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +65 -4
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +202 -35
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +1 -1
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/db/delete-lite-db.js +2 -1
- package/out/zero-cache/src/db/delete-lite-db.js.map +1 -1
- package/out/zero-cache/src/db/migration-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration-lite.js +10 -5
- package/out/zero-cache/src/db/migration-lite.js.map +1 -1
- package/out/zero-cache/src/db/migration.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration.js +4 -2
- package/out/zero-cache/src/db/migration.js.map +1 -1
- package/out/zero-cache/src/db/sqlite-corruption.d.ts +3 -2
- package/out/zero-cache/src/db/sqlite-corruption.d.ts.map +1 -1
- package/out/zero-cache/src/db/sqlite-corruption.js +13 -8
- package/out/zero-cache/src/db/sqlite-corruption.js.map +1 -1
- package/out/zero-cache/src/db/transaction-pool.d.ts +5 -15
- package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
- package/out/zero-cache/src/db/transaction-pool.js +8 -72
- package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.d.ts +6 -1
- package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/observability/metrics.js +20 -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 +105 -34
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/main.d.ts.map +1 -1
- package/out/zero-cache/src/server/main.js +8 -18
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +48 -5
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/run-worker.js +3 -2
- package/out/zero-cache/src/server/runner/run-worker.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 -1
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/server/worker-urls.d.ts +0 -1
- package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
- package/out/zero-cache/src/server/worker-urls.js +1 -2
- package/out/zero-cache/src/server/worker-urls.js.map +1 -1
- package/out/zero-cache/src/services/change-source/change-source.d.ts +4 -2
- package/out/zero-cache/src/services/change-source/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts +35 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.js +34 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.js.map +1 -0
- package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts +2 -0
- package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.js +81 -3
- package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts +2 -6
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js +14 -5
- package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +22 -11
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +7 -7
- 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 +90 -31
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/decommission.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/decommission.js +20 -11
- package/out/zero-cache/src/services/change-source/pg/decommission.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +9 -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 +61 -76
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +65 -2
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +101 -10
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +27 -2
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +41 -8
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts +0 -5
- 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 +29 -41
- 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/shard.d.ts +35 -16
- 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 +77 -7
- 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 +2 -1
- 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/data.js +5 -13
- package/out/zero-cache/src/services/change-source/protocol/current/data.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +6 -3
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.d.ts +6 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.js +21 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.js.map +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +3 -7
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +26 -10
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +15 -5
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js +71 -0
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts +68 -78
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/broadcast.js +84 -92
- package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts +19 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js +50 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts +34 -0
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +67 -0
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts +141 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +270 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.d.ts +19 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +39 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +5 -8
- 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 +20 -19
- 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-service.d.ts +90 -24
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +456 -66
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +50 -13
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts +8 -0
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +14 -3
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.js +42 -12
- package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/{litestream3-backup-monitor.d.ts → litestream3-prometheus-poller.d.ts} +19 -45
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/{litestream3-backup-monitor.js → litestream3-prometheus-poller.js} +68 -176
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts +15 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.js +55 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +5 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js +2 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts +11 -0
- package/out/zero-cache/src/services/change-streamer/shard-sampling.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js +19 -0
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +24 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +119 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +4 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.js +39 -14
- package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts +99 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js +344 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts +83 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +417 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.d.ts +121 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +391 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts +73 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +157 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts +62 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +164 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts +109 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +258 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/storer.d.ts +85 -12
- package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +286 -141
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +61 -10
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.js +101 -8
- package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +34 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js +86 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts +29 -0
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +154 -0
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +1 -0
- package/out/zero-cache/src/services/http-service.d.ts +1 -0
- package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/http-service.js +7 -3
- package/out/zero-cache/src/services/http-service.js.map +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js +4 -3
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts +12 -11
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +115 -152
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/config-v5.yml +42 -0
- package/out/zero-cache/src/services/litestream/config.yml +3 -2
- package/out/zero-cache/src/services/litestream/metrics.d.ts +5 -4
- package/out/zero-cache/src/services/litestream/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/metrics.js +10 -10
- package/out/zero-cache/src/services/litestream/metrics.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +5 -2
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +169 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +434 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-db.d.ts +368 -0
- package/out/zero-cache/src/services/replicator/change-log-db.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-db.js +491 -0
- package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts +55 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +150 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-processor.d.ts +6 -0
- package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +70 -25
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +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 +19 -6
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.d.ts +0 -22
- package/out/zero-cache/src/services/replicator/notifier.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.js +7 -1
- package/out/zero-cache/src/services/replicator/notifier.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts +17 -2
- package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js +9 -3
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts +27 -0
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.js +32 -0
- package/out/zero-cache/src/services/replicator/reporter/recorder.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/schema/backfilling.d.ts +119 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.js +214 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.js.map +1 -0
- package/out/zero-cache/src/services/replicator/schema/change-log.d.ts +3 -3
- package/out/zero-cache/src/services/replicator/schema/column-metadata.js +1 -1
- package/out/zero-cache/src/services/replicator/schema/column-metadata.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.js +9 -5
- package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +132 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +415 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.d.ts +120 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.js +283 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.js.map +1 -0
- package/out/zero-cache/src/services/replicator/write-worker.js +23 -12
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +2 -1
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/running-state.d.ts +1 -1
- package/out/zero-cache/src/services/running-state.d.ts.map +1 -1
- package/out/zero-cache/src/services/running-state.js +1 -0
- package/out/zero-cache/src/services/running-state.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.d.ts +3 -2
- package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.js +25 -17
- package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +14 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.d.ts +53 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.d.ts.map +1 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.js +68 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.js.map +1 -0
- 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 +18 -3
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- 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 +14 -4
- 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 +70 -8
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/downstream.d.ts +11 -0
- package/out/zero-cache/src/types/downstream.d.ts.map +1 -0
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js +14 -4
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/poke-chunk.d.ts +18 -0
- package/out/zero-cache/src/types/poke-chunk.d.ts.map +1 -0
- package/out/zero-cache/src/types/poke-chunk.js +57 -0
- package/out/zero-cache/src/types/poke-chunk.js.map +1 -0
- package/out/zero-cache/src/types/processes.d.ts +1 -2
- package/out/zero-cache/src/types/processes.d.ts.map +1 -1
- package/out/zero-cache/src/types/processes.js +1 -28
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +16 -0
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +25 -4
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/types/subscription.d.ts +2 -0
- package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
- package/out/zero-cache/src/types/subscription.js +6 -0
- package/out/zero-cache/src/types/subscription.js.map +1 -1
- package/out/zero-cache/src/workers/connection.d.ts +23 -4
- package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connection.js +130 -10
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.d.ts +25 -0
- package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +33 -1
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts +12 -0
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +75 -0
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero-poke-handler.d.ts +7 -2
- package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
- package/out/zero-client/src/client/zero-poke-handler.js +52 -2
- package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
- package/out/zero-client/src/client/zero.d.ts +6 -7
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +194 -107
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +1 -1
- package/out/zero-protocol/src/poke.d.ts +89 -7
- package/out/zero-protocol/src/poke.d.ts.map +1 -1
- package/out/zero-protocol/src/poke.js +16 -8
- package/out/zero-protocol/src/poke.js.map +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts +12 -7
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-schema/src/builder/table-builder.d.ts +23 -0
- package/out/zero-schema/src/builder/table-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/table-builder.js +18 -0
- package/out/zero-schema/src/builder/table-builder.js.map +1 -1
- package/out/zero-server/src/custom.js +10 -3
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zero-server/src/schema.d.ts +8 -0
- package/out/zero-server/src/schema.d.ts.map +1 -1
- package/out/zero-server/src/schema.js +63 -24
- package/out/zero-server/src/schema.js.map +1 -1
- package/out/zero-types/src/schema.d.ts +11 -0
- package/out/zero-types/src/schema.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts +10 -2
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +14 -6
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/stream.d.ts +0 -1
- package/out/zql/src/ivm/stream.d.ts.map +1 -1
- package/out/zql/src/ivm/stream.js +1 -7
- package/out/zql/src/ivm/stream.js.map +1 -1
- package/out/zql/src/ivm/union-fan-in.d.ts +1 -1
- package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/union-fan-in.js +11 -2
- package/out/zql/src/ivm/union-fan-in.js.map +1 -1
- package/out/zql/src/mutate/crud.d.ts +10 -8
- package/out/zql/src/mutate/crud.d.ts.map +1 -1
- package/out/zql/src/mutate/crud.js.map +1 -1
- package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
- package/out/zql/src/query/query-delegate-base.js +5 -1
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +2 -2
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query.d.ts +83 -14
- package/out/zql/src/query/query.d.ts.map +1 -1
- package/out/zql/src/query/static-query.d.ts +1 -1
- package/out/zql/src/query/static-query.d.ts.map +1 -1
- package/out/zqlite/src/db.js +2 -2
- package/out/zqlite/src/resolve-scalar-subqueries.d.ts +15 -0
- package/out/zqlite/src/resolve-scalar-subqueries.d.ts.map +1 -1
- package/out/zqlite/src/resolve-scalar-subqueries.js +33 -14
- package/out/zqlite/src/resolve-scalar-subqueries.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js +5 -5
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +4 -4
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +3 -3
- package/out/replicache/src/db/index.js +0 -91
- package/out/replicache/src/db/index.js.map +0 -1
- package/out/replicache/src/lazy.d.ts +0 -2
- package/out/replicache/src/lazy.d.ts.map +0 -1
- package/out/replicache/src/lazy.js +0 -12
- package/out/replicache/src/lazy.js.map +0 -1
- package/out/zero-cache/src/server/backup-watermark-reader.js +0 -35
- package/out/zero-cache/src/server/backup-watermark-reader.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.d.ts +0 -16
- package/out/zero-cache/src/services/change-streamer/replica-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js +0 -54
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts +0 -25
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js +0 -159
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts +0 -44
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js +0 -65
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts +0 -11
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js +0 -74
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts +0 -42
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js +0 -117
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js.map +0 -1
|
@@ -11,7 +11,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
11
11
|
}>;
|
|
12
12
|
timestamp: v.Optional<number>;
|
|
13
13
|
}, undefined>]>, v.TupleType<[v.Type<"pokePart">, v.ObjectType<{
|
|
14
|
-
pokeID: v.Type<string>;
|
|
15
14
|
lastMutationIDChanges: v.Optional<Record<string, number>>;
|
|
16
15
|
desiredQueriesPatches: v.Optional<Record<string, ({
|
|
17
16
|
ttl?: number | undefined;
|
|
@@ -75,6 +74,7 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
75
74
|
clientID: string;
|
|
76
75
|
};
|
|
77
76
|
})[]>;
|
|
77
|
+
pokeID: v.Type<string>;
|
|
78
78
|
}, undefined>]>, v.TupleType<[v.Type<"pokeEnd">, v.ObjectType<{
|
|
79
79
|
pokeID: v.Type<string>;
|
|
80
80
|
cookie: v.Type<string>;
|
|
@@ -11,12 +11,14 @@ import * as v from '../../shared/src/valita.ts';
|
|
|
11
11
|
* A poke begins with a `poke-start` message which contains the `baseCookie`
|
|
12
12
|
* the poke is updating from and the `cookie` the poke is updating to.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* Through protocol version 51, the poke continues with zero to many
|
|
15
|
+
* `poke-part` JSON messages. Starting in version 52, it continues with zero to
|
|
16
|
+
* many binary `pokeChunk` messages. Each binary message starts with a message
|
|
17
|
+
* type byte. Concatenating and decoding the payload after that byte produces a
|
|
18
|
+
* PokePartBody array. pokeChunk boundaries have no semantic meaning.
|
|
17
19
|
*
|
|
18
|
-
* Finally, the poke ends with a `poke-end` message.
|
|
19
|
-
*
|
|
20
|
+
* Finally, the poke ends with a `poke-end` message. The decoded patches can
|
|
21
|
+
* now be applied as a whole to update from `baseCookie` to `cookie`.
|
|
20
22
|
*
|
|
21
23
|
* Poke messages can be intermingled with other `down` messages, but cannot be
|
|
22
24
|
* intermingled with poke messages for a different `pokeID`. If this is
|
|
@@ -37,7 +39,6 @@ export declare const pokeStartBodySchema: v.ObjectType<{
|
|
|
37
39
|
timestamp: v.Optional<number>;
|
|
38
40
|
}, undefined>;
|
|
39
41
|
export declare const pokePartBodySchema: v.ObjectType<{
|
|
40
|
-
pokeID: v.Type<string>;
|
|
41
42
|
lastMutationIDChanges: v.Optional<Record<string, number>>;
|
|
42
43
|
desiredQueriesPatches: v.Optional<Record<string, ({
|
|
43
44
|
ttl?: number | undefined;
|
|
@@ -101,7 +102,79 @@ export declare const pokePartBodySchema: v.ObjectType<{
|
|
|
101
102
|
clientID: string;
|
|
102
103
|
};
|
|
103
104
|
})[]>;
|
|
105
|
+
pokeID: v.Type<string>;
|
|
104
106
|
}, undefined>;
|
|
107
|
+
/**
|
|
108
|
+
* The logical payload carried by binary poke chunks. Chunk boundaries are
|
|
109
|
+
* arbitrary; concatenating and decoding all chunks for a poke produces this
|
|
110
|
+
* array.
|
|
111
|
+
*/
|
|
112
|
+
export declare const pokePartsSchema: v.ArrayType<v.ObjectType<{
|
|
113
|
+
lastMutationIDChanges: v.Optional<Record<string, number>>;
|
|
114
|
+
desiredQueriesPatches: v.Optional<Record<string, ({
|
|
115
|
+
ttl?: number | undefined;
|
|
116
|
+
op: "put";
|
|
117
|
+
hash: string;
|
|
118
|
+
} | {
|
|
119
|
+
op: "del";
|
|
120
|
+
hash: string;
|
|
121
|
+
} | {
|
|
122
|
+
op: "clear";
|
|
123
|
+
})[]>>;
|
|
124
|
+
gotQueriesPatch: v.Optional<({
|
|
125
|
+
ttl?: number | undefined;
|
|
126
|
+
op: "put";
|
|
127
|
+
hash: string;
|
|
128
|
+
} | {
|
|
129
|
+
op: "del";
|
|
130
|
+
hash: string;
|
|
131
|
+
} | {
|
|
132
|
+
op: "clear";
|
|
133
|
+
})[]>;
|
|
134
|
+
rowsPatch: v.Optional<({
|
|
135
|
+
op: "put";
|
|
136
|
+
tableName: string;
|
|
137
|
+
value: Readonly<Record<string, import("../../shared/src/json.ts").ReadonlyJSONValue | undefined>>;
|
|
138
|
+
} | {
|
|
139
|
+
merge?: import("../../shared/src/json.ts").ReadonlyJSONObject | undefined;
|
|
140
|
+
constrain?: string[] | undefined;
|
|
141
|
+
op: "update";
|
|
142
|
+
tableName: string;
|
|
143
|
+
id: Readonly<Record<string, string | number | boolean>>;
|
|
144
|
+
} | {
|
|
145
|
+
op: "del";
|
|
146
|
+
tableName: string;
|
|
147
|
+
id: Readonly<Record<string, string | number | boolean>>;
|
|
148
|
+
} | {
|
|
149
|
+
op: "clear";
|
|
150
|
+
})[]>;
|
|
151
|
+
mutationsPatch: v.Optional<({
|
|
152
|
+
op: "put";
|
|
153
|
+
mutation: {
|
|
154
|
+
id: {
|
|
155
|
+
id: number;
|
|
156
|
+
clientID: string;
|
|
157
|
+
};
|
|
158
|
+
result: {
|
|
159
|
+
message?: string | undefined;
|
|
160
|
+
details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
|
|
161
|
+
error: "app";
|
|
162
|
+
} | {
|
|
163
|
+
details?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
|
|
164
|
+
error: "oooMutation" | "alreadyProcessed";
|
|
165
|
+
} | {
|
|
166
|
+
data?: import("../../shared/src/json.ts").ReadonlyJSONValue | undefined;
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
} | {
|
|
170
|
+
op: "del";
|
|
171
|
+
id: {
|
|
172
|
+
id: number;
|
|
173
|
+
clientID: string;
|
|
174
|
+
};
|
|
175
|
+
})[]>;
|
|
176
|
+
pokeID: v.Type<string>;
|
|
177
|
+
}, undefined>>;
|
|
105
178
|
export declare const pokeEndBodySchema: v.ObjectType<{
|
|
106
179
|
pokeID: v.Type<string>;
|
|
107
180
|
cookie: v.Type<string>;
|
|
@@ -121,7 +194,6 @@ export declare const pokeStartMessageSchema: v.TupleType<[v.Type<"pokeStart">, v
|
|
|
121
194
|
timestamp: v.Optional<number>;
|
|
122
195
|
}, undefined>]>;
|
|
123
196
|
export declare const pokePartMessageSchema: v.TupleType<[v.Type<"pokePart">, v.ObjectType<{
|
|
124
|
-
pokeID: v.Type<string>;
|
|
125
197
|
lastMutationIDChanges: v.Optional<Record<string, number>>;
|
|
126
198
|
desiredQueriesPatches: v.Optional<Record<string, ({
|
|
127
199
|
ttl?: number | undefined;
|
|
@@ -185,6 +257,7 @@ export declare const pokePartMessageSchema: v.TupleType<[v.Type<"pokePart">, v.O
|
|
|
185
257
|
clientID: string;
|
|
186
258
|
};
|
|
187
259
|
})[]>;
|
|
260
|
+
pokeID: v.Type<string>;
|
|
188
261
|
}, undefined>]>;
|
|
189
262
|
export declare const pokeEndMessageSchema: v.TupleType<[v.Type<"pokeEnd">, v.ObjectType<{
|
|
190
263
|
pokeID: v.Type<string>;
|
|
@@ -193,7 +266,16 @@ export declare const pokeEndMessageSchema: v.TupleType<[v.Type<"pokeEnd">, v.Obj
|
|
|
193
266
|
}, undefined>]>;
|
|
194
267
|
export type PokeStartBody = v.Infer<typeof pokeStartBodySchema>;
|
|
195
268
|
export type PokePartBody = v.Infer<typeof pokePartBodySchema>;
|
|
269
|
+
export type PokeParts = v.Infer<typeof pokePartsSchema>;
|
|
196
270
|
export type PokeEndBody = v.Infer<typeof pokeEndBodySchema>;
|
|
271
|
+
/** The first byte identifying a binary WebSocket message as a poke chunk. */
|
|
272
|
+
export declare const POKE_CHUNK_MESSAGE_TYPE = 0;
|
|
273
|
+
/** The first protocol version that receives binary poke chunks. */
|
|
274
|
+
export declare const POKE_CHUNK_PROTOCOL_VERSION = 52;
|
|
275
|
+
/** The last protocol version that receives JSON pokePart messages. */
|
|
276
|
+
export declare const LAST_POKE_PART_PROTOCOL_VERSION = 51;
|
|
277
|
+
/** A tagged binary poke chunk WebSocket message. */
|
|
278
|
+
export type PokeChunk = Uint8Array;
|
|
197
279
|
export type PokeStartMessage = v.Infer<typeof pokeStartMessageSchema>;
|
|
198
280
|
export type PokePartMessage = v.Infer<typeof pokePartMessageSchema>;
|
|
199
281
|
export type PokeEndMessage = v.Infer<typeof pokeEndMessageSchema>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"poke.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/poke.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAMhD
|
|
1
|
+
{"version":3,"file":"poke.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/poke.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAMhD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,eAAO,MAAM,mBAAmB;;;IAM9B;;;OAGG;;;;;;aAQH,CAAC;AAEH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAa7B,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAA8B,CAAC;AAE3D,eAAO,MAAM,iBAAiB;;;;aAO5B,CAAC;AAEH,eAAO,MAAM,sBAAsB;;;IA5CjC;;;OAGG;;;;;;eA4CH,CAAC;AACH,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAGhC,CAAC;AACH,eAAO,MAAM,oBAAoB;;;;eAG/B,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AACxD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE5D,6EAA6E;AAC7E,eAAO,MAAM,uBAAuB,IAAO,CAAC;AAE5C,mEAAmE;AACnE,eAAO,MAAM,2BAA2B,KAAK,CAAC;AAE9C,sEAAsE;AACtE,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAElD,oDAAoD;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC;AAEnC,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACtE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AACpE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
|
|
@@ -16,12 +16,14 @@ import { nullableVersionSchema, versionSchema } from "./version.js";
|
|
|
16
16
|
* A poke begins with a `poke-start` message which contains the `baseCookie`
|
|
17
17
|
* the poke is updating from and the `cookie` the poke is updating to.
|
|
18
18
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
19
|
+
* Through protocol version 51, the poke continues with zero to many
|
|
20
|
+
* `poke-part` JSON messages. Starting in version 52, it continues with zero to
|
|
21
|
+
* many binary `pokeChunk` messages. Each binary message starts with a message
|
|
22
|
+
* type byte. Concatenating and decoding the payload after that byte produces a
|
|
23
|
+
* PokePartBody array. pokeChunk boundaries have no semantic meaning.
|
|
22
24
|
*
|
|
23
|
-
* Finally, the poke ends with a `poke-end` message.
|
|
24
|
-
*
|
|
25
|
+
* Finally, the poke ends with a `poke-end` message. The decoded patches can
|
|
26
|
+
* now be applied as a whole to update from `baseCookie` to `cookie`.
|
|
25
27
|
*
|
|
26
28
|
* Poke messages can be intermingled with other `down` messages, but cannot be
|
|
27
29
|
* intermingled with poke messages for a different `pokeID`. If this is
|
|
@@ -42,13 +44,19 @@ var pokeStartBodySchema = valita_exports.object({
|
|
|
42
44
|
timestamp: valita_exports.number().optional()
|
|
43
45
|
});
|
|
44
46
|
var pokePartBodySchema = valita_exports.object({
|
|
45
|
-
pokeID: valita_exports.string(),
|
|
46
47
|
lastMutationIDChanges: valita_exports.record(valita_exports.number()).optional(),
|
|
47
48
|
desiredQueriesPatches: valita_exports.record(queriesPatchSchema).optional(),
|
|
48
49
|
gotQueriesPatch: queriesPatchSchema.optional(),
|
|
49
50
|
rowsPatch: rowsPatchSchema.optional(),
|
|
50
|
-
mutationsPatch: mutationsPatchSchema.optional()
|
|
51
|
+
mutationsPatch: mutationsPatchSchema.optional(),
|
|
52
|
+
pokeID: valita_exports.string()
|
|
51
53
|
});
|
|
54
|
+
/**
|
|
55
|
+
* The logical payload carried by binary poke chunks. Chunk boundaries are
|
|
56
|
+
* arbitrary; concatenating and decoding all chunks for a poke produces this
|
|
57
|
+
* array.
|
|
58
|
+
*/
|
|
59
|
+
var pokePartsSchema = valita_exports.array(pokePartBodySchema);
|
|
52
60
|
var pokeEndBodySchema = valita_exports.object({
|
|
53
61
|
pokeID: valita_exports.string(),
|
|
54
62
|
cookie: versionSchema,
|
|
@@ -58,6 +66,6 @@ var pokeStartMessageSchema = valita_exports.tuple([valita_exports.literal("pokeS
|
|
|
58
66
|
var pokePartMessageSchema = valita_exports.tuple([valita_exports.literal("pokePart"), pokePartBodySchema]);
|
|
59
67
|
var pokeEndMessageSchema = valita_exports.tuple([valita_exports.literal("pokeEnd"), pokeEndBodySchema]);
|
|
60
68
|
//#endregion
|
|
61
|
-
export { pokeEndMessageSchema, pokePartMessageSchema, pokeStartMessageSchema };
|
|
69
|
+
export { pokeEndMessageSchema, pokePartMessageSchema, pokePartsSchema, pokeStartMessageSchema };
|
|
62
70
|
|
|
63
71
|
//# sourceMappingURL=poke.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"poke.js","names":[],"sources":["../../../../zero-protocol/src/poke.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\nimport {mutationsPatchSchema} from './mutations-patch.ts';\nimport {queriesPatchSchema} from './queries-patch.ts';\nimport {rowsPatchSchema} from './row-patch.ts';\nimport {nullableVersionSchema, versionSchema} from './version.ts';\n\n/**\n * Pokes use a multi-part format. Pokes send entity data to the client and can\n * be multiple mega-bytes in size. Using a multi-part format allows the server\n * to avoid having to have the full poke in memory at one time.\n *\n * Each poke is assigned a `pokeID`, a unique id (within the context of the\n * connection) for identifying the poke. All messages for a poke will have the\n * same `pokeID`.\n *\n * A poke begins with a `poke-start` message which contains the `baseCookie`\n * the poke is updating from and the `cookie` the poke is updating to.\n *\n *
|
|
1
|
+
{"version":3,"file":"poke.js","names":[],"sources":["../../../../zero-protocol/src/poke.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\nimport {mutationsPatchSchema} from './mutations-patch.ts';\nimport {queriesPatchSchema} from './queries-patch.ts';\nimport {rowsPatchSchema} from './row-patch.ts';\nimport {nullableVersionSchema, versionSchema} from './version.ts';\n\n/**\n * Pokes use a multi-part format. Pokes send entity data to the client and can\n * be multiple mega-bytes in size. Using a multi-part format allows the server\n * to avoid having to have the full poke in memory at one time.\n *\n * Each poke is assigned a `pokeID`, a unique id (within the context of the\n * connection) for identifying the poke. All messages for a poke will have the\n * same `pokeID`.\n *\n * A poke begins with a `poke-start` message which contains the `baseCookie`\n * the poke is updating from and the `cookie` the poke is updating to.\n *\n * Through protocol version 51, the poke continues with zero to many\n * `poke-part` JSON messages. Starting in version 52, it continues with zero to\n * many binary `pokeChunk` messages. Each binary message starts with a message\n * type byte. Concatenating and decoding the payload after that byte produces a\n * PokePartBody array. pokeChunk boundaries have no semantic meaning.\n *\n * Finally, the poke ends with a `poke-end` message. The decoded patches can\n * now be applied as a whole to update from `baseCookie` to `cookie`.\n *\n * Poke messages can be intermingled with other `down` messages, but cannot be\n * intermingled with poke messages for a different `pokeID`. If this is\n * observed it is an unexpected error; the client should ignore both pokes,\n * disconnect, and reconnect.\n */\n\nexport const pokeStartBodySchema = v.object({\n pokeID: v.string(),\n // We always specify a Version as our cookie, but Replicache starts clients\n // with initial cookie `null`, before the first request. So we have to be\n // able to send a base cookie with value `null` to match that state.\n baseCookie: nullableVersionSchema,\n /**\n * This field is always set if the poke contains a `rowsPatch`.\n * It may be absent for patches that only update clients and queries.\n */\n schemaVersions: v\n .object({\n minSupportedVersion: v.number(),\n maxSupportedVersion: v.number(),\n })\n .optional(),\n timestamp: v.number().optional(),\n});\n\nexport const pokePartBodySchema = v.object({\n // Changes to last mutation id by client id.\n lastMutationIDChanges: v.record(v.number()).optional(),\n // Patches to the desired query sets by client id.\n desiredQueriesPatches: v.record(queriesPatchSchema).optional(),\n // Patches to the set of queries for which entities are sync'd in\n // rowsPatch.\n gotQueriesPatch: queriesPatchSchema.optional(),\n // Patches to the rows set.\n rowsPatch: rowsPatchSchema.optional(),\n // Mutation results patch\n mutationsPatch: mutationsPatchSchema.optional(),\n pokeID: v.string(),\n});\n\n/**\n * The logical payload carried by binary poke chunks. Chunk boundaries are\n * arbitrary; concatenating and decoding all chunks for a poke produces this\n * array.\n */\nexport const pokePartsSchema = v.array(pokePartBodySchema);\n\nexport const pokeEndBodySchema = v.object({\n pokeID: v.string(),\n // Note: This should be ignored (and may be empty) if cancel === `true`.\n cookie: versionSchema,\n // If `true`, the poke with id `pokeID` should be discarded without\n // applying it.\n cancel: v.boolean().optional(),\n});\n\nexport const pokeStartMessageSchema = v.tuple([\n v.literal('pokeStart'),\n pokeStartBodySchema,\n]);\nexport const pokePartMessageSchema = v.tuple([\n v.literal('pokePart'),\n pokePartBodySchema,\n]);\nexport const pokeEndMessageSchema = v.tuple([\n v.literal('pokeEnd'),\n pokeEndBodySchema,\n]);\n\nexport type PokeStartBody = v.Infer<typeof pokeStartBodySchema>;\nexport type PokePartBody = v.Infer<typeof pokePartBodySchema>;\nexport type PokeParts = v.Infer<typeof pokePartsSchema>;\nexport type PokeEndBody = v.Infer<typeof pokeEndBodySchema>;\n\n/** The first byte identifying a binary WebSocket message as a poke chunk. */\nexport const POKE_CHUNK_MESSAGE_TYPE = 0x00;\n\n/** The first protocol version that receives binary poke chunks. */\nexport const POKE_CHUNK_PROTOCOL_VERSION = 52;\n\n/** The last protocol version that receives JSON pokePart messages. */\nexport const LAST_POKE_PART_PROTOCOL_VERSION = 51;\n\n/** A tagged binary poke chunk WebSocket message. */\nexport type PokeChunk = Uint8Array;\n\nexport type PokeStartMessage = v.Infer<typeof pokeStartMessageSchema>;\nexport type PokePartMessage = v.Infer<typeof pokePartMessageSchema>;\nexport type PokeEndMessage = v.Infer<typeof pokeEndMessageSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,sBAAsB,eAAE,OAAO;CAC1C,QAAQ,eAAE,OAAO;CAIjB,YAAY;;;;;CAKZ,gBAAgB,eACb,OAAO;EACN,qBAAqB,eAAE,OAAO;EAC9B,qBAAqB,eAAE,OAAO;CAChC,CAAC,EACA,SAAS;CACZ,WAAW,eAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAED,IAAa,qBAAqB,eAAE,OAAO;CAEzC,uBAAuB,eAAE,OAAO,eAAE,OAAO,CAAC,EAAE,SAAS;CAErD,uBAAuB,eAAE,OAAO,kBAAkB,EAAE,SAAS;CAG7D,iBAAiB,mBAAmB,SAAS;CAE7C,WAAW,gBAAgB,SAAS;CAEpC,gBAAgB,qBAAqB,SAAS;CAC9C,QAAQ,eAAE,OAAO;AACnB,CAAC;;;;;;AAOD,IAAa,kBAAkB,eAAE,MAAM,kBAAkB;AAEzD,IAAa,oBAAoB,eAAE,OAAO;CACxC,QAAQ,eAAE,OAAO;CAEjB,QAAQ;CAGR,QAAQ,eAAE,QAAQ,EAAE,SAAS;AAC/B,CAAC;AAED,IAAa,yBAAyB,eAAE,MAAM,CAC5C,eAAE,QAAQ,WAAW,GACrB,mBACF,CAAC;AACD,IAAa,wBAAwB,eAAE,MAAM,CAC3C,eAAE,QAAQ,UAAU,GACpB,kBACF,CAAC;AACD,IAAa,uBAAuB,eAAE,MAAM,CAC1C,eAAE,QAAQ,SAAS,GACnB,iBACF,CAAC"}
|
|
@@ -10,15 +10,20 @@
|
|
|
10
10
|
* release. The server (`zero-cache`) must be deployed before clients start
|
|
11
11
|
* running the new code.
|
|
12
12
|
*/
|
|
13
|
-
export declare const PROTOCOL_VERSION =
|
|
13
|
+
export declare const PROTOCOL_VERSION = 52;
|
|
14
14
|
/**
|
|
15
15
|
* The minimum server-supported sync protocol version (i.e. the version
|
|
16
|
-
* declared in the "/sync/v{#}/connect" URL).
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
16
|
+
* declared in the "/sync/v{#}/connect" URL).
|
|
17
|
+
*
|
|
18
|
+
* CloudZero can serve applications running old client releases indefinitely.
|
|
19
|
+
* Consequently, this value must never be increased: `zero-cache` must continue
|
|
20
|
+
* to support every sync protocol from this version through `PROTOCOL_VERSION`.
|
|
21
|
+
* A wire change that an old client cannot ignore must branch on the client's
|
|
22
|
+
* protocol version and retain the old behavior. Keep each compatibility fork
|
|
23
|
+
* isolated at the boundary that owns the changed behavior and test both sides
|
|
24
|
+
* of its version cutoff.
|
|
25
|
+
*
|
|
26
|
+
* Client connections from protocol versions before this historical floor are
|
|
22
27
|
* closed with a `VersionNotSupported` error.
|
|
23
28
|
*/
|
|
24
29
|
export declare const MIN_SERVER_SUPPORTED_SYNC_PROTOCOL = 30;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-version.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/protocol-version.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"protocol-version.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/protocol-version.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAgDH,eAAO,MAAM,gBAAgB,KAAK,CAAC;AAEnC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,kCAAkC,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-version.js","names":[],"sources":["../../../../zero-protocol/src/protocol-version.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\n\n/**\n * The current `PROTOCOL_VERSION` of the code.\n *\n * The `PROTOCOL_VERSION` encompasses both the wire-protocol of the `/sync/...`\n * connection between the browser and `zero-cache`, as well as the format of\n * the `AST` objects stored in both components (i.e. IDB and CVR).\n *\n * A change in the `AST` schema (e.g. new functionality added) must be\n * accompanied by an increment of the `PROTOCOL_VERSION` and a new major\n * release. The server (`zero-cache`) must be deployed before clients start\n * running the new code.\n */\n// History:\n// -- Version 5 adds support for `pokeEnd.cookie`. (0.14)\n// -- Version 6 makes `pokeStart.cookie` optional. (0.16)\n// -- Version 7 introduces the initConnection.clientSchema field. (0.17)\n// -- Version 8 drops support for Version 5 (0.18).\n// -- Version 11 adds inspect queries. (0.18)\n// -- Version 12 adds 'timestamp' and 'date' types to the ClientSchema ValueType. (not shipped, reversed by version 14)\n// -- Version 14 removes 'timestamp' and 'date' types from the ClientSchema ValueType. (0.18)\n// -- Version 15 adds a `userPushParams` field to `initConnection` (0.19)\n// -- Version 16 adds a new error type (alreadyProcessed) to mutation responses (0.19)\n// -- Version 17 deprecates `AST` in downstream query puts. It was never used anyway. (0.21)\n// -- Version 18 adds `name` and `args` to the `queries-patch` protocol (0.21)\n// -- Version 19 adds `activeClients` to the `initConnection` protocol (0.22)\n// -- Version 20 changes inspector down message (0.22)\n// -- Version 21 removes `AST` in downstream query puts which was deprecated in Version 17, removes support for versions < 18 (0.22)\n// -- Version 22 adds an optional 'userQueryParams' field to `initConnection` (0.22)\n// -- Version 23 add `mutationResults` to poke (0.22)\n// -- Version 24 adds `ackMutationResults` to upstream (0.22).\n// -- version 25 modifies `mutationsResults` to include `del` patches (0.22)\n// -- version 26 adds inspect/metrics and adds metrics to inspect/query (0.23)\n// -- version 27 adds inspect/version (0.23)\n// -- version 28 adds more inspect/metrics (0.23)\n// -- version 29 adds error responses for custom queries (0.23)\n// -- version 30 adds an optional primaryKey to the ClientSchema (0.24)\n// -- version 31 adds admin password authentication to inspector RPC calls (0.24)\n// -- version 32 adds analyze-query to the inspector RPC calls (0.24)\n// -- version 33 adds `flip` to CorrelatedSubquery (0.25)\n// -- version 34 moves `flip` from CorrelatedSubquery to CorrelatedSubqueryCondition (0.25)\n// -- version 35 adds `readRows`, `readRowCountsByQuery` and `readRowCount` to analyze-query result (0.25)\n// -- version 36 changes inspector analyze-query and adds error response to RPC (0.25)\n// -- version 37 adds `elapsed` to AnalyzeQueryResult (0.25)\n// -- version 38 adds structured push/transform error responses (0.25)\n// -- version 39 removes per-transform error types and adds `message` to app error (0.25)\n// -- version 40 adds `dbRowScansByQuery` to AnalyzeQueryResult (0.25)\n// -- version 41 makes ClientSchema.primaryKey required (0.25)\n// -- version 42 adds planner events to AnalyzeQueryResult (0.25)\n// -- version 43 renames `plans` to `sqlitePlans`, `plannerEvents` to `joinPlans`, and `plannerDebug` option to `joinPlans` (0.25)\n// -- version 44 adds profileID to connection URL (0.25)\n// -- version 45 adds userPushHeaders and userQueryHeaders to initConnection (0.25)\n// -- version 46 adds scalarSubquery condition type to AST\n// -- version 47 adds optional auth token to push body\n// -- version 48 adds updateAuth\n// -- version 49 adds `scalar` to CorrelatedSubqueryCondition, removes scalarSubquery\n// -- version 50 adds OTEL headers to push and query messages\n// -- version 51 changes inspector metrics fields\nexport const PROTOCOL_VERSION =
|
|
1
|
+
{"version":3,"file":"protocol-version.js","names":[],"sources":["../../../../zero-protocol/src/protocol-version.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\n\n/**\n * The current `PROTOCOL_VERSION` of the code.\n *\n * The `PROTOCOL_VERSION` encompasses both the wire-protocol of the `/sync/...`\n * connection between the browser and `zero-cache`, as well as the format of\n * the `AST` objects stored in both components (i.e. IDB and CVR).\n *\n * A change in the `AST` schema (e.g. new functionality added) must be\n * accompanied by an increment of the `PROTOCOL_VERSION` and a new major\n * release. The server (`zero-cache`) must be deployed before clients start\n * running the new code.\n */\n// History:\n// -- Version 5 adds support for `pokeEnd.cookie`. (0.14)\n// -- Version 6 makes `pokeStart.cookie` optional. (0.16)\n// -- Version 7 introduces the initConnection.clientSchema field. (0.17)\n// -- Version 8 drops support for Version 5 (0.18).\n// -- Version 11 adds inspect queries. (0.18)\n// -- Version 12 adds 'timestamp' and 'date' types to the ClientSchema ValueType. (not shipped, reversed by version 14)\n// -- Version 14 removes 'timestamp' and 'date' types from the ClientSchema ValueType. (0.18)\n// -- Version 15 adds a `userPushParams` field to `initConnection` (0.19)\n// -- Version 16 adds a new error type (alreadyProcessed) to mutation responses (0.19)\n// -- Version 17 deprecates `AST` in downstream query puts. It was never used anyway. (0.21)\n// -- Version 18 adds `name` and `args` to the `queries-patch` protocol (0.21)\n// -- Version 19 adds `activeClients` to the `initConnection` protocol (0.22)\n// -- Version 20 changes inspector down message (0.22)\n// -- Version 21 removes `AST` in downstream query puts which was deprecated in Version 17, removes support for versions < 18 (0.22)\n// -- Version 22 adds an optional 'userQueryParams' field to `initConnection` (0.22)\n// -- Version 23 add `mutationResults` to poke (0.22)\n// -- Version 24 adds `ackMutationResults` to upstream (0.22).\n// -- version 25 modifies `mutationsResults` to include `del` patches (0.22)\n// -- version 26 adds inspect/metrics and adds metrics to inspect/query (0.23)\n// -- version 27 adds inspect/version (0.23)\n// -- version 28 adds more inspect/metrics (0.23)\n// -- version 29 adds error responses for custom queries (0.23)\n// -- version 30 adds an optional primaryKey to the ClientSchema (0.24)\n// -- version 31 adds admin password authentication to inspector RPC calls (0.24)\n// -- version 32 adds analyze-query to the inspector RPC calls (0.24)\n// -- version 33 adds `flip` to CorrelatedSubquery (0.25)\n// -- version 34 moves `flip` from CorrelatedSubquery to CorrelatedSubqueryCondition (0.25)\n// -- version 35 adds `readRows`, `readRowCountsByQuery` and `readRowCount` to analyze-query result (0.25)\n// -- version 36 changes inspector analyze-query and adds error response to RPC (0.25)\n// -- version 37 adds `elapsed` to AnalyzeQueryResult (0.25)\n// -- version 38 adds structured push/transform error responses (0.25)\n// -- version 39 removes per-transform error types and adds `message` to app error (0.25)\n// -- version 40 adds `dbRowScansByQuery` to AnalyzeQueryResult (0.25)\n// -- version 41 makes ClientSchema.primaryKey required (0.25)\n// -- version 42 adds planner events to AnalyzeQueryResult (0.25)\n// -- version 43 renames `plans` to `sqlitePlans`, `plannerEvents` to `joinPlans`, and `plannerDebug` option to `joinPlans` (0.25)\n// -- version 44 adds profileID to connection URL (0.25)\n// -- version 45 adds userPushHeaders and userQueryHeaders to initConnection (0.25)\n// -- version 46 adds scalarSubquery condition type to AST\n// -- version 47 adds optional auth token to push body\n// -- version 48 adds updateAuth\n// -- version 49 adds `scalar` to CorrelatedSubqueryCondition, removes scalarSubquery\n// -- version 50 adds OTEL headers to push and query messages\n// -- version 51 changes inspector metrics fields\n// -- version 52 replaces JSON pokePart messages with binary poke chunks for\n// clients using protocol version 52 or newer. Older clients retain pokePart.\nexport const PROTOCOL_VERSION = 52;\n\n/**\n * The minimum server-supported sync protocol version (i.e. the version\n * declared in the \"/sync/v{#}/connect\" URL).\n *\n * CloudZero can serve applications running old client releases indefinitely.\n * Consequently, this value must never be increased: `zero-cache` must continue\n * to support every sync protocol from this version through `PROTOCOL_VERSION`.\n * A wire change that an old client cannot ignore must branch on the client's\n * protocol version and retain the old behavior. Keep each compatibility fork\n * isolated at the boundary that owns the changed behavior and test both sides\n * of its version cutoff.\n *\n * Client connections from protocol versions before this historical floor are\n * closed with a `VersionNotSupported` error.\n */\nexport const MIN_SERVER_SUPPORTED_SYNC_PROTOCOL = 30;\n\nassert(\n MIN_SERVER_SUPPORTED_SYNC_PROTOCOL < PROTOCOL_VERSION,\n 'MIN_SERVER_SUPPORTED_SYNC_PROTOCOL must be less than PROTOCOL_VERSION',\n);\n"],"mappings":";AAgFA,OAAA,MAEE,uEACF"}
|
|
@@ -56,6 +56,29 @@ export declare class TableBuilderWithColumns<TShape extends TableSchema> {
|
|
|
56
56
|
primaryKey<TPKColNames extends (keyof TShape['columns'])[]>(...pkColumnNames: TPKColNames): TableBuilderWithColumns<TShape & {
|
|
57
57
|
primaryKey: TPKColNames;
|
|
58
58
|
}>;
|
|
59
|
+
/**
|
|
60
|
+
* Declares that `columnNames` together are unique — mirroring a unique index
|
|
61
|
+
* that already exists upstream. Call once per index.
|
|
62
|
+
*
|
|
63
|
+
* Zero neither creates nor enforces the constraint; declaring it tells the
|
|
64
|
+
* type checker what the server already knows from the replica, which is what
|
|
65
|
+
* lets a `{scalar: true}` subquery pinned on these columns typecheck.
|
|
66
|
+
*
|
|
67
|
+
* The return type is spelled out so the column names stay literal — spreading
|
|
68
|
+
* the accumulated keys widens them to `PrimaryKey`, which loses exactly the
|
|
69
|
+
* information the check needs.
|
|
70
|
+
*/
|
|
71
|
+
unique<const TUniqueColNames extends [
|
|
72
|
+
keyof TShape['columns'] & string,
|
|
73
|
+
...(keyof TShape['columns'] & string)[]
|
|
74
|
+
]>(...columnNames: TUniqueColNames): TableBuilderWithColumns<Omit<TShape, 'uniqueKeys'> & {
|
|
75
|
+
uniqueKeys: [
|
|
76
|
+
...(TShape extends {
|
|
77
|
+
uniqueKeys: infer TExisting extends readonly PrimaryKey[];
|
|
78
|
+
} ? TExisting : []),
|
|
79
|
+
TUniqueColNames
|
|
80
|
+
];
|
|
81
|
+
}>;
|
|
59
82
|
get schema(): TShape;
|
|
60
83
|
build(): TShape;
|
|
61
84
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAEnE,OAAO,KAAK,EAAC,UAAU,EAAC,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Aa,CAAC,MAAM,SAAS,WAAW,CAAC,GAAG,CAAC;;gBAErC,MAAM,EAAE,MAAM;IAI1B,IAAI,CAAC,UAAU,SAAS,MAAM,EAAE,UAAU,EAAE,UAAU;oBACL,MAAM;;IAMvD,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG;QAAC,QAAQ,EAAE,IAAI,CAAA;KAAC,CAAC;IAOtE,IAAI,MAAM,WAET;CACF;AAED,YAAY,EAAC,aAAa,EAAC,CAAC"}
|
|
@@ -72,6 +72,24 @@ var TableBuilderWithColumns = class TableBuilderWithColumns {
|
|
|
72
72
|
primaryKey: pkColumnNames
|
|
73
73
|
});
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Declares that `columnNames` together are unique — mirroring a unique index
|
|
77
|
+
* that already exists upstream. Call once per index.
|
|
78
|
+
*
|
|
79
|
+
* Zero neither creates nor enforces the constraint; declaring it tells the
|
|
80
|
+
* type checker what the server already knows from the replica, which is what
|
|
81
|
+
* lets a `{scalar: true}` subquery pinned on these columns typecheck.
|
|
82
|
+
*
|
|
83
|
+
* The return type is spelled out so the column names stay literal — spreading
|
|
84
|
+
* the accumulated keys widens them to `PrimaryKey`, which loses exactly the
|
|
85
|
+
* information the check needs.
|
|
86
|
+
*/
|
|
87
|
+
unique(...columnNames) {
|
|
88
|
+
return new TableBuilderWithColumns({
|
|
89
|
+
...this.#schema,
|
|
90
|
+
uniqueKeys: [...this.#schema.uniqueKeys ?? [], columnNames]
|
|
91
|
+
});
|
|
92
|
+
}
|
|
75
93
|
get schema() {
|
|
76
94
|
return this.#schema;
|
|
77
95
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-builder.js","names":["#schema"],"sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"sourcesContent":["import type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {mapValues} from '../../../shared/src/objects.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue, TableSchema} from '../table-schema.ts';\n\n/* oxlint-disable @typescript-eslint/no-explicit-any */\nexport function table<TName extends string>(name: TName) {\n return new TableBuilder({\n name,\n columns: {},\n primaryKey: [] as any as PrimaryKey,\n });\n}\n\nexport function string<T extends string = string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function number<T extends number = number>() {\n return new ColumnBuilder({\n type: 'number',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function boolean<T extends boolean = boolean>() {\n return new ColumnBuilder({\n type: 'boolean',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function json<T extends ReadonlyJSONValue = ReadonlyJSONValue>() {\n return new ColumnBuilder({\n type: 'json',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function enumeration<T extends string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport const column = {\n string,\n number,\n boolean,\n json,\n enumeration,\n};\n\nexport class TableBuilder<TShape extends TableSchema> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new TableBuilder<TShape>({\n ...this.#schema,\n // Strip the \"public.\" schema if specified, as tables in the upstream\n // \"public\" schema are created without the schema prefix on the replica.\n // See liteTableName() in zero-cache/src/types/names.ts\n serverName: serverName.startsWith('public.')\n ? serverName.substring('public.'.length)\n : serverName,\n });\n }\n\n columns<const TColumns extends Record<string, ColumnBuilder<SchemaValue>>>(\n columns: TColumns,\n ): TableBuilderWithColumns<{\n name: TShape['name'];\n columns: {[K in keyof TColumns]: TColumns[K]['schema']};\n primaryKey: TShape['primaryKey'];\n }> {\n const columnSchemas = mapValues(columns, column => column.schema);\n return new TableBuilderWithColumns({\n ...this.#schema,\n columns: columnSchemas,\n }) as any;\n }\n}\n\nexport class TableBuilderWithColumns<TShape extends TableSchema> {\n readonly #schema: TShape;\n\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n primaryKey<TPKColNames extends (keyof TShape['columns'])[]>(\n ...pkColumnNames: TPKColNames\n ) {\n return new TableBuilderWithColumns({\n ...this.#schema,\n primaryKey: pkColumnNames,\n });\n }\n\n get schema() {\n return this.#schema;\n }\n\n build() {\n // We can probably get the type system to throw an error if primaryKey is not called\n // before passing the schema to createSchema\n // Till then --\n if (this.#schema.primaryKey.length === 0) {\n throw new Error(`Table \"${this.#schema.name}\" is missing a primary key`);\n }\n const names = new Set<string>();\n for (const [col, {serverName}] of Object.entries(this.#schema.columns)) {\n const name = serverName ?? col;\n if (names.has(name)) {\n throw new Error(\n `Table \"${\n this.#schema.name\n }\" has multiple columns referencing \"${name}\"`,\n );\n }\n names.add(name);\n }\n return this.#schema;\n }\n}\n\nclass ColumnBuilder<TShape extends SchemaValue<any>> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new ColumnBuilder<TShape & {serverName: string}>({\n ...this.#schema,\n serverName,\n });\n }\n\n optional(): ColumnBuilder<Omit<TShape, 'optional'> & {optional: true}> {\n return new ColumnBuilder({\n ...this.#schema,\n optional: true,\n });\n }\n\n get schema() {\n return this.#schema;\n }\n}\n\nexport type {ColumnBuilder};\n"],"mappings":";;AAMA,SAAgB,MAA4B,MAAa;CACvD,OAAO,IAAI,aAAa;EACtB;EACA,SAAS,CAAC;EACV,YAAY,CAAC;CACf,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,UAAuC;CACrD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAg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B;EAC1B,KAAKA,UAAU;CACjB;CAEA,KAAgC,YAAwB;EACtD,OAAO,IAAI,cAA6C;GACtD,GAAG,KAAKA;GACR;EACF,CAAC;CACH;CAEA,WAAuE;EACrE,OAAO,IAAI,cAAc;GACvB,GAAG,KAAKA;GACR,UAAU;EACZ,CAAC;CACH;CAEA,IAAI,SAAS;EACX,OAAO,KAAKA;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"table-builder.js","names":["#schema"],"sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"sourcesContent":["import type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {mapValues} from '../../../shared/src/objects.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue, TableSchema} from '../table-schema.ts';\n\n/* oxlint-disable @typescript-eslint/no-explicit-any */\nexport function table<TName extends string>(name: TName) {\n return new TableBuilder({\n name,\n columns: {},\n primaryKey: [] as any as PrimaryKey,\n });\n}\n\nexport function string<T extends string = string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function number<T extends number = number>() {\n return new ColumnBuilder({\n type: 'number',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function boolean<T extends boolean = boolean>() {\n return new ColumnBuilder({\n type: 'boolean',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function json<T extends ReadonlyJSONValue = ReadonlyJSONValue>() {\n return new ColumnBuilder({\n type: 'json',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function enumeration<T extends string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport const column = {\n string,\n number,\n boolean,\n json,\n enumeration,\n};\n\nexport class TableBuilder<TShape extends TableSchema> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new TableBuilder<TShape>({\n ...this.#schema,\n // Strip the \"public.\" schema if specified, as tables in the upstream\n // \"public\" schema are created without the schema prefix on the replica.\n // See liteTableName() in zero-cache/src/types/names.ts\n serverName: serverName.startsWith('public.')\n ? serverName.substring('public.'.length)\n : serverName,\n });\n }\n\n columns<const TColumns extends Record<string, ColumnBuilder<SchemaValue>>>(\n columns: TColumns,\n ): TableBuilderWithColumns<{\n name: TShape['name'];\n columns: {[K in keyof TColumns]: TColumns[K]['schema']};\n primaryKey: TShape['primaryKey'];\n }> {\n const columnSchemas = mapValues(columns, column => column.schema);\n return new TableBuilderWithColumns({\n ...this.#schema,\n columns: columnSchemas,\n }) as any;\n }\n}\n\nexport class TableBuilderWithColumns<TShape extends TableSchema> {\n readonly #schema: TShape;\n\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n primaryKey<TPKColNames extends (keyof TShape['columns'])[]>(\n ...pkColumnNames: TPKColNames\n ) {\n return new TableBuilderWithColumns({\n ...this.#schema,\n primaryKey: pkColumnNames,\n });\n }\n\n /**\n * Declares that `columnNames` together are unique — mirroring a unique index\n * that already exists upstream. Call once per index.\n *\n * Zero neither creates nor enforces the constraint; declaring it tells the\n * type checker what the server already knows from the replica, which is what\n * lets a `{scalar: true}` subquery pinned on these columns typecheck.\n *\n * The return type is spelled out so the column names stay literal — spreading\n * the accumulated keys widens them to `PrimaryKey`, which loses exactly the\n * information the check needs.\n */\n unique<\n const TUniqueColNames extends [\n keyof TShape['columns'] & string,\n ...(keyof TShape['columns'] & string)[],\n ],\n >(\n ...columnNames: TUniqueColNames\n ): TableBuilderWithColumns<\n Omit<TShape, 'uniqueKeys'> & {\n uniqueKeys: [\n ...(TShape extends {\n uniqueKeys: infer TExisting extends readonly PrimaryKey[];\n }\n ? TExisting\n : []),\n TUniqueColNames,\n ];\n }\n > {\n return new TableBuilderWithColumns({\n ...this.#schema,\n uniqueKeys: [...(this.#schema.uniqueKeys ?? []), columnNames],\n }) as any;\n }\n\n get schema() {\n return this.#schema;\n }\n\n build() {\n // We can probably get the type system to throw an error if primaryKey is not called\n // before passing the schema to createSchema\n // Till then --\n if (this.#schema.primaryKey.length === 0) {\n throw new Error(`Table \"${this.#schema.name}\" is missing a primary key`);\n }\n const names = new Set<string>();\n for (const [col, {serverName}] of Object.entries(this.#schema.columns)) {\n const name = serverName ?? col;\n if (names.has(name)) {\n throw new Error(\n `Table \"${\n this.#schema.name\n }\" has multiple columns referencing \"${name}\"`,\n );\n }\n names.add(name);\n }\n return this.#schema;\n }\n}\n\nclass ColumnBuilder<TShape extends SchemaValue<any>> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new ColumnBuilder<TShape & {serverName: string}>({\n ...this.#schema,\n serverName,\n });\n }\n\n optional(): ColumnBuilder<Omit<TShape, 'optional'> & {optional: true}> {\n return new ColumnBuilder({\n ...this.#schema,\n optional: true,\n });\n }\n\n get schema() {\n return this.#schema;\n }\n}\n\nexport type {ColumnBuilder};\n"],"mappings":";;AAMA,SAAgB,MAA4B,MAAa;CACvD,OAAO,IAAI,aAAa;EACtB;EACA,SAAS,CAAC;EACV,YAAY,CAAC;CACf,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,UAAuC;CACrD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,OAAwD;CACtE,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,cAAgC;CAC9C,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAUA,IAAa,eAAb,MAAa,aAAyC;CACpD;CACA,YAAY,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I,cAA6C;GACtD,GAAG,KAAKA;GACR;EACF,CAAC;CACH;CAEA,WAAuE;EACrE,OAAO,IAAI,cAAc;GACvB,GAAG,KAAKA;GACR,UAAU;EACZ,CAAC;CACH;CAEA,IAAI,SAAS;EACX,OAAO,KAAKA;CACd;AACF"}
|
|
@@ -162,7 +162,8 @@ function makeServerTableCRUD(schema) {
|
|
|
162
162
|
value = removeUndefined(value);
|
|
163
163
|
const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];
|
|
164
164
|
const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);
|
|
165
|
-
const
|
|
165
|
+
const primaryKeyColumns = origAndServerNamesFor(schema.primaryKey, schema);
|
|
166
|
+
const stmt = formatPgInternalConvert(sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(targetedColumns.map(([, serverName]) => sql.ident(serverName)), ",")}) VALUES (${sql.join(Object.entries(value).map(([col, v]) => sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)])), ", ")}) ON CONFLICT (${sql.join(primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)), ", ")}) DO NOTHING`);
|
|
166
167
|
await this[dbTxSymbol].query(stmt.text, stmt.values);
|
|
167
168
|
},
|
|
168
169
|
async upsert(value) {
|
|
@@ -170,13 +171,16 @@ function makeServerTableCRUD(schema) {
|
|
|
170
171
|
const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];
|
|
171
172
|
const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);
|
|
172
173
|
const primaryKeyColumns = origAndServerNamesFor(schema.primaryKey, schema);
|
|
173
|
-
const
|
|
174
|
+
const updatedEntries = nonPrimaryKeyEntries(value, schema);
|
|
175
|
+
const conflictAction = updatedEntries.length === 0 ? sql`DO NOTHING` : sql`DO UPDATE SET ${sql.join(updatedEntries.map(([col, val]) => sql`${sql.ident(schema.columns[col].serverName ?? col)} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`), ", ")}`;
|
|
176
|
+
const stmt = formatPgInternalConvert(sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(targetedColumns.map(([, serverName]) => sql.ident(serverName)), ",")}) VALUES (${sql.join(Object.entries(value).map(([col, val]) => sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])), ", ")}) ON CONFLICT (${sql.join(primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)), ", ")}) ${conflictAction}`);
|
|
174
177
|
await this[dbTxSymbol].query(stmt.text, stmt.values);
|
|
175
178
|
},
|
|
176
179
|
async update(value) {
|
|
177
180
|
value = removeUndefined(value);
|
|
178
181
|
const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];
|
|
179
|
-
const targetedColumns = origAndServerNamesFor(
|
|
182
|
+
const targetedColumns = origAndServerNamesFor(nonPrimaryKeyEntries(value, schema).map(([name]) => name), schema);
|
|
183
|
+
if (targetedColumns.length === 0) return;
|
|
180
184
|
const stmt = formatPgInternalConvert(sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(targetedColumns.map(([origName, serverName]) => sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`), ", ")} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`);
|
|
181
185
|
await this[dbTxSymbol].query(stmt.text, stmt.values);
|
|
182
186
|
},
|
|
@@ -188,6 +192,9 @@ function makeServerTableCRUD(schema) {
|
|
|
188
192
|
}
|
|
189
193
|
};
|
|
190
194
|
}
|
|
195
|
+
function nonPrimaryKeyEntries(value, schema) {
|
|
196
|
+
return Object.entries(value).filter(([name]) => !schema.primaryKey.includes(name));
|
|
197
|
+
}
|
|
191
198
|
function serverName(x) {
|
|
192
199
|
return x.serverName ?? x.name;
|
|
193
200
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#tableCRUDs","#getOrFetchServerSchema"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (tx: TDBTransaction, args: TArgs, ctx: Context) => Promise<void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n #serverSchema: ServerSchema | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n async #getOrFetchServerSchema(\n dbTransaction: DBTransaction<unknown>,\n ): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = await getServerSchema(dbTransaction, this.#schema);\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.#getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )})`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO UPDATE SET ${sql.join(\n Object.entries(value).map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2DA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC,UAAU;EACf,KAAKC,gBAAgB;CACvB;CAEA,YAAmB;EACjB,MAAM,IAAI,MAAM,iBAAiB;CACnC;CAEA,IAKE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAC7C,OAAO,KAAKF,eAAe,SACzB,eAAe,KACf,eAAe,QACf,KAAKC,SACL,KAAKC,aACP;CACF;CAEA,UAA0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AAO,IAAI;AACnE;AAEA,SAAS,eACP,OACA,oBACA;CACA,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,KAAK;AACpE"}
|
|
1
|
+
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#tableCRUDs","#getOrFetchServerSchema"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (tx: TDBTransaction, args: TArgs, ctx: Context) => Promise<void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n #serverSchema: ServerSchema | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n async #getOrFetchServerSchema(\n dbTransaction: DBTransaction<unknown>,\n ): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = await getServerSchema(dbTransaction, this.#schema);\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.#getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO NOTHING`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const updatedEntries = nonPrimaryKeyEntries(value, schema);\n const conflictAction =\n updatedEntries.length === 0\n ? sql`DO NOTHING`\n : sql`DO UPDATE SET ${sql.join(\n updatedEntries.map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`;\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) ${conflictAction}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(\n nonPrimaryKeyEntries(value, schema).map(([name]) => name),\n schema,\n );\n if (targetedColumns.length === 0) {\n return;\n }\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction nonPrimaryKeyEntries(\n value: Record<string, unknown>,\n schema: TableSchema,\n) {\n return Object.entries(value).filter(\n ([name]) => !schema.primaryKey.includes(name),\n );\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2DA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC,UAAU;EACf,KAAKC,gBAAgB;CACvB;CAEA,YAAmB;EACjB,MAAM,IAAI,MAAM,iBAAiB;CACnC;CAEA,IAKE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAC7C,OAAO,KAAKF,eAAe,SACzB,eAAe,KACf,eAAe,QACf,KAAKC,SACL,KAAKC,aACP;CACF;CAEA,UAA0B;EACxB,MAAM,IAAI,MAAM,mDAAmD;CACrE;CAEA,cAA8B;EAC5B,MAAM,IAAI,MAAM,uDAAuD;CACzE;AACF;AAEA,IAAa,kBAAb,MAG6D;CAC3D,WAAoB;CACpB,SAAkB;CAClB;CACA;CACA;CACA;;;;CAIA;CAEA;CACA;CAEA,YACE,eACA,UACA,YACA,QACA,QACA,cACA;EACA,KAAK,gBAAgB;EACrB,KAAK,WAAW;EAChB,KAAK,aAAa;EAClB,KAAK,SAAS;EACd,KAAKD,UAAU;EACf,KAAKC,gBAAgB;EAErB,MAAM,WAAW,IAAI,+BACnB,eACA,QACA,YACF;EACA,KAAK,QAAQ,sBAAsB,UAAU,MAAM;CACrD;CAEA,IACE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAG7C,OAAO,KAAK,cAAc,SACxB,eAAe,KACf,eAAe,QACf,KAAKD,SACL,KAAKC,aACP;CACF;AAC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ServerSchema } from '../../zero-types/src/server-schema.ts';
|
|
3
3
|
import type { DBTransaction } from '../../zql/src/mutate/custom.ts';
|
|
4
4
|
export declare function getServerSchema<S extends Schema>(dbTransaction: DBTransaction<unknown>, schema: S): Promise<ServerSchema>;
|
|
5
|
+
/**
|
|
6
|
+
* The query behind {@linkcode getServerSchema}, exported so that it can be
|
|
7
|
+
* diffed against the `information_schema` query it replaced.
|
|
8
|
+
*/
|
|
9
|
+
export declare function serverSchemaQuery(schemaTablePairs: readonly (readonly [string, string])[]): {
|
|
10
|
+
text: string;
|
|
11
|
+
values: unknown[];
|
|
12
|
+
};
|
|
5
13
|
export type SchemaIncompatibilityError = {
|
|
6
14
|
type: 'typeError';
|
|
7
15
|
table: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../../zero-server/src/schema.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAC3D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,uCAAuC,CAAC;AACxE,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,gCAAgC,CAAC;AAkBlE,wBAAsB,eAAe,CAAC,CAAC,SAAS,MAAM,EACpD,aAAa,EAAE,aAAa,CAAC,OAAO,CAAC,EACrC,MAAM,EAAE,CAAC,GACR,OAAO,CAAC,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../../zero-server/src/schema.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAC3D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,uCAAuC,CAAC;AACxE,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,gCAAgC,CAAC;AAkBlE,wBAAsB,eAAe,CAAC,CAAC,SAAS,MAAM,EACpD,aAAa,EAAE,aAAa,CAAC,OAAO,CAAC,EACrC,MAAM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