@rocicorp/zero 1.2.0-canary.1 → 1.2.0-canary.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/out/analyze-query/src/bin-analyze.js +25 -25
  2. package/out/analyze-query/src/bin-analyze.js.map +1 -1
  3. package/out/ast-to-zql/src/ast-to-zql.d.ts.map +1 -1
  4. package/out/ast-to-zql/src/ast-to-zql.js +2 -1
  5. package/out/ast-to-zql/src/ast-to-zql.js.map +1 -1
  6. package/out/ast-to-zql/src/format.d.ts.map +1 -1
  7. package/out/ast-to-zql/src/format.js +6 -6
  8. package/out/ast-to-zql/src/format.js.map +1 -1
  9. package/out/replicache/src/btree/node.d.ts.map +1 -1
  10. package/out/replicache/src/btree/node.js +2 -2
  11. package/out/replicache/src/btree/node.js.map +1 -1
  12. package/out/replicache/src/connection-loop.js +3 -3
  13. package/out/replicache/src/connection-loop.js.map +1 -1
  14. package/out/replicache/src/deleted-clients.d.ts +0 -4
  15. package/out/replicache/src/deleted-clients.d.ts.map +1 -1
  16. package/out/replicache/src/deleted-clients.js +1 -1
  17. package/out/replicache/src/deleted-clients.js.map +1 -1
  18. package/out/replicache/src/hash.d.ts.map +1 -1
  19. package/out/replicache/src/hash.js.map +1 -1
  20. package/out/replicache/src/process-scheduler.d.ts.map +1 -1
  21. package/out/replicache/src/process-scheduler.js.map +1 -1
  22. package/out/replicache/src/request-idle.js +1 -1
  23. package/out/replicache/src/request-idle.js.map +1 -1
  24. package/out/replicache/src/sync/patch.d.ts +1 -1
  25. package/out/replicache/src/sync/patch.d.ts.map +1 -1
  26. package/out/replicache/src/sync/patch.js +1 -1
  27. package/out/replicache/src/sync/patch.js.map +1 -1
  28. package/out/shared/src/arrays.d.ts.map +1 -1
  29. package/out/shared/src/arrays.js +1 -2
  30. package/out/shared/src/arrays.js.map +1 -1
  31. package/out/shared/src/bigint-json.d.ts.map +1 -1
  32. package/out/shared/src/bigint-json.js +1 -1
  33. package/out/shared/src/bigint-json.js.map +1 -1
  34. package/out/shared/src/btree-set.d.ts.map +1 -1
  35. package/out/shared/src/btree-set.js +74 -42
  36. package/out/shared/src/btree-set.js.map +1 -1
  37. package/out/shared/src/iterables.d.ts +7 -0
  38. package/out/shared/src/iterables.d.ts.map +1 -1
  39. package/out/shared/src/iterables.js +10 -1
  40. package/out/shared/src/iterables.js.map +1 -1
  41. package/out/shared/src/logging.d.ts.map +1 -1
  42. package/out/shared/src/logging.js +10 -9
  43. package/out/shared/src/logging.js.map +1 -1
  44. package/out/shared/src/options.js +1 -1
  45. package/out/shared/src/options.js.map +1 -1
  46. package/out/shared/src/tdigest-schema.d.ts.map +1 -1
  47. package/out/shared/src/tdigest-schema.js.map +1 -1
  48. package/out/shared/src/tdigest.d.ts.map +1 -1
  49. package/out/shared/src/tdigest.js +7 -7
  50. package/out/shared/src/tdigest.js.map +1 -1
  51. package/out/shared/src/valita.d.ts.map +1 -1
  52. package/out/shared/src/valita.js +1 -1
  53. package/out/shared/src/valita.js.map +1 -1
  54. package/out/z2s/src/sql.d.ts +2 -2
  55. package/out/z2s/src/sql.d.ts.map +1 -1
  56. package/out/z2s/src/sql.js +4 -4
  57. package/out/z2s/src/sql.js.map +1 -1
  58. package/out/zero/package.js +9 -10
  59. package/out/zero/package.js.map +1 -1
  60. package/out/zero/src/pg.js +1 -1
  61. package/out/zero/src/server.js +1 -1
  62. package/out/zero-cache/src/auth/load-permissions.d.ts +2 -2
  63. package/out/zero-cache/src/auth/load-permissions.d.ts.map +1 -1
  64. package/out/zero-cache/src/auth/load-permissions.js +1 -1
  65. package/out/zero-cache/src/auth/load-permissions.js.map +1 -1
  66. package/out/zero-cache/src/config/zero-config.d.ts +17 -1
  67. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  68. package/out/zero-cache/src/config/zero-config.js +37 -3
  69. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  70. package/out/zero-cache/src/custom/fetch.d.ts +1 -1
  71. package/out/zero-cache/src/custom/fetch.d.ts.map +1 -1
  72. package/out/zero-cache/src/custom/fetch.js +2 -0
  73. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  74. package/out/zero-cache/src/custom-queries/transform-query.d.ts.map +1 -1
  75. package/out/zero-cache/src/custom-queries/transform-query.js +5 -2
  76. package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
  77. package/out/zero-cache/src/db/migration-lite.d.ts.map +1 -1
  78. package/out/zero-cache/src/db/migration-lite.js +1 -1
  79. package/out/zero-cache/src/db/migration-lite.js.map +1 -1
  80. package/out/zero-cache/src/db/migration.d.ts.map +1 -1
  81. package/out/zero-cache/src/db/migration.js +1 -1
  82. package/out/zero-cache/src/db/migration.js.map +1 -1
  83. package/out/zero-cache/src/db/pg-copy-binary.d.ts +101 -0
  84. package/out/zero-cache/src/db/pg-copy-binary.d.ts.map +1 -0
  85. package/out/zero-cache/src/db/pg-copy-binary.js +381 -0
  86. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -0
  87. package/out/zero-cache/src/db/run-transaction.d.ts.map +1 -1
  88. package/out/zero-cache/src/db/run-transaction.js +2 -2
  89. package/out/zero-cache/src/db/run-transaction.js.map +1 -1
  90. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  91. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  92. package/out/zero-cache/src/db/warmup.d.ts.map +1 -1
  93. package/out/zero-cache/src/db/warmup.js +3 -1
  94. package/out/zero-cache/src/db/warmup.js.map +1 -1
  95. package/out/zero-cache/src/observability/metrics.d.ts +1 -1
  96. package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
  97. package/out/zero-cache/src/observability/metrics.js.map +1 -1
  98. package/out/zero-cache/src/server/anonymous-otel-start.d.ts.map +1 -1
  99. package/out/zero-cache/src/server/anonymous-otel-start.js +8 -2
  100. package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
  101. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  102. package/out/zero-cache/src/server/change-streamer.js +3 -1
  103. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  104. package/out/zero-cache/src/server/logging.d.ts.map +1 -1
  105. package/out/zero-cache/src/server/logging.js +9 -1
  106. package/out/zero-cache/src/server/logging.js.map +1 -1
  107. package/out/zero-cache/src/server/main.js +1 -1
  108. package/out/zero-cache/src/server/main.js.map +1 -1
  109. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  110. package/out/zero-cache/src/server/replicator.js +28 -1
  111. package/out/zero-cache/src/server/replicator.js.map +1 -1
  112. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  113. package/out/zero-cache/src/server/syncer.js +8 -10
  114. package/out/zero-cache/src/server/syncer.js.map +1 -1
  115. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
  116. package/out/zero-cache/src/server/worker-urls.js +2 -1
  117. package/out/zero-cache/src/server/worker-urls.js.map +1 -1
  118. package/out/zero-cache/src/services/change-source/change-source.d.ts +5 -1
  119. package/out/zero-cache/src/services/change-source/change-source.d.ts.map +1 -1
  120. package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
  121. package/out/zero-cache/src/services/change-source/common/replica-schema.js +13 -1
  122. package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
  123. package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
  124. package/out/zero-cache/src/services/change-source/custom/change-source.js +7 -4
  125. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  126. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  127. package/out/zero-cache/src/services/change-source/pg/change-source.js +74 -23
  128. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  129. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +1 -0
  130. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  131. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +85 -5
  132. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  133. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +1 -1
  134. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +1 -1
  135. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  136. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +1 -1
  137. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
  138. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +31 -1
  139. package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
  140. package/out/zero-cache/src/services/change-streamer/broadcast.js +1 -1
  141. package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
  142. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +1 -1
  143. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +3 -3
  144. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  145. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +4 -0
  146. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  147. package/out/zero-cache/src/services/change-streamer/change-streamer.js +9 -1
  148. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  149. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  150. package/out/zero-cache/src/services/change-streamer/storer.js +1 -1
  151. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  152. package/out/zero-cache/src/services/life-cycle.d.ts +1 -0
  153. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  154. package/out/zero-cache/src/services/life-cycle.js +2 -2
  155. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  156. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  157. package/out/zero-cache/src/services/litestream/commands.js +5 -5
  158. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  159. package/out/zero-cache/src/services/mutagen/pusher.d.ts +2 -2
  160. package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
  161. package/out/zero-cache/src/services/mutagen/pusher.js +7 -4
  162. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  163. package/out/zero-cache/src/services/replicator/change-processor.js +1 -1
  164. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  165. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  166. package/out/zero-cache/src/services/replicator/incremental-sync.js +6 -3
  167. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  168. package/out/zero-cache/src/services/replicator/replication-status.js.map +1 -1
  169. package/out/zero-cache/src/services/replicator/schema/column-metadata.d.ts +1 -1
  170. package/out/zero-cache/src/services/replicator/schema/column-metadata.d.ts.map +1 -1
  171. package/out/zero-cache/src/services/replicator/schema/column-metadata.js.map +1 -1
  172. package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts.map +1 -1
  173. package/out/zero-cache/src/services/replicator/schema/replication-state.js +6 -3
  174. package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
  175. package/out/zero-cache/src/services/view-syncer/client-schema.d.ts.map +1 -1
  176. package/out/zero-cache/src/services/view-syncer/client-schema.js +4 -3
  177. package/out/zero-cache/src/services/view-syncer/client-schema.js.map +1 -1
  178. package/out/zero-cache/src/services/view-syncer/cvr-store.js +2 -2
  179. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  180. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  181. package/out/zero-cache/src/services/view-syncer/cvr.js +12 -9
  182. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  183. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +1 -1
  184. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  185. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +3 -1
  186. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  187. package/out/zero-cache/src/services/view-syncer/row-record-cache.d.ts.map +1 -1
  188. package/out/zero-cache/src/services/view-syncer/row-record-cache.js +13 -7
  189. package/out/zero-cache/src/services/view-syncer/row-record-cache.js.map +1 -1
  190. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +1 -1
  191. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  192. package/out/zero-cache/src/services/view-syncer/snapshotter.js +1 -1
  193. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  194. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  195. package/out/zero-cache/src/services/view-syncer/view-syncer.js +34 -15
  196. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  197. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  198. package/out/zero-cache/src/types/lite.js +3 -2
  199. package/out/zero-cache/src/types/lite.js.map +1 -1
  200. package/out/zero-cache/src/types/pg-types.js +4 -1
  201. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  202. package/out/zero-cache/src/types/pg.d.ts +1 -0
  203. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  204. package/out/zero-cache/src/types/pg.js +26 -10
  205. package/out/zero-cache/src/types/pg.js.map +1 -1
  206. package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
  207. package/out/zero-cache/src/types/subscription.js +2 -2
  208. package/out/zero-cache/src/types/subscription.js.map +1 -1
  209. package/out/zero-cache/src/workers/connection.js.map +1 -1
  210. package/out/zero-cache/src/workers/replicator.d.ts +5 -2
  211. package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
  212. package/out/zero-cache/src/workers/replicator.js +10 -6
  213. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  214. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts +1 -1
  215. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
  216. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +18 -2
  217. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  218. package/out/zero-cache/src/workers/syncer.d.ts +1 -1
  219. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  220. package/out/zero-cache/src/workers/syncer.js +5 -5
  221. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  222. package/out/zero-client/src/client/http-string.d.ts.map +1 -1
  223. package/out/zero-client/src/client/http-string.js.map +1 -1
  224. package/out/zero-client/src/client/metrics.d.ts.map +1 -1
  225. package/out/zero-client/src/client/metrics.js +2 -1
  226. package/out/zero-client/src/client/metrics.js.map +1 -1
  227. package/out/zero-client/src/client/server-option.js +1 -1
  228. package/out/zero-client/src/client/server-option.js.map +1 -1
  229. package/out/zero-client/src/client/version.js +1 -1
  230. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  231. package/out/zero-client/src/client/zero-poke-handler.js +7 -3
  232. package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
  233. package/out/zero-pg/src/mod.js +1 -1
  234. package/out/zero-protocol/src/application-error.d.ts +1 -1
  235. package/out/zero-protocol/src/application-error.d.ts.map +1 -1
  236. package/out/zero-protocol/src/application-error.js.map +1 -1
  237. package/out/zero-protocol/src/ast.d.ts.map +1 -1
  238. package/out/zero-protocol/src/ast.js.map +1 -1
  239. package/out/zero-protocol/src/primary-key.d.ts.map +1 -1
  240. package/out/zero-protocol/src/primary-key.js.map +1 -1
  241. package/out/zero-protocol/src/push.d.ts.map +1 -1
  242. package/out/zero-protocol/src/push.js.map +1 -1
  243. package/out/zero-schema/src/name-mapper.js +1 -1
  244. package/out/zero-schema/src/name-mapper.js.map +1 -1
  245. package/out/zero-server/src/mod.js +1 -1
  246. package/out/zero-server/src/process-mutations.d.ts.map +1 -1
  247. package/out/zero-server/src/process-mutations.js +2 -1
  248. package/out/zero-server/src/process-mutations.js.map +1 -1
  249. package/out/zero-server/src/push-processor.d.ts +1 -0
  250. package/out/zero-server/src/push-processor.d.ts.map +1 -1
  251. package/out/zero-server/src/push-processor.js +3 -2
  252. package/out/zero-server/src/push-processor.js.map +1 -1
  253. package/out/zero-types/src/name-mapper.d.ts +1 -0
  254. package/out/zero-types/src/name-mapper.d.ts.map +1 -1
  255. package/out/zero-types/src/name-mapper.js +3 -0
  256. package/out/zero-types/src/name-mapper.js.map +1 -1
  257. package/out/zql/src/builder/builder.d.ts.map +1 -1
  258. package/out/zql/src/builder/builder.js +5 -15
  259. package/out/zql/src/builder/builder.js.map +1 -1
  260. package/out/zql/src/builder/like.js +2 -1
  261. package/out/zql/src/builder/like.js.map +1 -1
  262. package/out/zql/src/ivm/data.d.ts.map +1 -1
  263. package/out/zql/src/ivm/data.js +6 -15
  264. package/out/zql/src/ivm/data.js.map +1 -1
  265. package/out/zql/src/ivm/memory-source.d.ts +1 -1
  266. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  267. package/out/zql/src/ivm/memory-source.js +4 -6
  268. package/out/zql/src/ivm/memory-source.js.map +1 -1
  269. package/out/zql/src/ivm/take.d.ts.map +1 -1
  270. package/out/zql/src/ivm/take.js +2 -2
  271. package/out/zql/src/ivm/take.js.map +1 -1
  272. package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
  273. package/out/zql/src/ivm/view-apply-change.js +34 -26
  274. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  275. package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
  276. package/out/zql/src/planner/planner-debug.js.map +1 -1
  277. package/out/zql/src/query/complete-ordering.js +1 -1
  278. package/out/zql/src/query/complete-ordering.js.map +1 -1
  279. package/out/zql/src/query/expression.d.ts +1 -1
  280. package/out/zql/src/query/expression.d.ts.map +1 -1
  281. package/out/zql/src/query/expression.js.map +1 -1
  282. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  283. package/out/zql/src/query/query-impl.js +2 -2
  284. package/out/zql/src/query/query-impl.js.map +1 -1
  285. package/out/zql/src/query/query-registry.d.ts.map +1 -1
  286. package/out/zql/src/query/query-registry.js +2 -1
  287. package/out/zql/src/query/query-registry.js.map +1 -1
  288. package/out/zql/src/query/query.d.ts +1 -2
  289. package/out/zql/src/query/query.d.ts.map +1 -1
  290. package/out/zql/src/query/ttl.js +1 -1
  291. package/out/zql/src/query/ttl.js.map +1 -1
  292. package/out/zqlite/src/internal/sql.d.ts +2 -2
  293. package/out/zqlite/src/internal/sql.d.ts.map +1 -1
  294. package/out/zqlite/src/internal/sql.js +1 -2
  295. package/out/zqlite/src/internal/sql.js.map +1 -1
  296. package/out/zqlite/src/sqlite-cost-model.d.ts +1 -1
  297. package/out/zqlite/src/sqlite-cost-model.d.ts.map +1 -1
  298. package/out/zqlite/src/sqlite-cost-model.js +1 -1
  299. package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
  300. package/out/zqlite/src/sqlite-stat-fanout.js +1 -1
  301. package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
  302. package/out/zqlite/src/table-source.d.ts.map +1 -1
  303. package/out/zqlite/src/table-source.js +8 -12
  304. package/out/zqlite/src/table-source.js.map +1 -1
  305. package/package.json +9 -10
  306. package/out/zql/src/ivm/cap.d.ts +0 -32
  307. package/out/zql/src/ivm/cap.d.ts.map +0 -1
  308. package/out/zql/src/ivm/cap.js +0 -226
  309. package/out/zql/src/ivm/cap.js.map +0 -1
@@ -1,8 +1,8 @@
1
1
  import "../../zero-protocol/src/application-error.js";
2
2
  import "../../zero-server/src/custom.js";
3
3
  import "../../zero-server/src/pg-query-executor.js";
4
- import "../../zero-server/src/process-mutations.js";
5
4
  import "../../zero-server/src/push-processor.js";
5
+ import "../../zero-server/src/process-mutations.js";
6
6
  import "../../zero-server/src/queries/process-queries.js";
7
7
  import "../../zero-server/src/zql-database.js";
8
8
  import "../../zero-server/src/mod.js";
@@ -18,7 +18,7 @@ export interface ApplicationErrorOptions<T extends ReadonlyJSONValue | undefined
18
18
  */
19
19
  export declare class ApplicationError<const T extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined> extends Error {
20
20
  #private;
21
- constructor(message: string, options?: ApplicationErrorOptions<T> | undefined);
21
+ constructor(message: string, options?: ApplicationErrorOptions<T>);
22
22
  get details(): T;
23
23
  get kind(): 'Application';
24
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"application-error.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/application-error.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAEhE;;;;;GAKG;AACH,MAAM,WAAW,uBAAuB,CACtC,CAAC,SAAS,iBAAiB,GAAG,SAAS;IAEvC,OAAO,CAAC,EAAE,CAAC,CAAC;IACZ,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;GAMG;AACH,qBAAa,gBAAgB,CAC3B,KAAK,CAAC,CAAC,SAAS,iBAAiB,GAAG,SAAS,GAAG,iBAAiB,GAAG,SAAS,CAC7E,SAAQ,KAAK;;gBAOX,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,SAAS;IAOlD,IAAI,OAAO,IAAI,CAAC,CAEf;IAED,IAAI,IAAI,IAAI,aAAa,CAExB;CACF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAE5E;AAED,wBAAgB,wBAAwB,CACtC,CAAC,SAAS,iBAAiB,GAAG,SAAS,GAAG,iBAAiB,GAAG,SAAS,EACvE,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAYrC"}
1
+ {"version":3,"file":"application-error.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/application-error.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAEhE;;;;;GAKG;AACH,MAAM,WAAW,uBAAuB,CACtC,CAAC,SAAS,iBAAiB,GAAG,SAAS;IAEvC,OAAO,CAAC,EAAE,CAAC,CAAC;IACZ,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;GAMG;AACH,qBAAa,gBAAgB,CAC3B,KAAK,CAAC,CAAC,SAAS,iBAAiB,GAAG,SAAS,GAAG,iBAAiB,GAAG,SAAS,CAC7E,SAAQ,KAAK;;gBAMD,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,uBAAuB,CAAC,CAAC,CAAC;IAMjE,IAAI,OAAO,IAAI,CAAC,CAEf;IAED,IAAI,IAAI,IAAI,aAAa,CAExB;CACF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAE5E;AAED,wBAAgB,wBAAwB,CACtC,CAAC,SAAS,iBAAiB,GAAG,SAAS,GAAG,iBAAiB,GAAG,SAAS,EACvE,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAYrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"application-error.js","names":["#details"],"sources":["../../../../zero-protocol/src/application-error.ts"],"sourcesContent":["import {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\n\n/**\n * Options accepted by {@link ApplicationError}.\n *\n * Use these when you need to attach additional context to an error that will\n * be sent back to the client.\n */\nexport interface ApplicationErrorOptions<\n T extends ReadonlyJSONValue | undefined,\n> {\n details?: T;\n cause?: unknown;\n}\n\n/**\n * Error type that application code can throw to surface structured metadata back to\n * the client.\n *\n * Use this when you want to return a descriptive message along with the\n * JSON-serializable `details`.\n */\nexport class ApplicationError<\n const T extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n> extends Error {\n /**\n * This maps onto errors for transform and push app-level failures.\n */\n readonly #details: T;\n\n constructor(\n message: string,\n options?: ApplicationErrorOptions<T> | undefined,\n ) {\n super(message, {cause: options?.cause});\n this.name = 'ApplicationError';\n this.#details = options?.details ?? (undefined as T);\n }\n\n get details(): T {\n return this.#details;\n }\n\n get kind(): 'Application' {\n return 'Application';\n }\n}\n\nexport function isApplicationError(error: unknown): error is ApplicationError {\n return error instanceof ApplicationError;\n}\n\nexport function wrapWithApplicationError<\n T extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n>(error: unknown): ApplicationError<T> {\n if (isApplicationError(error)) {\n return error as ApplicationError<T>;\n }\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return new ApplicationError<T>(message, {\n cause: error,\n details: details as T,\n });\n}\n"],"mappings":";;;;;;;;;AAuBA,IAAa,mBAAb,cAEU,MAAM;;;;CAId;CAEA,YACE,SACA,SACA;AACA,QAAM,SAAS,EAAC,OAAO,SAAS,OAAM,CAAC;AACvC,OAAK,OAAO;AACZ,QAAA,UAAgB,SAAS,WAAY,KAAA;;CAGvC,IAAI,UAAa;AACf,SAAO,MAAA;;CAGT,IAAI,OAAsB;AACxB,SAAO;;;AAIX,SAAgB,mBAAmB,OAA2C;AAC5E,QAAO,iBAAiB;;AAG1B,SAAgB,yBAEd,OAAqC;AACrC,KAAI,mBAAmB,MAAM,CAC3B,QAAO;AAMT,QAAO,IAAI,iBAHK,gBAAgB,MAAM,EAGE;EACtC,OAAO;EACE,SAJK,gBAAgB,MAAM;EAKrC,CAAC"}
1
+ {"version":3,"file":"application-error.js","names":["#details"],"sources":["../../../../zero-protocol/src/application-error.ts"],"sourcesContent":["import {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\n\n/**\n * Options accepted by {@link ApplicationError}.\n *\n * Use these when you need to attach additional context to an error that will\n * be sent back to the client.\n */\nexport interface ApplicationErrorOptions<\n T extends ReadonlyJSONValue | undefined,\n> {\n details?: T;\n cause?: unknown;\n}\n\n/**\n * Error type that application code can throw to surface structured metadata back to\n * the client.\n *\n * Use this when you want to return a descriptive message along with the\n * JSON-serializable `details`.\n */\nexport class ApplicationError<\n const T extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n> extends Error {\n /**\n * This maps onto errors for transform and push app-level failures.\n */\n readonly #details: T;\n\n constructor(message: string, options?: ApplicationErrorOptions<T>) {\n super(message, {cause: options?.cause});\n this.name = 'ApplicationError';\n this.#details = options?.details ?? (undefined as T);\n }\n\n get details(): T {\n return this.#details;\n }\n\n get kind(): 'Application' {\n return 'Application';\n }\n}\n\nexport function isApplicationError(error: unknown): error is ApplicationError {\n return error instanceof ApplicationError;\n}\n\nexport function wrapWithApplicationError<\n T extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n>(error: unknown): ApplicationError<T> {\n if (isApplicationError(error)) {\n return error as ApplicationError<T>;\n }\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return new ApplicationError<T>(message, {\n cause: error,\n details: details as T,\n });\n}\n"],"mappings":";;;;;;;;;AAuBA,IAAa,mBAAb,cAEU,MAAM;;;;CAId;CAEA,YAAY,SAAiB,SAAsC;AACjE,QAAM,SAAS,EAAC,OAAO,SAAS,OAAM,CAAC;AACvC,OAAK,OAAO;AACZ,QAAA,UAAgB,SAAS,WAAY,KAAA;;CAGvC,IAAI,UAAa;AACf,SAAO,MAAA;;CAGT,IAAI,OAAsB;AACxB,SAAO;;;AAIX,SAAgB,mBAAmB,OAA2C;AAC5E,QAAO,iBAAiB;;AAG1B,SAAgB,yBAEd,OAAqC;AACrC,KAAI,mBAAmB,MAAM,CAC3B,QAAO;AAMT,QAAO,IAAI,iBAHK,gBAAgB,MAAM,EAGE;EACtC,OAAO;EACE,SAJK,gBAAgB,MAAM;EAKrC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAChD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAY,KAAK,GAAG,EAAC,MAAM,WAAW,CAAC;AAE9C,eAAO,MAAM,WAA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,UAAU,EAAE,SAAS,SAAS,EAAE,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,EAAE,IAAI,CAAC;IACX,UAAU,EAAE,SAAS,SAAS,EAAE,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,OAAO,EAAE,kBAAkB,CAAC;IAC5B,EAAE,EAAE,mCAAmC,CAAC;IACxC,IAAI,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC,YAAY,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,mCAAmC,GAAG,QAAQ,GAAG,YAAY,CAAC;AA6G1E,wBAAgB,YAAY,CAAC,GAAG,EAAE,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAOpD;AAED,wBAAgB,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,iBAQlD;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,UAAU,aASnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"ast.js","names":[],"sources":["../../../../zero-protocol/src/ast.ts"],"sourcesContent":["/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {defined} from '../../shared/src/arrays.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\nexport const planIdSymbol = Symbol('planId');\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.literalUnion('asc', 'desc')]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client' | 'test';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.literalUnion('=', '!=', 'IS', 'IS NOT');\n\nexport const orderOpsSchema = v.literalUnion('<', '>', '<=', '>=');\n\nexport const likeOpsSchema = v.literalUnion(\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n);\n\nexport const inOpsSchema = v.literalUnion('IN', 'NOT IN');\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.literalUnion('authData', 'preMutationRow'),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.literalUnion('EXISTS', 'NOT EXISTS');\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n flip: v.boolean().optional(),\n scalar: v.boolean().optional(),\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(\n Array.isArray(field) && field.length >= 1,\n 'Expected non-empty array for compound key',\n );\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n flip?: boolean | undefined;\n scalar?: boolean | undefined;\n [planIdSymbol]?: number | undefined;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n related(subqueries: CorrelatedSubquery[]): readonly CorrelatedSubquery[];\n where(cond: Condition): Condition | undefined;\n // conjunction or disjunction, called when traversing the return value of where()\n conditions(conds: Condition[]): readonly Condition[];\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const where = ast.where ? transform.where(ast.where) : undefined;\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: where ? transformWhere(where, ast.table, transform) : undefined,\n related: ast.related\n ? transform.related(\n ast.related.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n )\n : undefined,\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: transform.conditions(\n where.conditions.map(c => transformWhere(c, table, transform)),\n ),\n };\n}\n\nconst normalizeCache = new WeakMap<AST, Required<AST>>();\n\nconst NORMALIZE_TRANSFORM: ASTTransform = {\n tableName: t => t,\n columnName: (_, c) => c,\n related: sortedRelated,\n where: flattened,\n conditions: c => c.sort(cmpCondition),\n};\n\nexport function normalizeAST(ast: AST): Required<AST> {\n let normalized = normalizeCache.get(ast);\n if (!normalized) {\n normalized = transformAST(ast, NORMALIZE_TRANSFORM);\n normalizeCache.set(ast, normalized);\n }\n return normalized;\n}\n\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nfunction sortedRelated(\n related: CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n return related.sort(cmpRelated);\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return (\n cmpRelated(a.related, b.related) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n cmpOptionalBool(a.flip, b.flip) ||\n cmpOptionalBool(a.scalar, b.scalar)\n );\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal', 'Expected literal type for comparison');\n return compareUTF8(String(a.value), String(b.value));\n case 'column':\n assert(b.type === 'column', 'Expected column type for comparison');\n return compareUTF8(a.name, b.name);\n case 'static':\n throw new Error(\n 'Static parameters should be resolved before normalization',\n );\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\n/**\n * Returns a flattened version of the Conditions in which nested Conjunctions with\n * the same operation ('AND' or 'OR') are flattened to the same level. e.g.\n *\n * ```\n * ((a AND b) AND (c AND (d OR (e OR f)))) -> (a AND b AND c AND (d OR e OR f))\n * ```\n *\n * Also flattens singleton Conjunctions regardless of operator, and removes\n * empty Conjunctions.\n */\nfunction flattened(cond: Condition): Condition | undefined {\n if (cond.type === 'simple' || cond.type === 'correlatedSubquery') {\n return cond;\n }\n const conditions = defined(\n cond.conditions.flatMap(c =>\n c.type === cond.type ? c.conditions.map(c => flattened(c)) : flattened(c),\n ),\n );\n\n switch (conditions.length) {\n case 0:\n return undefined;\n case 1:\n return conditions[0];\n default:\n return {\n type: cond.type,\n conditions,\n };\n }\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n\nfunction cmpOptionalBool(\n a: boolean | undefined,\n b: boolean | undefined,\n): number {\n // undefined < false < true\n const toNum = (v: boolean | undefined) => (v === undefined ? 0 : v ? 2 : 1);\n return toNum(a) - toNum(b);\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAa,cAAc;AAE3B,IAAa,iBAAiB,eAAE,QAAQ;AACxC,IAAa,gBAAgB,QAAQ;AACrC,IAAa,eAAe,OAAO,SAAS;AAM5C,IAAa,iBAAiB,cAJA,SAC5B,eAAE,MAAM,CAAC,gBAAgB,aAAe,OAAO,OAAO,CAAC,CAAC,CACzD,CAEmE;AAGrC,eAAE,MAC/B,eAAE,QAAQ,EACV,eAAE,QAAQ,EACV,eAAE,SAAS,EACX,eAAE,MAAM,CACT;AAED,IAAa,oBAAoB,aAAe,KAAK,MAAM,MAAM,SAAS;AAE1E,IAAa,iBAAiB,aAAe,KAAK,KAAK,MAAM,KAAK;AAElE,IAAa,gBAAgB,aAC3B,QACA,YACA,SACA,YACD;AAED,IAAa,cAAc,aAAe,MAAM,SAAS;AAEzD,IAAa,uBAAuB,eAAE,MACpC,mBACA,gBACA,eACA,YACD;AAED,IAAM,yBAAmD,eAAiB;CACxE,MAAM,eAAE,QAAQ,UAAU;CAC1B,OAAO,eAAE,MACP,eAAE,QAAQ,EACV,eAAE,QAAQ,EACV,eAAE,SAAS,EACX,eAAE,MAAM,EACR,cAAgB,eAAE,MAAM,eAAE,QAAQ,EAAE,eAAE,QAAQ,EAAE,eAAE,S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;AAE1B,KAAI,MAAM,KACR,QAAO;AAET,KAAI,MAAM,KACR,QAAO;AAET,QAAO;;AAGT,SAAS,gBACP,GACA,GACQ;CAER,MAAM,SAAS,MAA4B,MAAM,KAAA,IAAY,IAAI,IAAI,IAAI;AACzE,QAAO,MAAM,EAAE,GAAG,MAAM,EAAE"}
1
+ {"version":3,"file":"ast.js","names":[],"sources":["../../../../zero-protocol/src/ast.ts"],"sourcesContent":["/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {defined} from '../../shared/src/arrays.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\nexport const planIdSymbol = Symbol('planId');\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.literalUnion('asc', 'desc')]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client' | 'test';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.literalUnion('=', '!=', 'IS', 'IS NOT');\n\nexport const orderOpsSchema = v.literalUnion('<', '>', '<=', '>=');\n\nexport const likeOpsSchema = v.literalUnion(\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n);\n\nexport const inOpsSchema = v.literalUnion('IN', 'NOT IN');\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.literalUnion('authData', 'preMutationRow'),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.literalUnion('EXISTS', 'NOT EXISTS');\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n flip: v.boolean().optional(),\n scalar: v.boolean().optional(),\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(\n Array.isArray(field) && field.length >= 1,\n 'Expected non-empty array for compound key',\n );\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n // oxlint-disable-next-line e18e/prefer-spread-syntax\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n flip?: boolean | undefined;\n scalar?: boolean | undefined;\n [planIdSymbol]?: number | undefined;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n related(subqueries: CorrelatedSubquery[]): readonly CorrelatedSubquery[];\n where(cond: Condition): Condition | undefined;\n // conjunction or disjunction, called when traversing the return value of where()\n conditions(conds: Condition[]): readonly Condition[];\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const where = ast.where ? transform.where(ast.where) : undefined;\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: where ? transformWhere(where, ast.table, transform) : undefined,\n related: ast.related\n ? transform.related(\n ast.related.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n )\n : undefined,\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: transform.conditions(\n where.conditions.map(c => transformWhere(c, table, transform)),\n ),\n };\n}\n\nconst normalizeCache = new WeakMap<AST, Required<AST>>();\n\nconst NORMALIZE_TRANSFORM: ASTTransform = {\n tableName: t => t,\n columnName: (_, c) => c,\n related: sortedRelated,\n where: flattened,\n conditions: c => c.sort(cmpCondition),\n};\n\nexport function normalizeAST(ast: AST): Required<AST> {\n let normalized = normalizeCache.get(ast);\n if (!normalized) {\n normalized = transformAST(ast, NORMALIZE_TRANSFORM);\n normalizeCache.set(ast, normalized);\n }\n return normalized;\n}\n\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n related: r => r,\n where: w => w,\n conditions: c => c,\n });\n}\n\nfunction sortedRelated(\n related: CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n return related.sort(cmpRelated);\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return (\n cmpRelated(a.related, b.related) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n cmpOptionalBool(a.flip, b.flip) ||\n cmpOptionalBool(a.scalar, b.scalar)\n );\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal', 'Expected literal type for comparison');\n return compareUTF8(String(a.value), String(b.value));\n case 'column':\n assert(b.type === 'column', 'Expected column type for comparison');\n return compareUTF8(a.name, b.name);\n case 'static':\n throw new Error(\n 'Static parameters should be resolved before normalization',\n );\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\n/**\n * Returns a flattened version of the Conditions in which nested Conjunctions with\n * the same operation ('AND' or 'OR') are flattened to the same level. e.g.\n *\n * ```\n * ((a AND b) AND (c AND (d OR (e OR f)))) -> (a AND b AND c AND (d OR e OR f))\n * ```\n *\n * Also flattens singleton Conjunctions regardless of operator, and removes\n * empty Conjunctions.\n */\nfunction flattened(cond: Condition): Condition | undefined {\n if (cond.type === 'simple' || cond.type === 'correlatedSubquery') {\n return cond;\n }\n const conditions = defined(\n cond.conditions.flatMap(c =>\n c.type === cond.type ? c.conditions.map(c => flattened(c)) : flattened(c),\n ),\n );\n\n switch (conditions.length) {\n case 0:\n return undefined;\n case 1:\n return conditions[0];\n default:\n return {\n type: cond.type,\n conditions,\n };\n }\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n\nfunction cmpOptionalBool(\n a: boolean | undefined,\n b: boolean | undefined,\n): number {\n // undefined < false < true\n const toNum = (v: boolean | undefined) => (v === undefined ? 0 : v ? 2 : 1);\n return toNum(a) - toNum(b);\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAa,cAAc;AAE3B,IAAa,iBAAiB,eAAE,QAAQ;AACxC,IAAa,gBAAgB,QAAQ;AACrC,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K,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,eAAO,MAAM,2BAA2B,6DAEvC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,2BAA2B,CAAC,CAAC"}
1
+ {"version":3,"file":"primary-key.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/primary-key.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAEhD,eAAO,MAAM,gBAAgB,wCAG5B,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAE1D,eAAO,MAAM,qBAAqB,gEAIjC,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,eAAO,MAAM,2BAA2B,6DAEvC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,2BAA2B,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"primary-key.js","names":[],"sources":["../../../../zero-protocol/src/primary-key.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\n\nexport const primaryKeySchema = v.readonly(\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nexport type PrimaryKey = v.Infer<typeof primaryKeySchema>;\n\nexport const primaryKeyValueSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n);\n\nexport type PrimaryKeyValue = v.Infer<typeof primaryKeyValueSchema>;\n\nexport const primaryKeyValueRecordSchema = v.readonlyRecord(\n primaryKeyValueSchema,\n);\n\nexport type PrimaryKeyValueRecord = v.Infer<typeof primaryKeyValueRecordSchema>;\n"],"mappings":";;AAEA,IAAa,mBAAmB,SAC9B,eAAE,MAAM,CAAC,eAAE,QAAQ,CAAC,CAAC,CAAC,OAAO,eAAE,MAAM,eAAE,QAAQ,CAAC,CAAC,CAClD;AAID,IAAa,wBAAwB,eAAE,MACrC,eAAE,QAAQ,EACV,eAAE,QAAQ,EACV,eAAE,SAAS,CACZ;AAID,IAAa,8BAA8B,eACzC,sBACD"}
1
+ {"version":3,"file":"primary-key.js","names":[],"sources":["../../../../zero-protocol/src/primary-key.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\n\nexport const primaryKeySchema = v.readonly(\n // oxlint-disable-next-line e18e/prefer-spread-syntax\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nexport type PrimaryKey = v.Infer<typeof primaryKeySchema>;\n\nexport const primaryKeyValueSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n);\n\nexport type PrimaryKeyValue = v.Infer<typeof primaryKeyValueSchema>;\n\nexport const primaryKeyValueRecordSchema = v.readonlyRecord(\n primaryKeyValueSchema,\n);\n\nexport type PrimaryKeyValueRecord = v.Infer<typeof primaryKeyValueRecordSchema>;\n"],"mappings":";;AAEA,IAAa,mBAAmB,SAE9B,eAAE,MAAM,CAAC,eAAE,QAAQ,CAAC,CAAC,CAAC,OAAO,eAAE,MAAM,eAAE,QAAQ,CAAC,CAAC,CAClD;AAID,IAAa,wBAAwB,eAAE,MACrC,eAAE,QAAQ,EACV,eAAE,QAAQ,EACV,eAAE,SAAS,CACZ;AAID,IAAa,8BAA8B,eACzC,sBACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/push.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAChD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,qCAAqC,CAAC;AAUpE,eAAO,MAAM,kBAAkB,eAAe,CAAC;AAK/C,eAAO,MAAM,6BAA6B,yBAAyB,CAAC;AAEpE,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;eAoBnC,CAAC;AAEF;;GAEG;AACH,QAAA,MAAM,cAAc;;;;;aAKlB,CAAC;AAEH;;;GAGG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Content":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema} from './data.ts';\nimport {pushFailedBodySchema} from './error.ts';\nimport {mutationIDSchema} from './mutation-id.ts';\nimport * as MutationType from './mutation-type-enum.ts';\nimport {primaryKeySchema, primaryKeyValueRecordSchema} from './primary-key.ts';\n\n// NOTE! If you change this name you must also change the\n// string in `replicache-impl.ts` But CRUD mutators are being\n// deleted soon so this should not happen.\nexport const CRUD_MUTATION_NAME = '_zero_crud';\n\n// Internal mutation name for cleaning up mutation results.\n// This mutation is sent from zero-cache to zero-server to delete\n// acknowledged mutation results from the upstream database.\nexport const CLEANUP_RESULTS_MUTATION_NAME = '_zero_cleanupResults';\n\nexport const cleanupResultsArgSchema = v.union(\n // Legacy format (no type field) - treat as single\n v.object({\n clientGroupID: v.string(),\n clientID: v.string(),\n upToMutationID: v.number(),\n }),\n // Explicit single: delete up to a specific mutation ID for one client\n v.object({\n type: v.literal('single'),\n clientGroupID: v.string(),\n clientID: v.string(),\n upToMutationID: v.number(),\n }),\n // Bulk: delete all mutations for multiple clients\n v.object({\n type: v.literal('bulk'),\n clientGroupID: v.string(),\n clientIDs: v.tuple([v.string()]).concat(v.array(v.string())),\n }),\n);\n\n/**\n * Inserts if entity with id does not already exist.\n */\nconst insertOpSchema = v.object({\n op: v.literal('insert'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n value: rowSchema,\n});\n\n/**\n * Upsert semantics. Inserts if entity with id does not already exist,\n * otherwise updates existing entity with id.\n */\nconst upsertOpSchema = v.object({\n op: v.literal('upsert'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n value: rowSchema,\n});\n\n/**\n * Updates if entity with id exists, otherwise does nothing.\n */\nconst updateOpSchema = v.object({\n op: v.literal('update'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n // Partial value with at least the primary key fields\n value: rowSchema,\n});\n\n/**\n * Deletes entity with id if it exists, otherwise does nothing.\n */\nconst deleteOpSchema = v.object({\n op: v.literal('delete'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n // Partial value representing the primary key\n value: primaryKeyValueRecordSchema,\n});\n\nconst crudOpSchema = v.union(\n insertOpSchema,\n upsertOpSchema,\n updateOpSchema,\n deleteOpSchema,\n);\n\nconst crudArgSchema = v.object({\n ops: v.array(crudOpSchema),\n});\n\nconst crudArgsSchema = v.tuple([crudArgSchema]);\n\nexport const crudMutationSchema = v.object({\n type: v.literal(MutationType.CRUD),\n id: v.number(),\n clientID: v.string(),\n name: v.literal(CRUD_MUTATION_NAME),\n args: crudArgsSchema,\n timestamp: v.number(),\n});\n\nexport const customMutationSchema = v.object({\n type: v.literal(MutationType.Custom),\n id: v.number(),\n clientID: v.string(),\n name: v.string(),\n args: v.array(jsonSchema),\n timestamp: v.number(),\n});\n\nexport const mutationSchema = v.union(crudMutationSchema, customMutationSchema);\n\nexport const pushBodySchema = v.object({\n clientGroupID: v.string(),\n mutations: v.array(mutationSchema),\n pushVersion: v.number(),\n // For legacy (CRUD) mutations, the schema is tied to the client group /\n // sync connection. For custom mutations, schema versioning is delegated\n // to the custom protocol / api-server.\n schemaVersion: v.number().optional(),\n timestamp: v.number(),\n requestID: v.string(),\n /**\n * @deprecated auth is managed at client-group scope via connect/updateAuth\n * and should not be included in push messages.\n */\n auth: v.string().optional(),\n});\n\nexport const pushMessageSchema = v.tuple([v.literal('push'), pushBodySchema]);\n\nconst appErrorSchema = v.object({\n error: v.literal('app'),\n // The user can return any additional data here\n message: v.string().optional(),\n details: jsonSchema.optional(),\n});\nconst zeroErrorSchema = v.object({\n error: v.union(\n /** @deprecated push oooMutation errors are now represented as ['error', { ... }] messages */\n v.literal('oooMutation'),\n v.literal('alreadyProcessed'),\n ),\n details: jsonSchema.optional(),\n});\n\nconst mutationOkSchema = v.object({\n // The user can return any additional data here\n data: jsonSchema.optional(),\n});\nconst mutationErrorSchema = v.union(appErrorSchema, zeroErrorSchema);\n\nexport const mutationResultSchema = v.union(\n mutationOkSchema,\n mutationErrorSchema,\n);\n\nexport const mutationResponseSchema = v.object({\n id: mutationIDSchema,\n result: mutationResultSchema,\n});\n\nconst pushOkSchema = v.object({\n mutations: v.array(mutationResponseSchema),\n});\n\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst unsupportedPushVersionSchema = v.object({\n /** @deprecated */\n error: v.literal('unsupportedPushVersion'),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst unsupportedSchemaVersionSchema = v.object({\n /** @deprecated */\n error: v.literal('unsupportedSchemaVersion'),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push http errors are now represented as ['error', { ... }] messages\n */\nconst httpErrorSchema = v.object({\n /** @deprecated */\n error: v.literal('http'),\n /** @deprecated */\n status: v.number(),\n /** @deprecated */\n details: v.string(),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push zero errors are now represented as ['error', { ... }] messages\n */\nconst zeroPusherErrorSchema = v.object({\n /** @deprecated */\n error: v.literal('zeroPusher'),\n /** @deprecated */\n details: v.string(),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst pushErrorSchema = v.union(\n unsupportedPushVersionSchema,\n unsupportedSchemaVersionSchema,\n httpErrorSchema,\n zeroPusherErrorSchema,\n);\n\nexport const pushResponseBodySchema = v.union(pushOkSchema, pushErrorSchema);\n\nexport const pushResponseSchema = v.union(\n pushResponseBodySchema,\n pushFailedBodySchema,\n);\nexport const pushResponseMessageSchema = v.tuple([\n v.literal('pushResponse'),\n pushResponseBodySchema,\n]);\n\nexport const ackMutationResponsesMessageSchema = v.tuple([\n v.literal('ackMutationResponses'),\n mutationIDSchema,\n]);\n\n/**\n * The schema for the querystring parameters of the custom push endpoint.\n */\nexport const pushParamsSchema = v.object({\n schema: v.string(),\n appID: v.string(),\n});\n\nexport type InsertOp = v.Infer<typeof insertOpSchema>;\nexport type UpsertOp = v.Infer<typeof upsertOpSchema>;\nexport type UpdateOp = v.Infer<typeof updateOpSchema>;\nexport type DeleteOp = v.Infer<typeof deleteOpSchema>;\nexport type CRUDOp = v.Infer<typeof crudOpSchema>;\nexport type CRUDOpKind = CRUDOp['op'];\nexport type CRUDMutationArg = v.Infer<typeof crudArgSchema>;\nexport type CRUDMutation = v.Infer<typeof crudMutationSchema>;\nexport type CustomMutation = v.Infer<typeof customMutationSchema>;\nexport type Mutation = v.Infer<typeof mutationSchema>;\nexport type PushBody = v.Infer<typeof pushBodySchema>;\nexport type PushMessage = v.Infer<typeof pushMessageSchema>;\nexport type PushResponseBody = v.Infer<typeof pushResponseBodySchema>;\nexport type PushResponse = v.Infer<typeof pushResponseSchema>;\nexport type PushResponseMessage = v.Infer<typeof pushResponseMessageSchema>;\nexport type MutationResponse = v.Infer<typeof mutationResponseSchema>;\nexport type MutationOk = v.Infer<typeof mutationOkSchema>;\nexport type MutationError = v.Infer<typeof mutationErrorSchema>;\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nexport type PushError = v.Infer<typeof pushErrorSchema>;\nexport type PushOk = v.Infer<typeof pushOkSchema>;\nexport type MutationResult = v.Infer<typeof mutationResultSchema>;\nexport type AckMutationMessage = v.Infer<\n typeof ackMutationResponsesMessageSchema\n>;\nexport type CleanupResultsArg = v.Infer<typeof cleanupResultsArgSchema>;\nexport type {MutationID} from './mutation-id.ts';\n\nexport function mapCRUD(\n arg: CRUDMutationArg,\n map: NameMapper,\n): CRUDMutationArg {\n return {\n ops: arg.ops.map(\n ({op, tableName, primaryKey, value}) =>\n ({\n op,\n tableName: map.tableName(tableName),\n primaryKey: map.columns(tableName, primaryKey),\n value: map.row(tableName, value),\n // The cast is necessary because ts objects to the `value` field\n // for \"delete\" ops being different.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,IAAI,IAAI,KACV,EAAC,IAAI,WAAW,YAAY,aAC1B;EACC;EACA,WAAW,IAAI,UAAU,UAAU;EACnC,YAAY,IAAI,QAAQ,WAAW,WAAW;EAC9C,OAAO,IAAI,IAAI,WAAW,MAAM;EAGjC,EACJ,EACF"}
1
+ {"version":3,"file":"push.js","names":[],"sources":["../../../../zero-protocol/src/push.ts"],"sourcesContent":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema} from './data.ts';\nimport {pushFailedBodySchema} from './error.ts';\nimport {mutationIDSchema} from './mutation-id.ts';\nimport * as MutationType from './mutation-type-enum.ts';\nimport {primaryKeySchema, primaryKeyValueRecordSchema} from './primary-key.ts';\n\n// NOTE! If you change this name you must also change the\n// string in `replicache-impl.ts` But CRUD mutators are being\n// deleted soon so this should not happen.\nexport const CRUD_MUTATION_NAME = '_zero_crud';\n\n// Internal mutation name for cleaning up mutation results.\n// This mutation is sent from zero-cache to zero-server to delete\n// acknowledged mutation results from the upstream database.\nexport const CLEANUP_RESULTS_MUTATION_NAME = '_zero_cleanupResults';\n\nexport const cleanupResultsArgSchema = v.union(\n // Legacy format (no type field) - treat as single\n v.object({\n clientGroupID: v.string(),\n clientID: v.string(),\n upToMutationID: v.number(),\n }),\n // Explicit single: delete up to a specific mutation ID for one client\n v.object({\n type: v.literal('single'),\n clientGroupID: v.string(),\n clientID: v.string(),\n upToMutationID: v.number(),\n }),\n // Bulk: delete all mutations for multiple clients\n v.object({\n type: v.literal('bulk'),\n clientGroupID: v.string(),\n // oxlint-disable-next-line e18e/prefer-spread-syntax\n clientIDs: v.tuple([v.string()]).concat(v.array(v.string())),\n }),\n);\n\n/**\n * Inserts if entity with id does not already exist.\n */\nconst insertOpSchema = v.object({\n op: v.literal('insert'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n value: rowSchema,\n});\n\n/**\n * Upsert semantics. Inserts if entity with id does not already exist,\n * otherwise updates existing entity with id.\n */\nconst upsertOpSchema = v.object({\n op: v.literal('upsert'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n value: rowSchema,\n});\n\n/**\n * Updates if entity with id exists, otherwise does nothing.\n */\nconst updateOpSchema = v.object({\n op: v.literal('update'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n // Partial value with at least the primary key fields\n value: rowSchema,\n});\n\n/**\n * Deletes entity with id if it exists, otherwise does nothing.\n */\nconst deleteOpSchema = v.object({\n op: v.literal('delete'),\n tableName: v.string(),\n primaryKey: primaryKeySchema,\n // Partial value representing the primary key\n value: primaryKeyValueRecordSchema,\n});\n\nconst crudOpSchema = v.union(\n insertOpSchema,\n upsertOpSchema,\n updateOpSchema,\n deleteOpSchema,\n);\n\nconst crudArgSchema = v.object({\n ops: v.array(crudOpSchema),\n});\n\nconst crudArgsSchema = v.tuple([crudArgSchema]);\n\nexport const crudMutationSchema = v.object({\n type: v.literal(MutationType.CRUD),\n id: v.number(),\n clientID: v.string(),\n name: v.literal(CRUD_MUTATION_NAME),\n args: crudArgsSchema,\n timestamp: v.number(),\n});\n\nexport const customMutationSchema = v.object({\n type: v.literal(MutationType.Custom),\n id: v.number(),\n clientID: v.string(),\n name: v.string(),\n args: v.array(jsonSchema),\n timestamp: v.number(),\n});\n\nexport const mutationSchema = v.union(crudMutationSchema, customMutationSchema);\n\nexport const pushBodySchema = v.object({\n clientGroupID: v.string(),\n mutations: v.array(mutationSchema),\n pushVersion: v.number(),\n // For legacy (CRUD) mutations, the schema is tied to the client group /\n // sync connection. For custom mutations, schema versioning is delegated\n // to the custom protocol / api-server.\n schemaVersion: v.number().optional(),\n timestamp: v.number(),\n requestID: v.string(),\n /**\n * @deprecated auth is managed at client-group scope via connect/updateAuth\n * and should not be included in push messages.\n */\n auth: v.string().optional(),\n});\n\nexport const pushMessageSchema = v.tuple([v.literal('push'), pushBodySchema]);\n\nconst appErrorSchema = v.object({\n error: v.literal('app'),\n // The user can return any additional data here\n message: v.string().optional(),\n details: jsonSchema.optional(),\n});\nconst zeroErrorSchema = v.object({\n error: v.union(\n /** @deprecated push oooMutation errors are now represented as ['error', { ... }] messages */\n v.literal('oooMutation'),\n v.literal('alreadyProcessed'),\n ),\n details: jsonSchema.optional(),\n});\n\nconst mutationOkSchema = v.object({\n // The user can return any additional data here\n data: jsonSchema.optional(),\n});\nconst mutationErrorSchema = v.union(appErrorSchema, zeroErrorSchema);\n\nexport const mutationResultSchema = v.union(\n mutationOkSchema,\n mutationErrorSchema,\n);\n\nexport const mutationResponseSchema = v.object({\n id: mutationIDSchema,\n result: mutationResultSchema,\n});\n\nconst pushOkSchema = v.object({\n mutations: v.array(mutationResponseSchema),\n});\n\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst unsupportedPushVersionSchema = v.object({\n /** @deprecated */\n error: v.literal('unsupportedPushVersion'),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst unsupportedSchemaVersionSchema = v.object({\n /** @deprecated */\n error: v.literal('unsupportedSchemaVersion'),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push http errors are now represented as ['error', { ... }] messages\n */\nconst httpErrorSchema = v.object({\n /** @deprecated */\n error: v.literal('http'),\n /** @deprecated */\n status: v.number(),\n /** @deprecated */\n details: v.string(),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push zero errors are now represented as ['error', { ... }] messages\n */\nconst zeroPusherErrorSchema = v.object({\n /** @deprecated */\n error: v.literal('zeroPusher'),\n /** @deprecated */\n details: v.string(),\n /** @deprecated */\n mutationIDs: v.array(mutationIDSchema).optional(),\n});\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nconst pushErrorSchema = v.union(\n unsupportedPushVersionSchema,\n unsupportedSchemaVersionSchema,\n httpErrorSchema,\n zeroPusherErrorSchema,\n);\n\nexport const pushResponseBodySchema = v.union(pushOkSchema, pushErrorSchema);\n\nexport const pushResponseSchema = v.union(\n pushResponseBodySchema,\n pushFailedBodySchema,\n);\nexport const pushResponseMessageSchema = v.tuple([\n v.literal('pushResponse'),\n pushResponseBodySchema,\n]);\n\nexport const ackMutationResponsesMessageSchema = v.tuple([\n v.literal('ackMutationResponses'),\n mutationIDSchema,\n]);\n\n/**\n * The schema for the querystring parameters of the custom push endpoint.\n */\nexport const pushParamsSchema = v.object({\n schema: v.string(),\n appID: v.string(),\n});\n\nexport type InsertOp = v.Infer<typeof insertOpSchema>;\nexport type UpsertOp = v.Infer<typeof upsertOpSchema>;\nexport type UpdateOp = v.Infer<typeof updateOpSchema>;\nexport type DeleteOp = v.Infer<typeof deleteOpSchema>;\nexport type CRUDOp = v.Infer<typeof crudOpSchema>;\nexport type CRUDOpKind = CRUDOp['op'];\nexport type CRUDMutationArg = v.Infer<typeof crudArgSchema>;\nexport type CRUDMutation = v.Infer<typeof crudMutationSchema>;\nexport type CustomMutation = v.Infer<typeof customMutationSchema>;\nexport type Mutation = v.Infer<typeof mutationSchema>;\nexport type PushBody = v.Infer<typeof pushBodySchema>;\nexport type PushMessage = v.Infer<typeof pushMessageSchema>;\nexport type PushResponseBody = v.Infer<typeof pushResponseBodySchema>;\nexport type PushResponse = v.Infer<typeof pushResponseSchema>;\nexport type PushResponseMessage = v.Infer<typeof pushResponseMessageSchema>;\nexport type MutationResponse = v.Infer<typeof mutationResponseSchema>;\nexport type MutationOk = v.Infer<typeof mutationOkSchema>;\nexport type MutationError = v.Infer<typeof mutationErrorSchema>;\n/**\n * @deprecated push errors are now represented as ['error', { ... }] messages\n */\nexport type PushError = v.Infer<typeof pushErrorSchema>;\nexport type PushOk = v.Infer<typeof pushOkSchema>;\nexport type MutationResult = v.Infer<typeof mutationResultSchema>;\nexport type AckMutationMessage = v.Infer<\n typeof ackMutationResponsesMessageSchema\n>;\nexport type CleanupResultsArg = v.Infer<typeof cleanupResultsArgSchema>;\nexport type {MutationID} from './mutation-id.ts';\n\nexport function mapCRUD(\n arg: CRUDMutationArg,\n map: NameMapper,\n): CRUDMutationArg {\n return {\n ops: arg.ops.map(\n ({op, tableName, primaryKey, value}) =>\n ({\n op,\n tableName: map.tableName(tableName),\n primaryKey: map.columns(tableName, primaryKey),\n value: map.row(tableName, value),\n // The cast is necessary because ts objects to the `value` field\n // for \"delete\" ops being different.\n }) as unknown as CRUDOp,\n ),\n };\n}\n"],"mappings":";;;;;;;;AAYA,IAAa,qBAAqB;AAKlC,IAAa,gCAAgC;AAE7C,IAAa,0BAA0B,eAAE,MAEvC,eAAE,OAAO;CACP,eAAe,eAAE,QAAQ;CACzB,UAAU,eAAE,QAAQ;CACpB,gBAAgB,eAAE,QAAQ;CAC3B,CAAC,EAEF,eAAE,OAAO;CACP,MAAM,eAAE,QAAQ,SAAS;CACzB,eAAe,eAAE,QAAQ;CACzB,UAAU,eAAE,QAAQ;CACpB,gBAAgB,eAAE,QAAQ;CAC3B,CAAC,EAEF,eAAE,OAAO;CACP,MAAM,eAAE,QAAQ,OAAO;CACvB,eAAe,eAAE,QAAQ;CAEzB,WAAW,eAAE,MAAM,CAAC,eAAE,QAAQ,CAAC,CAAC,CAAC,OAAO,eAAE,MAAM,eAAE,QAAQ,CAAC,CAAC;CAC7D,CAAC,CACH;;;;AAKD,IAAM,iBAAiB,eAAE,OAAO;CAC9B,IAAI,eAAE,QAAQ,SAAS;CACvB,WAAW,eAAE,QAAQ;CACrB,YAAY;CACZ,OAAO;CACR,CAAC;;;;;AAMF,IAAM,iBAAiB,eAAE,OAAO;CAC9B,IAAI,eAAE,QAAQ,SAAS;CACvB,WAAW,eAAE,QAAQ;CACrB,YAAY;CACZ,OAAO;CACR,CAAC;;;;AAKF,IAAM,iBAAiB,eAAE,OAAO;CAC9B,IAAI,eAAE,QAAQ,SAAS;CACvB,WAAW,eAAE,QAAQ;CACrB,YAAY;CAEZ,OAAO;CACR,CAAC;;;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CAC/C,eAAE,QAAQ,eAAe,EACzB,uBACD,CAAC;AAEF,IAAa,oCAAoC,eAAE,MAAM,CACvD,eAAE,QAAQ,uBAAuB,EACjC,iBACD,CAAC;;;;AAKF,IAAa,mBAAmB,eAAE,OAAO;CACvC,QAAQ,eAAE,QAAQ;CAClB,OAAO,eAAE,QAAQ;CAClB,CAAC;AAgCF,SAAgB,QACd,KACA,KACiB;AACjB,QAAO,EACL,KAAK,IAAI,IAAI,KACV,EAAC,IAAI,WAAW,YAAY,aAC1B;EACC;EACA,WAAW,IAAI,UAAU,UAAU;EACnC,YAAY,IAAI,QAAQ,WAAW,WAAW;EAC9C,OAAO,IAAI,IAAI,WAAW,MAAM;EAGjC,EACJ,EACF"}
@@ -28,7 +28,7 @@ function createMapperFrom(src, tables) {
28
28
  * specified `tablesToColumns` map.
29
29
  */
30
30
  function validator(tablesToColumns) {
31
- return new NameMapper(new Map([...tablesToColumns.entries()].map(([tableName, columns]) => [tableName, {
31
+ return new NameMapper(new Map(Array.from(tablesToColumns.entries(), ([tableName, columns]) => [tableName, {
32
32
  tableName,
33
33
  columns: Object.fromEntries(columns.map((c) => [c, c])),
34
34
  allColumnsSame: true
@@ -1 +1 @@
1
- {"version":3,"file":"name-mapper.js","names":[],"sources":["../../../../zero-schema/src/name-mapper.ts"],"sourcesContent":["import {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport type {TableSchema} from './table-schema.ts';\n\nexport {NameMapper};\n\nexport function clientToServer(\n tables: Record<string, TableSchema>,\n): NameMapper {\n return createMapperFrom('client', tables);\n}\n\nexport function serverToClient(\n tables: Record<string, TableSchema>,\n): NameMapper {\n return createMapperFrom('server', tables);\n}\n\nfunction createMapperFrom(\n src: 'client' | 'server',\n tables: Record<string, TableSchema>,\n): NameMapper {\n const mapping = new Map(\n Object.entries(tables).map(\n ([tableName, {serverName: serverTableName, columns}]) => {\n let allColumnsSame = true;\n const names: Record<string, string> = {};\n for (const [name, {serverName}] of Object.entries(columns)) {\n if (serverName && serverName !== name) {\n allColumnsSame = false;\n }\n if (src === 'client') {\n names[name] = serverName ?? name;\n } else {\n names[serverName ?? name] = name;\n }\n }\n return [\n src === 'client' ? tableName : (serverTableName ?? tableName),\n {\n tableName:\n src === 'client' ? (serverTableName ?? tableName) : tableName,\n columns: names,\n allColumnsSame,\n },\n ];\n },\n ),\n );\n return new NameMapper(mapping);\n}\n\n/**\n * Returns an \"identity\" NameMapper that simply serves the purpose\n * of validating that all table and column names conform to the\n * specified `tablesToColumns` map.\n */\nexport function validator(tablesToColumns: Map<string, string[]>): NameMapper {\n const identity = new Map(\n [...tablesToColumns.entries()].map(([tableName, columns]) => [\n tableName,\n {\n tableName,\n columns: Object.fromEntries(columns.map(c => [c, c])),\n allColumnsSame: true,\n },\n ]),\n );\n return new NameMapper(identity);\n}\n"],"mappings":";;AAKA,SAAgB,eACd,QACY;AACZ,QAAO,iBAAiB,UAAU,OAAO;;AAG3C,SAAgB,eACd,QACY;AACZ,QAAO,iBAAiB,UAAU,OAAO;;AAG3C,SAAS,iBACP,KACA,QACY;AA4BZ,QAAO,IAAI,WA3BK,IAAI,IAClB,OAAO,QAAQ,OAAO,CAAC,KACpB,CAAC,WAAW,EAAC,YAAY,iBAAiB,eAAc;EACvD,IAAI,iBAAiB;EACrB,MAAM,QAAgC,EAAE;AACxC,OAAK,MAAM,CAAC,MAAM,EAAC,iBAAgB,OAAO,QAAQ,QAAQ,EAAE;AAC1D,OAAI,cAAc,eAAe,KAC/B,kBAAiB;AAEnB,OAAI,QAAQ,SACV,OAAM,QAAQ,cAAc;OAE5B,OAAM,cAAc,QAAQ;;AAGhC,SAAO,CACL,QAAQ,WAAW,YAAa,mBAAmB,WACnD;GACE,WACE,QAAQ,WAAY,mBAAmB,YAAa;GACtD,SAAS;GACT;GACD,CACF;GAEJ,CACF,CAC6B;;;;;;;AAQhC,SAAgB,UAAU,iBAAoD;AAW5E,QAAO,IAAI,WAVM,IAAI,IACnB,CAAC,GAAG,gBAAgB,SAAS,CAAC,CAAC,KAAK,CAAC,WAAW,aAAa,CAC3D,WACA;EACE;EACA,SAAS,OAAO,YAAY,QAAQ,KAAI,MAAK,CAAC,GAAG,EAAE,CAAC,CAAC;EACrD,gBAAgB;EACjB,CACF,CAAC,CACH,CAC8B"}
1
+ {"version":3,"file":"name-mapper.js","names":[],"sources":["../../../../zero-schema/src/name-mapper.ts"],"sourcesContent":["import {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport type {TableSchema} from './table-schema.ts';\n\nexport {NameMapper};\n\nexport function clientToServer(\n tables: Record<string, TableSchema>,\n): NameMapper {\n return createMapperFrom('client', tables);\n}\n\nexport function serverToClient(\n tables: Record<string, TableSchema>,\n): NameMapper {\n return createMapperFrom('server', tables);\n}\n\nfunction createMapperFrom(\n src: 'client' | 'server',\n tables: Record<string, TableSchema>,\n): NameMapper {\n const mapping = new Map(\n Object.entries(tables).map(\n ([tableName, {serverName: serverTableName, columns}]) => {\n let allColumnsSame = true;\n const names: Record<string, string> = {};\n for (const [name, {serverName}] of Object.entries(columns)) {\n if (serverName && serverName !== name) {\n allColumnsSame = false;\n }\n if (src === 'client') {\n names[name] = serverName ?? name;\n } else {\n names[serverName ?? name] = name;\n }\n }\n return [\n src === 'client' ? tableName : (serverTableName ?? tableName),\n {\n tableName:\n src === 'client' ? (serverTableName ?? tableName) : tableName,\n columns: names,\n allColumnsSame,\n },\n ];\n },\n ),\n );\n return new NameMapper(mapping);\n}\n\n/**\n * Returns an \"identity\" NameMapper that simply serves the purpose\n * of validating that all table and column names conform to the\n * specified `tablesToColumns` map.\n */\nexport function validator(tablesToColumns: Map<string, string[]>): NameMapper {\n const identity = new Map(\n Array.from(tablesToColumns.entries(), ([tableName, columns]) => [\n tableName,\n {\n tableName,\n columns: Object.fromEntries(columns.map(c => [c, c])),\n allColumnsSame: true,\n },\n ]),\n );\n return new NameMapper(identity);\n}\n"],"mappings":";;AAKA,SAAgB,eACd,QACY;AACZ,QAAO,iBAAiB,UAAU,OAAO;;AAG3C,SAAgB,eACd,QACY;AACZ,QAAO,iBAAiB,UAAU,OAAO;;AAG3C,SAAS,iBACP,KACA,QACY;AA4BZ,QAAO,IAAI,WA3BK,IAAI,IAClB,OAAO,QAAQ,OAAO,CAAC,KACpB,CAAC,WAAW,EAAC,YAAY,iBAAiB,eAAc;EACvD,IAAI,iBAAiB;EACrB,MAAM,QAAgC,EAAE;AACxC,OAAK,MAAM,CAAC,MAAM,EAAC,iBAAgB,OAAO,QAAQ,QAAQ,EAAE;AAC1D,OAAI,cAAc,eAAe,KAC/B,kBAAiB;AAEnB,OAAI,QAAQ,SACV,OAAM,QAAQ,cAAc;OAE5B,OAAM,cAAc,QAAQ;;AAGhC,SAAO,CACL,QAAQ,WAAW,YAAa,mBAAmB,WACnD;GACE,WACE,QAAQ,WAAY,mBAAmB,YAAa;GACtD,SAAS;GACT;GACD,CACF;GAEJ,CACF,CAC6B;;;;;;;AAQhC,SAAgB,UAAU,iBAAoD;AAW5E,QAAO,IAAI,WAVM,IAAI,IACnB,MAAM,KAAK,gBAAgB,SAAS,GAAG,CAAC,WAAW,aAAa,CAC9D,WACA;EACE;EACA,SAAS,OAAO,YAAY,QAAQ,KAAI,MAAK,CAAC,GAAG,EAAE,CAAC,CAAC;EACrD,gBAAgB;EACjB,CACF,CAAC,CACH,CAC8B"}
@@ -1,8 +1,8 @@
1
1
  import "../../zero-protocol/src/application-error.js";
2
2
  import "./custom.js";
3
3
  import "./pg-query-executor.js";
4
- import "./process-mutations.js";
5
4
  import "./push-processor.js";
5
+ import "./process-mutations.js";
6
6
  import "./queries/process-queries.js";
7
7
  import "./zql-database.js";
8
8
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"process-mutations.d.ts","sourceRoot":"","sources":["../../../../zero-server/src/process-mutations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,QAAQ,EAAC,MAAM,kBAAkB,CAAC;AAG3D,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;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10
  import { cleanupResultsArgSchema, pushBodySchema, pushParamsSchema } from "../../zero-protocol/src/push.js";
11
11
  import { MutationAlreadyProcessedError } from "../../zero-cache/src/services/mutagen/error.js";
12
12
  import { createLogContext } from "./logging.js";
13
+ import { separatorRe } from "./push-processor.js";
13
14
  //#region ../zero-server/src/process-mutations.ts
14
15
  var applicationErrorWrapper = async (fn) => {
15
16
  try {
@@ -262,7 +263,7 @@ function makeAppErrorResponse(m, error) {
262
263
  }
263
264
  /** @deprecated Use getMutator instead */
264
265
  function getMutation(mutators, name) {
265
- const mutator = getObjectAtPath(mutators, name.split(/\.|\|/));
266
+ const mutator = getObjectAtPath(mutators, name.split(separatorRe));
266
267
  assert(typeof mutator === "function", `could not find mutator ${name}`);
267
268
  if (isMutator(mutator)) return (tx, args, ctx) => mutator.fn({
268
269
  args,
@@ -1 +1 @@
1
- {"version":3,"file":"process-mutations.js","names":["#dbProvider","#req","#params","#lc","#transactImpl","#checkAndIncrementLastMutationID","#getTransactionInput"],"sources":["../../../../zero-server/src/process-mutations.ts"],"sourcesContent":["import type {LogContext, LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {MutationAlreadyProcessedError} from '../../zero-cache/src/services/mutagen/error.ts';\nimport type {ApplicationError} from '../../zero-protocol/src/application-error.ts';\nimport {\n isApplicationError,\n wrapWithApplicationError,\n} from '../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../zero-protocol/src/error-reason.ts';\nimport type {PushFailedBody} from '../../zero-protocol/src/error.ts';\nimport {\n CLEANUP_RESULTS_MUTATION_NAME,\n cleanupResultsArgSchema,\n pushBodySchema,\n pushParamsSchema,\n type CleanupResultsArg,\n type CustomMutation,\n type Mutation,\n type MutationID,\n type MutationResponse,\n type PushBody,\n type PushResponse,\n} from '../../zero-protocol/src/push.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs, CustomMutatorImpl} from './custom.ts';\nimport {createLogContext} from './logging.ts';\n\nexport interface TransactionProviderHooks {\n updateClientMutationID: () => Promise<{lastMutationID: number | bigint}>;\n writeMutationResult: (result: MutationResponse) => Promise<void>;\n deleteMutationResults: (args: CleanupResultsArg) => Promise<void>;\n}\n\nexport interface TransactionProviderInput {\n upstreamSchema: string;\n clientGroupID: string;\n clientID: string;\n mutationID: number;\n}\n\n/**\n * Defines the abstract interface for a database that PushProcessor can execute\n * transactions against.\n */\nexport interface Database<T> {\n transaction: <R>(\n callback: (\n tx: T,\n transactionHooks: TransactionProviderHooks,\n ) => MaybePromise<R>,\n transactionInput?: TransactionProviderInput,\n ) => Promise<R>;\n}\n\nexport type ExtractTransactionType<D> = D extends Database<infer T> ? T : never;\nexport type Params = v.Infer<typeof pushParamsSchema>;\n\nexport type TransactFn<D extends Database<ExtractTransactionType<D>>> = (\n cb: TransactFnCallback<D>,\n) => Promise<MutationResponse>;\n\nexport type TransactFnCallback<D extends Database<ExtractTransactionType<D>>> =\n (\n tx: ExtractTransactionType<D>,\n mutatorName: string,\n mutatorArgs: ReadonlyJSONValue | undefined,\n ) => Promise<void>;\n\nexport type Parsed<D extends Database<ExtractTransactionType<D>>> = {\n transact: TransactFn<D>;\n mutations: CustomMutation[];\n};\n\ntype MutationPhase = 'preTransaction' | 'transactionPending' | 'postCommit';\n\nconst applicationErrorWrapper = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n return await fn();\n } catch (error) {\n if (\n error instanceof DatabaseTransactionError ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError ||\n isApplicationError(error)\n ) {\n throw error;\n }\n\n throw wrapWithApplicationError(error);\n }\n};\n\n/**\n * @deprecated Use {@linkcode handleMutateRequest} instead.\n */\nexport const handleMutationRequest = handleMutateRequest;\n\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n queryString: URLSearchParams | Record<string, string>,\n body: ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<PushResponse>;\n\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n request: Request,\n logLevel?: LogLevel,\n): Promise<PushResponse>;\n\nexport async function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n queryStringOrRequest: Request | URLSearchParams | Record<string, string>,\n bodyOrLogLevel?: ReadonlyJSONValue | LogLevel,\n logLevel?: LogLevel,\n): Promise<PushResponse> {\n // Parse overload arguments\n const isRequestOverload = queryStringOrRequest instanceof Request;\n\n let request: Request | undefined;\n let queryString: URLSearchParams | Record<string, string>;\n let jsonBody: unknown;\n\n let lc: LogContext;\n\n if (isRequestOverload) {\n request = queryStringOrRequest;\n const level = (bodyOrLogLevel as LogLevel | undefined) ?? 'info';\n\n // Create log context early, before extracting JSON from Request\n lc = createLogContext(level).withContext('PushProcessor');\n\n const url = new URL(request.url);\n queryString = url.searchParams;\n\n try {\n jsonBody = await request.json();\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs: [],\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n } else {\n queryString = queryStringOrRequest;\n jsonBody = bodyOrLogLevel;\n const level = logLevel ?? 'info';\n lc = createLogContext(level).withContext('PushProcessor');\n }\n\n let mutationIDs: MutationID[] = [];\n\n let pushBody: PushBody;\n try {\n pushBody = v.parse(jsonBody, pushBodySchema);\n mutationIDs = pushBody.mutations.map(m => ({\n id: m.id,\n clientID: m.clientID,\n }));\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n let queryParams: Params;\n try {\n const queryStringObj =\n queryString instanceof URLSearchParams\n ? Object.fromEntries(queryString)\n : queryString;\n queryParams = v.parse(queryStringObj, pushParamsSchema, 'passthrough');\n } catch (error) {\n lc.error?.('Failed to parse push query parameters', error);\n const message = `Failed to parse push query parameters: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n if (pushBody.pushVersion !== 1) {\n const response = {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.UnsupportedPushVersion,\n mutationIDs,\n message: `Unsupported push version: ${pushBody.pushVersion}`,\n } as const satisfies PushFailedBody;\n return response;\n }\n\n const responses: MutationResponse[] = [];\n let processedCount = 0;\n\n try {\n const transactor = new Transactor(dbProvider, pushBody, queryParams, lc);\n\n // Each mutation goes through three phases:\n // 1. Pre-transaction: user logic that runs before `transact` is called. If\n // this throws we still advance LMID and persist the failure result.\n // 2. Transaction: the callback passed to `transact`, which can be retried\n // if it fails with an ApplicationError.\n // 3. Post-commit: any logic that runs after `transact` resolves. Failures\n // here are logged but the mutation remains committed.\n for (const m of pushBody.mutations) {\n // Handle internal mutations (like cleanup) directly without user dispatch\n if (m.type === 'custom' && m.name === CLEANUP_RESULTS_MUTATION_NAME) {\n lc.debug?.(\n `Processing internal mutation '${m.name}' (clientID=${m.clientID})`,\n );\n try {\n await processCleanupResultsMutation(dbProvider, m, queryParams, lc);\n // No response added - this is fire-and-forget\n processedCount++;\n } catch (error) {\n lc.warn?.(\n `Failed to process cleanup mutation for client ${m.clientID}`,\n error,\n );\n // Don't fail the whole push for cleanup errors\n processedCount++;\n }\n continue;\n }\n\n assert(m.type === 'custom', 'Expected custom mutation');\n lc.debug?.(\n `Processing mutation '${m.name}' (id=${m.id}, clientID=${m.clientID})`,\n );\n\n let mutationPhase: MutationPhase = 'preTransaction';\n\n const transactProxy: TransactFn<D> = async innerCb => {\n mutationPhase = 'transactionPending';\n const result = await transactor.transact(m, innerCb);\n mutationPhase = 'postCommit';\n return result;\n };\n\n try {\n const res = await applicationErrorWrapper(() => cb(transactProxy, m));\n responses.push(res);\n lc.debug?.(`Mutation '${m.name}' (id=${m.id}) completed successfully`);\n\n processedCount++;\n } catch (error) {\n if (!isApplicationError(error)) {\n throw error;\n }\n\n if (mutationPhase === 'preTransaction') {\n // Pre-transaction\n await transactor.persistPreTransactionFailure(m, error);\n } else if (mutationPhase === 'postCommit') {\n // Post-commit\n lc.error?.(\n `Post-commit mutation handler failed for mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n }\n\n lc.warn?.(\n `Application error processing mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n responses.push(makeAppErrorResponse(m, error));\n\n processedCount++;\n }\n }\n\n return {\n mutations: responses,\n };\n } catch (error) {\n lc.error?.('Failed to process push request', error);\n // only include mutationIDs for mutations that were not processed\n const unprocessedMutationIDs = mutationIDs.slice(processedCount);\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason:\n error instanceof OutOfOrderMutation\n ? ErrorReason.OutOfOrderMutation\n : error instanceof DatabaseTransactionError\n ? ErrorReason.Database\n : ErrorReason.Internal,\n message,\n mutationIDs: unprocessedMutationIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\nclass Transactor<D extends Database<ExtractTransactionType<D>>> {\n readonly #dbProvider: D;\n readonly #req: PushBody;\n readonly #params: Params;\n readonly #lc: LogContext;\n\n constructor(dbProvider: D, req: PushBody, params: Params, lc: LogContext) {\n this.#dbProvider = dbProvider;\n this.#req = req;\n this.#params = params;\n this.#lc = lc;\n }\n\n transact = async (\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n ): Promise<MutationResponse> => {\n let appError: ApplicationError | undefined = undefined;\n for (;;) {\n try {\n const ret = await this.#transactImpl(mutation, cb, appError);\n if (appError !== undefined) {\n this.#lc.warn?.(\n `Mutation ${mutation.id} for client ${mutation.clientID} was retried after an error`,\n appError,\n );\n return makeAppErrorResponse(mutation, appError);\n }\n\n return ret;\n } catch (error) {\n if (error instanceof OutOfOrderMutation) {\n this.#lc.error?.(error);\n throw error;\n }\n\n if (error instanceof MutationAlreadyProcessedError) {\n this.#lc.warn?.(error);\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {\n error: 'alreadyProcessed',\n details: error.message,\n },\n };\n }\n\n if (appError !== undefined) {\n // Retry also failed → internal error, cannot skip mutation\n this.#lc.error?.(\n `Retry also failed for mutation ${mutation.id} for client ${mutation.clientID}`,\n error,\n );\n throw error;\n }\n\n // First attempt failed → store error and retry without mutator\n const originalError =\n error instanceof DatabaseTransactionError\n ? (error.cause ?? error)\n : error;\n appError = wrapWithApplicationError(originalError);\n this.#lc.warn?.(\n `Error processing mutation ${mutation.id} for client ${mutation.clientID}, retrying without mutator`,\n appError,\n );\n continue;\n }\n }\n };\n\n async persistPreTransactionFailure(\n mutation: CustomMutation,\n appError: ApplicationError<ReadonlyJSONValue | undefined>,\n ): Promise<MutationResponse> {\n // User-land code threw before calling `transact`. We still need to bump the\n // LMID for this mutation and persist the error so that the client knows it failed.\n const ret = await this.#transactImpl(\n mutation,\n // noop callback since there's no transaction to execute\n () => promiseVoid,\n appError,\n );\n return ret;\n }\n\n async #transactImpl(\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n appError: ApplicationError | undefined,\n ): Promise<MutationResponse> {\n let transactionPhase: DatabaseTransactionPhase = 'open';\n\n try {\n const ret = await this.#dbProvider.transaction(\n async (dbTx, transactionHooks) => {\n // update the transaction phase to 'execute' after the transaction is opened\n transactionPhase = 'execute';\n\n await this.#checkAndIncrementLastMutationID(\n transactionHooks,\n mutation.clientID,\n mutation.id,\n );\n\n if (appError === undefined) {\n this.#lc.debug?.(\n `Executing mutator '${mutation.name}' (id=${mutation.id})`,\n );\n await cb(dbTx, mutation.name, mutation.args[0]);\n } else {\n const mutationResult = makeAppErrorResponse(mutation, appError);\n await transactionHooks.writeMutationResult(mutationResult);\n }\n\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {},\n };\n },\n this.#getTransactionInput(mutation),\n );\n\n return ret;\n } catch (error) {\n if (\n isApplicationError(error) ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError\n ) {\n throw error;\n }\n\n throw new DatabaseTransactionError(transactionPhase, {cause: error});\n }\n }\n\n #getTransactionInput(mutation: CustomMutation): TransactionProviderInput {\n return {\n upstreamSchema: this.#params.schema,\n clientGroupID: this.#req.clientGroupID,\n clientID: mutation.clientID,\n mutationID: mutation.id,\n };\n }\n\n async #checkAndIncrementLastMutationID(\n transactionHooks: TransactionProviderHooks,\n clientID: string,\n receivedMutationID: number,\n ) {\n const {lastMutationID} = await transactionHooks.updateClientMutationID();\n\n if (receivedMutationID < lastMutationID) {\n throw new MutationAlreadyProcessedError(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n } else if (receivedMutationID > lastMutationID) {\n throw new OutOfOrderMutation(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n }\n }\n}\n\nexport class OutOfOrderMutation extends Error {\n constructor(\n clientID: string,\n receivedMutationID: number,\n lastMutationID: number | bigint,\n ) {\n super(\n `Client ${clientID} sent mutation ID ${receivedMutationID} but expected ${lastMutationID}`,\n );\n }\n}\n\nfunction makeAppErrorResponse(\n m: Mutation,\n error: ApplicationError<ReadonlyJSONValue | undefined>,\n): MutationResponse {\n return {\n id: {\n clientID: m.clientID,\n id: m.id,\n },\n result: {\n error: 'app',\n message: error.message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n/** @deprecated Use getMutator instead */\nexport function getMutation(\n // oxlint-disable-next-line no-explicit-any\n mutators: AnyMutatorRegistry | CustomMutatorDefs<any>,\n name: string,\n // oxlint-disable-next-line no-explicit-any\n): CustomMutatorImpl<any> {\n const path = name.split(/\\.|\\|/);\n const mutator = getObjectAtPath(mutators, path);\n assert(typeof mutator === 'function', `could not find mutator ${name}`);\n\n if (isMutator(mutator)) {\n // mutator needs to be called with {tx, args, ctx}\n // CustomMutatorImpl is called with (tx, args, ctx)\n return (tx, args, ctx) => mutator.fn({args, ctx, tx});\n }\n\n // oxlint-disable-next-line no-explicit-any\n return mutator as CustomMutatorImpl<any>;\n}\n\nfunction getObjectAtPath(\n obj: Record<string, unknown>,\n path: string[],\n): unknown {\n let current: unknown = obj;\n for (const part of path) {\n if (typeof current !== 'object' || current === null || !(part in current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Processes internal cleanup mutation that deletes acknowledged mutation results\n * from the upstream database. This runs without LMID tracking since it's an\n * internal operation.\n */\nasync function processCleanupResultsMutation<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n mutation: CustomMutation,\n queryParams: Params,\n lc: LogContext,\n): Promise<void> {\n const parseResult = v.test(mutation.args[0], cleanupResultsArgSchema);\n if (!parseResult.ok) {\n lc.warn?.('Cleanup mutation has invalid args', parseResult.error);\n return;\n }\n const args: CleanupResultsArg = parseResult.value;\n\n // Determine clientID for transaction input based on cleanup type\n // Note: legacy format without type field is treated as single\n const clientID =\n 'type' in args && args.type === 'bulk' ? args.clientIDs[0] : args.clientID;\n\n // Run in a transaction, using the hook for DB-specific operation.\n // Note: only upstreamSchema is used by deleteMutationResults; the other\n // fields are required by the interface but ignored for this operation.\n await dbProvider.transaction(\n async (_, hooks) => {\n await hooks.deleteMutationResults(args);\n },\n {\n upstreamSchema: queryParams.schema,\n clientGroupID: args.clientGroupID,\n clientID,\n mutationID: 0,\n },\n );\n}\n\ntype DatabaseTransactionPhase = 'open' | 'execute';\nclass DatabaseTransactionError extends Error {\n constructor(phase: DatabaseTransactionPhase, options?: ErrorOptions) {\n super(\n phase === 'open'\n ? `Failed to open database transaction: ${getErrorMessage(options?.cause)}`\n : `Database transaction failed after opening: ${getErrorMessage(options?.cause)}`,\n options,\n );\n this.name = 'DatabaseTransactionError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAmFA,IAAM,0BAA0B,OAAU,OAAqC;AAC7E,KAAI;AACF,SAAO,MAAM,IAAI;UACV,OAAO;AACd,MACE,iBAAiB,4BACjB,iBAAiB,sBACjB,iBAAiB,iCACjB,mBAAmB,MAAM,CAEzB,OAAM;AAGR,QAAM,yBAAyB,MAAM;;;;;;AAOzC,IAAa,wBAAwB;AA2BrC,eAAsB,oBAGpB,YACA,IAIA,sBACA,gBACA,UACuB;CAEvB,MAAM,oBAAoB,gCAAgC;CAE1D,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,IAAI;AAEJ,KAAI,mBAAmB;AACrB,YAAU;AAIV,OAAK,iBAHU,kBAA2C,OAG9B,CAAC,YAAY,gBAAgB;AAGzD,gBADY,IAAI,IAAI,QAAQ,IAAI,CACd;AAElB,MAAI;AACF,cAAW,MAAM,QAAQ,MAAM;WACxB,OAAO;AACd,MAAG,QAAQ,6BAA6B,MAAM;GAC9C,MAAM,UAAU,8BAA8B,gB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EwB;CAExB,MAAM,UAAU,gBAAgB,UADnB,KAAK,MAAM,QAAQ,CACe;AAC/C,QAAO,OAAO,YAAY,YAAY,0BAA0B,OAAO;AAEvE,KAAI,UAAU,QAAQ,CAGpB,SAAQ,IAAI,MAAM,QAAQ,QAAQ,GAAG;EAAC;EAAM;EAAK;EAAG,CAAC;AAIvD,QAAO;;AAGT,SAAS,gBACP,KACA,MACS;CACT,IAAI,UAAmB;AACvB,MAAK,MAAM,QAAQ,MAAM;AACvB,MAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,EAAE,QAAQ,SAC/D;AAEF,YAAW,QAAoC;;AAEjD,QAAO;;;;;;;AAQT,eAAe,8BAGb,YACA,UACA,aACA,IACe;CACf,MAAM,cAAc,KAAO,SAAS,KAAK,IAAI,wBAAwB;AACrE,KAAI,CAAC,YAAY,IAAI;AACnB,KAAG,OAAO,qCAAqC,YAAY,MAAM;AACjE;;CAEF,MAAM,OAA0B,YAAY;CAI5C,MAAM,WACJ,UAAU,QAAQ,KAAK,SAAS,SAAS,KAAK,UAAU,KAAK,KAAK;AAKpE,OAAM,WAAW,YACf,OAAO,GAAG,UAAU;AAClB,QAAM,MAAM,sBAAsB,KAAK;IAEzC;EACE,gBAAgB,YAAY;EAC5B,eAAe,KAAK;EACpB;EACA,YAAY;EACb,CACF;;AAIH,IAAM,2BAAN,cAAuC,MAAM;CAC3C,YAAY,OAAiC,SAAwB;AACnE,QACE,UAAU,SACN,wCAAwC,gBAAgB,SAAS,MAAM,KACvE,8CAA8C,gBAAgB,SAAS,MAAM,IACjF,QACD;AACD,OAAK,OAAO"}
1
+ {"version":3,"file":"process-mutations.js","names":["#dbProvider","#req","#params","#lc","#transactImpl","#checkAndIncrementLastMutationID","#getTransactionInput"],"sources":["../../../../zero-server/src/process-mutations.ts"],"sourcesContent":["import type {LogContext, LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {MutationAlreadyProcessedError} from '../../zero-cache/src/services/mutagen/error.ts';\nimport type {ApplicationError} from '../../zero-protocol/src/application-error.ts';\nimport {\n isApplicationError,\n wrapWithApplicationError,\n} from '../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../zero-protocol/src/error-reason.ts';\nimport type {PushFailedBody} from '../../zero-protocol/src/error.ts';\nimport {\n CLEANUP_RESULTS_MUTATION_NAME,\n cleanupResultsArgSchema,\n pushBodySchema,\n pushParamsSchema,\n type CleanupResultsArg,\n type CustomMutation,\n type Mutation,\n type MutationID,\n type MutationResponse,\n type PushBody,\n type PushResponse,\n} from '../../zero-protocol/src/push.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs, CustomMutatorImpl} from './custom.ts';\nimport {createLogContext} from './logging.ts';\nimport {separatorRe} from './push-processor.ts';\n\nexport interface TransactionProviderHooks {\n updateClientMutationID: () => Promise<{lastMutationID: number | bigint}>;\n writeMutationResult: (result: MutationResponse) => Promise<void>;\n deleteMutationResults: (args: CleanupResultsArg) => Promise<void>;\n}\n\nexport interface TransactionProviderInput {\n upstreamSchema: string;\n clientGroupID: string;\n clientID: string;\n mutationID: number;\n}\n\n/**\n * Defines the abstract interface for a database that PushProcessor can execute\n * transactions against.\n */\nexport interface Database<T> {\n transaction: <R>(\n callback: (\n tx: T,\n transactionHooks: TransactionProviderHooks,\n ) => MaybePromise<R>,\n transactionInput?: TransactionProviderInput,\n ) => Promise<R>;\n}\n\nexport type ExtractTransactionType<D> = D extends Database<infer T> ? T : never;\nexport type Params = v.Infer<typeof pushParamsSchema>;\n\nexport type TransactFn<D extends Database<ExtractTransactionType<D>>> = (\n cb: TransactFnCallback<D>,\n) => Promise<MutationResponse>;\n\nexport type TransactFnCallback<D extends Database<ExtractTransactionType<D>>> =\n (\n tx: ExtractTransactionType<D>,\n mutatorName: string,\n mutatorArgs: ReadonlyJSONValue | undefined,\n ) => Promise<void>;\n\nexport type Parsed<D extends Database<ExtractTransactionType<D>>> = {\n transact: TransactFn<D>;\n mutations: CustomMutation[];\n};\n\ntype MutationPhase = 'preTransaction' | 'transactionPending' | 'postCommit';\n\nconst applicationErrorWrapper = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n return await fn();\n } catch (error) {\n if (\n error instanceof DatabaseTransactionError ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError ||\n isApplicationError(error)\n ) {\n throw error;\n }\n\n throw wrapWithApplicationError(error);\n }\n};\n\n/**\n * @deprecated Use {@linkcode handleMutateRequest} instead.\n */\nexport const handleMutationRequest = handleMutateRequest;\n\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n queryString: URLSearchParams | Record<string, string>,\n body: ReadonlyJSONValue,\n logLevel?: LogLevel,\n): Promise<PushResponse>;\n\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n request: Request,\n logLevel?: LogLevel,\n): Promise<PushResponse>;\n\nexport async function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n cb: (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n ) => Promise<MutationResponse>,\n queryStringOrRequest: Request | URLSearchParams | Record<string, string>,\n bodyOrLogLevel?: ReadonlyJSONValue | LogLevel,\n logLevel?: LogLevel,\n): Promise<PushResponse> {\n // Parse overload arguments\n const isRequestOverload = queryStringOrRequest instanceof Request;\n\n let request: Request | undefined;\n let queryString: URLSearchParams | Record<string, string>;\n let jsonBody: unknown;\n\n let lc: LogContext;\n\n if (isRequestOverload) {\n request = queryStringOrRequest;\n const level = (bodyOrLogLevel as LogLevel | undefined) ?? 'info';\n\n // Create log context early, before extracting JSON from Request\n lc = createLogContext(level).withContext('PushProcessor');\n\n const url = new URL(request.url);\n queryString = url.searchParams;\n\n try {\n jsonBody = await request.json();\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs: [],\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n } else {\n queryString = queryStringOrRequest;\n jsonBody = bodyOrLogLevel;\n const level = logLevel ?? 'info';\n lc = createLogContext(level).withContext('PushProcessor');\n }\n\n let mutationIDs: MutationID[] = [];\n\n let pushBody: PushBody;\n try {\n pushBody = v.parse(jsonBody, pushBodySchema);\n mutationIDs = pushBody.mutations.map(m => ({\n id: m.id,\n clientID: m.clientID,\n }));\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n let queryParams: Params;\n try {\n const queryStringObj =\n queryString instanceof URLSearchParams\n ? Object.fromEntries(queryString)\n : queryString;\n queryParams = v.parse(queryStringObj, pushParamsSchema, 'passthrough');\n } catch (error) {\n lc.error?.('Failed to parse push query parameters', error);\n const message = `Failed to parse push query parameters: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n if (pushBody.pushVersion !== 1) {\n const response = {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.UnsupportedPushVersion,\n mutationIDs,\n message: `Unsupported push version: ${pushBody.pushVersion}`,\n } as const satisfies PushFailedBody;\n return response;\n }\n\n const responses: MutationResponse[] = [];\n let processedCount = 0;\n\n try {\n const transactor = new Transactor(dbProvider, pushBody, queryParams, lc);\n\n // Each mutation goes through three phases:\n // 1. Pre-transaction: user logic that runs before `transact` is called. If\n // this throws we still advance LMID and persist the failure result.\n // 2. Transaction: the callback passed to `transact`, which can be retried\n // if it fails with an ApplicationError.\n // 3. Post-commit: any logic that runs after `transact` resolves. Failures\n // here are logged but the mutation remains committed.\n for (const m of pushBody.mutations) {\n // Handle internal mutations (like cleanup) directly without user dispatch\n if (m.type === 'custom' && m.name === CLEANUP_RESULTS_MUTATION_NAME) {\n lc.debug?.(\n `Processing internal mutation '${m.name}' (clientID=${m.clientID})`,\n );\n try {\n await processCleanupResultsMutation(dbProvider, m, queryParams, lc);\n // No response added - this is fire-and-forget\n processedCount++;\n } catch (error) {\n lc.warn?.(\n `Failed to process cleanup mutation for client ${m.clientID}`,\n error,\n );\n // Don't fail the whole push for cleanup errors\n processedCount++;\n }\n continue;\n }\n\n assert(m.type === 'custom', 'Expected custom mutation');\n lc.debug?.(\n `Processing mutation '${m.name}' (id=${m.id}, clientID=${m.clientID})`,\n );\n\n let mutationPhase: MutationPhase = 'preTransaction';\n\n const transactProxy: TransactFn<D> = async innerCb => {\n mutationPhase = 'transactionPending';\n const result = await transactor.transact(m, innerCb);\n mutationPhase = 'postCommit';\n return result;\n };\n\n try {\n const res = await applicationErrorWrapper(() => cb(transactProxy, m));\n responses.push(res);\n lc.debug?.(`Mutation '${m.name}' (id=${m.id}) completed successfully`);\n\n processedCount++;\n } catch (error) {\n if (!isApplicationError(error)) {\n throw error;\n }\n\n if (mutationPhase === 'preTransaction') {\n // Pre-transaction\n await transactor.persistPreTransactionFailure(m, error);\n } else if (mutationPhase === 'postCommit') {\n // Post-commit\n lc.error?.(\n `Post-commit mutation handler failed for mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n }\n\n lc.warn?.(\n `Application error processing mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n responses.push(makeAppErrorResponse(m, error));\n\n processedCount++;\n }\n }\n\n return {\n mutations: responses,\n };\n } catch (error) {\n lc.error?.('Failed to process push request', error);\n // only include mutationIDs for mutations that were not processed\n const unprocessedMutationIDs = mutationIDs.slice(processedCount);\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason:\n error instanceof OutOfOrderMutation\n ? ErrorReason.OutOfOrderMutation\n : error instanceof DatabaseTransactionError\n ? ErrorReason.Database\n : ErrorReason.Internal,\n message,\n mutationIDs: unprocessedMutationIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\nclass Transactor<D extends Database<ExtractTransactionType<D>>> {\n readonly #dbProvider: D;\n readonly #req: PushBody;\n readonly #params: Params;\n readonly #lc: LogContext;\n\n constructor(dbProvider: D, req: PushBody, params: Params, lc: LogContext) {\n this.#dbProvider = dbProvider;\n this.#req = req;\n this.#params = params;\n this.#lc = lc;\n }\n\n transact = async (\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n ): Promise<MutationResponse> => {\n let appError: ApplicationError | undefined = undefined;\n for (;;) {\n try {\n const ret = await this.#transactImpl(mutation, cb, appError);\n if (appError !== undefined) {\n this.#lc.warn?.(\n `Mutation ${mutation.id} for client ${mutation.clientID} was retried after an error`,\n appError,\n );\n return makeAppErrorResponse(mutation, appError);\n }\n\n return ret;\n } catch (error) {\n if (error instanceof OutOfOrderMutation) {\n this.#lc.error?.(error);\n throw error;\n }\n\n if (error instanceof MutationAlreadyProcessedError) {\n this.#lc.warn?.(error);\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {\n error: 'alreadyProcessed',\n details: error.message,\n },\n };\n }\n\n if (appError !== undefined) {\n // Retry also failed → internal error, cannot skip mutation\n this.#lc.error?.(\n `Retry also failed for mutation ${mutation.id} for client ${mutation.clientID}`,\n error,\n );\n throw error;\n }\n\n // First attempt failed → store error and retry without mutator\n const originalError =\n error instanceof DatabaseTransactionError\n ? (error.cause ?? error)\n : error;\n appError = wrapWithApplicationError(originalError);\n this.#lc.warn?.(\n `Error processing mutation ${mutation.id} for client ${mutation.clientID}, retrying without mutator`,\n appError,\n );\n continue;\n }\n }\n };\n\n async persistPreTransactionFailure(\n mutation: CustomMutation,\n appError: ApplicationError<ReadonlyJSONValue | undefined>,\n ): Promise<MutationResponse> {\n // User-land code threw before calling `transact`. We still need to bump the\n // LMID for this mutation and persist the error so that the client knows it failed.\n const ret = await this.#transactImpl(\n mutation,\n // noop callback since there's no transaction to execute\n () => promiseVoid,\n appError,\n );\n return ret;\n }\n\n async #transactImpl(\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n appError: ApplicationError | undefined,\n ): Promise<MutationResponse> {\n let transactionPhase: DatabaseTransactionPhase = 'open';\n\n try {\n const ret = await this.#dbProvider.transaction(\n async (dbTx, transactionHooks) => {\n // update the transaction phase to 'execute' after the transaction is opened\n transactionPhase = 'execute';\n\n await this.#checkAndIncrementLastMutationID(\n transactionHooks,\n mutation.clientID,\n mutation.id,\n );\n\n if (appError === undefined) {\n this.#lc.debug?.(\n `Executing mutator '${mutation.name}' (id=${mutation.id})`,\n );\n await cb(dbTx, mutation.name, mutation.args[0]);\n } else {\n const mutationResult = makeAppErrorResponse(mutation, appError);\n await transactionHooks.writeMutationResult(mutationResult);\n }\n\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {},\n };\n },\n this.#getTransactionInput(mutation),\n );\n\n return ret;\n } catch (error) {\n if (\n isApplicationError(error) ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError\n ) {\n throw error;\n }\n\n throw new DatabaseTransactionError(transactionPhase, {cause: error});\n }\n }\n\n #getTransactionInput(mutation: CustomMutation): TransactionProviderInput {\n return {\n upstreamSchema: this.#params.schema,\n clientGroupID: this.#req.clientGroupID,\n clientID: mutation.clientID,\n mutationID: mutation.id,\n };\n }\n\n async #checkAndIncrementLastMutationID(\n transactionHooks: TransactionProviderHooks,\n clientID: string,\n receivedMutationID: number,\n ) {\n const {lastMutationID} = await transactionHooks.updateClientMutationID();\n\n if (receivedMutationID < lastMutationID) {\n throw new MutationAlreadyProcessedError(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n } else if (receivedMutationID > lastMutationID) {\n throw new OutOfOrderMutation(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n }\n }\n}\n\nexport class OutOfOrderMutation extends Error {\n constructor(\n clientID: string,\n receivedMutationID: number,\n lastMutationID: number | bigint,\n ) {\n super(\n `Client ${clientID} sent mutation ID ${receivedMutationID} but expected ${lastMutationID}`,\n );\n }\n}\n\nfunction makeAppErrorResponse(\n m: Mutation,\n error: ApplicationError<ReadonlyJSONValue | undefined>,\n): MutationResponse {\n return {\n id: {\n clientID: m.clientID,\n id: m.id,\n },\n result: {\n error: 'app',\n message: error.message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n/** @deprecated Use getMutator instead */\nexport function getMutation(\n // oxlint-disable-next-line no-explicit-any\n mutators: AnyMutatorRegistry | CustomMutatorDefs<any>,\n name: string,\n // oxlint-disable-next-line no-explicit-any\n): CustomMutatorImpl<any> {\n const path = name.split(separatorRe);\n const mutator = getObjectAtPath(mutators, path);\n assert(typeof mutator === 'function', `could not find mutator ${name}`);\n\n if (isMutator(mutator)) {\n // mutator needs to be called with {tx, args, ctx}\n // CustomMutatorImpl is called with (tx, args, ctx)\n return (tx, args, ctx) => mutator.fn({args, ctx, tx});\n }\n\n // oxlint-disable-next-line no-explicit-any\n return mutator as CustomMutatorImpl<any>;\n}\n\nfunction getObjectAtPath(\n obj: Record<string, unknown>,\n path: string[],\n): unknown {\n let current: unknown = obj;\n for (const part of path) {\n if (typeof current !== 'object' || current === null || !(part in current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Processes internal cleanup mutation that deletes acknowledged mutation results\n * from the upstream database. This runs without LMID tracking since it's an\n * internal operation.\n */\nasync function processCleanupResultsMutation<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n mutation: CustomMutation,\n queryParams: Params,\n lc: LogContext,\n): Promise<void> {\n const parseResult = v.test(mutation.args[0], cleanupResultsArgSchema);\n if (!parseResult.ok) {\n lc.warn?.('Cleanup mutation has invalid args', parseResult.error);\n return;\n }\n const args: CleanupResultsArg = parseResult.value;\n\n // Determine clientID for transaction input based on cleanup type\n // Note: legacy format without type field is treated as single\n const clientID =\n 'type' in args && args.type === 'bulk' ? args.clientIDs[0] : args.clientID;\n\n // Run in a transaction, using the hook for DB-specific operation.\n // Note: only upstreamSchema is used by deleteMutationResults; the other\n // fields are required by the interface but ignored for this operation.\n await dbProvider.transaction(\n async (_, hooks) => {\n await hooks.deleteMutationResults(args);\n },\n {\n upstreamSchema: queryParams.schema,\n clientGroupID: args.clientGroupID,\n clientID,\n mutationID: 0,\n },\n );\n}\n\ntype DatabaseTransactionPhase = 'open' | 'execute';\nclass DatabaseTransactionError extends Error {\n constructor(phase: DatabaseTransactionPhase, options?: ErrorOptions) {\n super(\n phase === 'open'\n ? `Failed to open database transaction: ${getErrorMessage(options?.cause)}`\n : `Database transaction failed after opening: ${getErrorMessage(options?.cause)}`,\n options,\n );\n this.name = 'DatabaseTransactionError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAoFA,IAAM,0BAA0B,OAAU,OAAqC;AAC7E,KAAI;AACF,SAAO,MAAM,IAAI;UACV,OAAO;AACd,MACE,iBAAiB,4BACjB,iBAAiB,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AEzC;EACE,gBAAgB,YAAY;EAC5B,eAAe,KAAK;EACpB;EACA,YAAY;EACb,CACF;;AAIH,IAAM,2BAAN,cAAuC,MAAM;CAC3C,YAAY,OAAiC,SAAwB;AACnE,QACE,UAAU,SACN,wCAAwC,gBAAgB,SAAS,MAAM,KACvE,8CAA8C,gBAAgB,SAAS,MAAM,IACjF,QACD;AACD,OAAK,OAAO"}
@@ -5,6 +5,7 @@ import { type Database, type ExtractTransactionType } from '../../zero-server/sr
5
5
  import type { Schema } from '../../zero-types/src/schema.ts';
6
6
  import type { AnyMutatorRegistry } from '../../zql/src/mutate/mutator-registry.ts';
7
7
  import type { CustomMutatorDefs } from './custom.ts';
8
+ export declare const separatorRe: RegExp;
8
9
  export declare class PushProcessor<_S extends Schema, D extends Database<ExtractTransactionType<D>>, MD extends AnyMutatorRegistry | CustomMutatorDefs<ExtractTransactionType<D>>, C = undefined> {
9
10
  #private;
10
11
  constructor(dbProvider: D, context?: C, logLevel?: LogLevel);
@@ -1 +1 @@
1
- {"version":3,"file":"push-processor.d.ts","sourceRoot":"","sources":["../../../../zero-server/src/push-processor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,QAAQ,EAAC,MAAM,kBAAkB,CAAC;AAE/C,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAGhE,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,sBAAsB,EAG5B,MAAM,4CAA4C,CAAC;AACpD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAE3D,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,0CAA0C,CAAC;AAEjF,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,aAAa,CAAC;AAEnD,qBAAa,aAAa,CACxB,EAAE,SAAS,MAAM,EACjB,CAAC,SAAS,QAAQ,CAAC,sBAAsB,CAAC,CAAC,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C,EAC5E,CAAC,GAAG,SAAS;;gBAMD,UAAU,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,QAAQ,GAAE,QAAiB;IAMnE;;;;;;;;;;OAUG;IACH,OAAO,CACL,QAAQ,EAAE,EAAE,EACZ,WAAW,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACrD,IAAI,EAAE,iBAAiB,GACtB,OAAO,CAAC,YAAY,CAAC;IAExB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC;CAqD/D"}
@@ -6,6 +6,7 @@ import "../../zero-protocol/src/push.js";
6
6
  import { handleMutateRequest } from "./process-mutations.js";
7
7
  import "@rocicorp/logger";
8
8
  //#region ../zero-server/src/push-processor.ts
9
+ var separatorRe = /[.|]/;
9
10
  var PushProcessor = class {
10
11
  #dbProvider;
11
12
  #logLevel;
@@ -23,7 +24,7 @@ var PushProcessor = class {
23
24
  return transact((tx, name, args) => this.#dispatchMutation(mutators, tx, name, args));
24
25
  }
25
26
  #dispatchMutation(mutators, dbTx, key, args) {
26
- const mutator = getValueAtPath(mutators, key, /\.|\|/);
27
+ const mutator = getValueAtPath(mutators, key, separatorRe);
27
28
  assert(typeof mutator === "function", `could not find mutator ${key}`);
28
29
  if (isMutator(mutator)) return mutator.fn({
29
30
  args,
@@ -34,6 +35,6 @@ var PushProcessor = class {
34
35
  }
35
36
  };
36
37
  //#endregion
37
- export { PushProcessor };
38
+ export { PushProcessor, separatorRe };
38
39
 
39
40
  //# sourceMappingURL=push-processor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"push-processor.js","names":["#dbProvider","#logLevel","#context","#processMutation","#dispatchMutation"],"sources":["../../../../zero-server/src/push-processor.ts"],"sourcesContent":["import {type LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport {getValueAtPath} from '../../shared/src/object-traversal.ts';\nimport {\n type CustomMutation,\n type MutationResponse,\n type PushResponse,\n} from '../../zero-protocol/src/push.ts';\nimport {\n type Database,\n type ExtractTransactionType,\n handleMutateRequest,\n type TransactFn,\n} from '../../zero-server/src/process-mutations.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {Transaction} from '../../zql/src/mutate/custom.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\n\nexport class PushProcessor<\n _S extends Schema,\n D extends Database<ExtractTransactionType<D>>,\n MD extends AnyMutatorRegistry | CustomMutatorDefs<ExtractTransactionType<D>>,\n C = undefined,\n> {\n readonly #dbProvider: D;\n readonly #logLevel: LogLevel;\n readonly #context: C;\n\n constructor(dbProvider: D, context?: C, logLevel: LogLevel = 'info') {\n this.#dbProvider = dbProvider;\n this.#context = context as C;\n this.#logLevel = logLevel;\n }\n\n /**\n * Processes a push request from zero-cache.\n * This function will parse the request, check the protocol version, and process each mutation in the request.\n * - If a mutation is out of order: processing will stop and an error will be returned. The zero client will retry the mutation.\n * - If a mutation has already been processed: it will be skipped and the processing will continue.\n * - If a mutation receives an application error: it will be skipped, the error will be returned to the client, and processing will continue.\n *\n * @param mutators the custom mutators for the application\n * @param queryString the query string from the request sent by zero-cache. This will include zero's postgres schema name and appID.\n * @param body the body of the request sent by zero-cache as a JSON object.\n */\n process(\n mutators: MD,\n queryString: URLSearchParams | Record<string, string>,\n body: ReadonlyJSONValue,\n ): Promise<PushResponse>;\n\n /**\n * This override gets the query string and the body from a Request object.\n *\n * @param mutators the custom mutators for the application\n * @param request A `Request` object.\n */\n process(mutators: MD, request: Request): Promise<PushResponse>;\n process(\n mutators: MD,\n queryOrQueryString: Request | URLSearchParams | Record<string, string>,\n body?: ReadonlyJSONValue,\n ): Promise<PushResponse> {\n if (queryOrQueryString instanceof Request) {\n return handleMutateRequest(\n this.#dbProvider,\n (transact, mutation) =>\n this.#processMutation(mutators, transact, mutation),\n queryOrQueryString,\n this.#logLevel,\n );\n }\n return handleMutateRequest(\n this.#dbProvider,\n (transact, mutation) =>\n this.#processMutation(mutators, transact, mutation),\n queryOrQueryString,\n must(body, 'body is required when using query params directly'),\n this.#logLevel,\n );\n }\n\n #processMutation(\n mutators: MD,\n transact: TransactFn<D>,\n _mutation: CustomMutation,\n ): Promise<MutationResponse> {\n return transact((tx, name, args) =>\n this.#dispatchMutation(mutators, tx, name, args),\n );\n }\n\n #dispatchMutation(\n mutators: MD,\n dbTx: ExtractTransactionType<D>,\n key: string,\n args: ReadonlyJSONValue | undefined,\n ): Promise<void> {\n // Legacy mutators used | as a separator, new mutators use .\n const mutator = getValueAtPath(mutators, key, /\\.|\\|/);\n assert(typeof mutator === 'function', `could not find mutator ${key}`);\n if (isMutator(mutator)) {\n return mutator.fn({\n args,\n ctx: this.#context,\n tx: dbTx as Transaction<Schema, unknown>,\n });\n }\n return mutator(dbTx, args);\n }\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,gBAAb,MAKE;CACA;CACA;CACA;CAEA,YAAY,YAAe,SAAa,WAAqB,QAAQ;AACnE,QAAA,aAAmB;AACnB,QAAA,UAAgB;AAChB,QAAA,WAAiB;;CA2BnB,QACE,UACA,oBACA,MACuB;AACvB,MAAI,8BAA8B,QAChC,QAAO,oBACL,MAAA,aACC,UAAU,aACT,MAAA,gBAAsB,UAAU,UAAU,SAAS,EACrD,oBACA,MAAA,SACD;AAEH,SAAO,oBACL,MAAA,aACC,UAAU,aACT,MAAA,gBAAsB,UAAU,UAAU,SAAS,EACrD,oBACA,KAAK,MAAM,oDAAoD,EAC/D,MAAA,SACD;;CAGH,iBACE,UACA,UACA,WAC2B;AAC3B,SAAO,UAAU,IAAI,MAAM,SACzB,MAAA,iBAAuB,UAAU,IAAI,MAAM,KAAK,CACjD;;CAGH,kBACE,UACA,MACA,KACA,MACe;EAEf,MAAM,UAAU,eAAe,UAAU,KAAK,QAAQ;AACtD,SAAO,OAAO,YAAY,YAAY,0BAA0B,MAAM;AACtE,MAAI,UAAU,QAAQ,CACpB,QAAO,QAAQ,GAAG;GAChB;GACA,KAAK,MAAA;GACL,IAAI;GACL,CAAC;AAEJ,SAAO,QAAQ,MAAM,KAAK"}
1
+ {"version":3,"file":"push-processor.js","names":["#dbProvider","#logLevel","#context","#processMutation","#dispatchMutation"],"sources":["../../../../zero-server/src/push-processor.ts"],"sourcesContent":["import {type LogLevel} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport {getValueAtPath} from '../../shared/src/object-traversal.ts';\nimport {\n type CustomMutation,\n type MutationResponse,\n type PushResponse,\n} from '../../zero-protocol/src/push.ts';\nimport {\n type Database,\n type ExtractTransactionType,\n handleMutateRequest,\n type TransactFn,\n} from '../../zero-server/src/process-mutations.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {Transaction} from '../../zql/src/mutate/custom.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs} from './custom.ts';\n\nexport const separatorRe = /[.|]/;\n\nexport class PushProcessor<\n _S extends Schema,\n D extends Database<ExtractTransactionType<D>>,\n MD extends AnyMutatorRegistry | CustomMutatorDefs<ExtractTransactionType<D>>,\n C = undefined,\n> {\n readonly #dbProvider: D;\n readonly #logLevel: LogLevel;\n readonly #context: C;\n\n constructor(dbProvider: D, context?: C, logLevel: LogLevel = 'info') {\n this.#dbProvider = dbProvider;\n this.#context = context as C;\n this.#logLevel = logLevel;\n }\n\n /**\n * Processes a push request from zero-cache.\n * This function will parse the request, check the protocol version, and process each mutation in the request.\n * - If a mutation is out of order: processing will stop and an error will be returned. The zero client will retry the mutation.\n * - If a mutation has already been processed: it will be skipped and the processing will continue.\n * - If a mutation receives an application error: it will be skipped, the error will be returned to the client, and processing will continue.\n *\n * @param mutators the custom mutators for the application\n * @param queryString the query string from the request sent by zero-cache. This will include zero's postgres schema name and appID.\n * @param body the body of the request sent by zero-cache as a JSON object.\n */\n process(\n mutators: MD,\n queryString: URLSearchParams | Record<string, string>,\n body: ReadonlyJSONValue,\n ): Promise<PushResponse>;\n\n /**\n * This override gets the query string and the body from a Request object.\n *\n * @param mutators the custom mutators for the application\n * @param request A `Request` object.\n */\n process(mutators: MD, request: Request): Promise<PushResponse>;\n process(\n mutators: MD,\n queryOrQueryString: Request | URLSearchParams | Record<string, string>,\n body?: ReadonlyJSONValue,\n ): Promise<PushResponse> {\n if (queryOrQueryString instanceof Request) {\n return handleMutateRequest(\n this.#dbProvider,\n (transact, mutation) =>\n this.#processMutation(mutators, transact, mutation),\n queryOrQueryString,\n this.#logLevel,\n );\n }\n return handleMutateRequest(\n this.#dbProvider,\n (transact, mutation) =>\n this.#processMutation(mutators, transact, mutation),\n queryOrQueryString,\n must(body, 'body is required when using query params directly'),\n this.#logLevel,\n );\n }\n\n #processMutation(\n mutators: MD,\n transact: TransactFn<D>,\n _mutation: CustomMutation,\n ): Promise<MutationResponse> {\n return transact((tx, name, args) =>\n this.#dispatchMutation(mutators, tx, name, args),\n );\n }\n\n #dispatchMutation(\n mutators: MD,\n dbTx: ExtractTransactionType<D>,\n key: string,\n args: ReadonlyJSONValue | undefined,\n ): Promise<void> {\n // Legacy mutators used | as a separator, new mutators use .\n const mutator = getValueAtPath(mutators, key, separatorRe);\n assert(typeof mutator === 'function', `could not find mutator ${key}`);\n if (isMutator(mutator)) {\n return mutator.fn({\n args,\n ctx: this.#context,\n tx: dbTx as Transaction<Schema, unknown>,\n });\n }\n return mutator(dbTx, args);\n }\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,cAAc;AAE3B,IAAa,gBAAb,MAKE;CACA;CACA;CACA;CAEA,YAAY,YAAe,SAAa,WAAqB,QAAQ;AACnE,QAAA,aAAmB;AACnB,QAAA,UAAgB;AAChB,QAAA,WAAiB;;CA2BnB,QACE,UACA,oBACA,MACuB;AACvB,MAAI,8BAA8B,QAChC,QAAO,oBACL,MAAA,aACC,UAAU,aACT,MAAA,gBAAsB,UAAU,UAAU,SAAS,EACrD,oBACA,MAAA,SACD;AAEH,SAAO,oBACL,MAAA,aACC,UAAU,aACT,MAAA,gBAAsB,UAAU,UAAU,SAAS,EACrD,oBACA,KAAK,MAAM,oDAAoD,EAC/D,MAAA,SACD;;CAGH,iBACE,UACA,UACA,WAC2B;AAC3B,SAAO,UAAU,IAAI,MAAM,SACzB,MAAA,iBAAuB,UAAU,IAAI,MAAM,KAAK,CACjD;;CAGH,kBACE,UACA,MACA,KACA,MACe;EAEf,MAAM,UAAU,eAAe,UAAU,KAAK,YAAY;AAC1D,SAAO,OAAO,YAAY,YAAY,0BAA0B,MAAM;AACtE,MAAI,UAAU,QAAQ,CACpB,QAAO,QAAQ,GAAG;GAChB;GACA,KAAK,MAAA;GACL,IAAI;GACL,CAAC;AAEJ,SAAO,QAAQ,MAAM,KAAK"}
@@ -12,6 +12,7 @@ export declare class NameMapper {
12
12
  #private;
13
13
  constructor(tables: Map<string, DestNames>);
14
14
  tableName(src: string, context?: JSONValue): string;
15
+ tableNameIfKnown(src: string): string | undefined;
15
16
  columnName(table: string, src: string, ctx?: JSONValue): string;
16
17
  row<V extends Value>(table: string, row: Readonly<Record<string, V>>): Readonly<Record<string, V>>;
17
18
  columns<Columns extends readonly string[] | undefined>(table: string, cols: Columns): Columns;