@rocicorp/zero 0.5.2024110200 → 0.6.2024111600

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 (330) hide show
  1. package/out/{internal.js → advanced.js} +1 -1
  2. package/out/{chunk-INJ4WJHS.js → chunk-V5NTGJ4X.js} +1152 -585
  3. package/out/chunk-V5NTGJ4X.js.map +7 -0
  4. package/out/react.js.map +2 -2
  5. package/out/shared/src/browser-env.d.ts +17 -0
  6. package/out/shared/src/browser-env.d.ts.map +1 -1
  7. package/out/shared/src/expand.d.ts +7 -0
  8. package/out/shared/src/expand.d.ts.map +1 -0
  9. package/out/solid.js +4 -4
  10. package/out/solid.js.map +2 -2
  11. package/out/zero-cache/src/auth/load-authorization.d.ts +3 -0
  12. package/out/zero-cache/src/auth/load-authorization.d.ts.map +1 -0
  13. package/out/zero-cache/src/auth/load-authorization.js +21 -0
  14. package/out/zero-cache/src/auth/load-authorization.js.map +1 -0
  15. package/out/zero-cache/src/config/config.d.ts +112 -0
  16. package/out/zero-cache/src/config/config.d.ts.map +1 -0
  17. package/out/zero-cache/src/config/config.js +246 -0
  18. package/out/zero-cache/src/config/config.js.map +1 -0
  19. package/out/zero-cache/src/config/zero-config.d.ts +145 -964
  20. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  21. package/out/zero-cache/src/config/zero-config.js +242 -115
  22. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  23. package/out/zero-cache/src/db/delete-lite-db.d.ts +2 -0
  24. package/out/zero-cache/src/db/delete-lite-db.d.ts.map +1 -0
  25. package/out/zero-cache/src/db/delete-lite-db.js +7 -0
  26. package/out/zero-cache/src/db/delete-lite-db.js.map +1 -0
  27. package/out/zero-cache/src/db/migration.d.ts +1 -0
  28. package/out/zero-cache/src/db/migration.d.ts.map +1 -1
  29. package/out/zero-cache/src/db/migration.js +17 -7
  30. package/out/zero-cache/src/db/migration.js.map +1 -1
  31. package/out/zero-cache/src/db/pg-to-lite.d.ts +1 -1
  32. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  33. package/out/zero-cache/src/db/pg-to-lite.js +7 -3
  34. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  35. package/out/zero-cache/src/db/short-lived-client.d.ts +16 -0
  36. package/out/zero-cache/src/db/short-lived-client.d.ts.map +1 -0
  37. package/out/zero-cache/src/db/short-lived-client.js +50 -0
  38. package/out/zero-cache/src/db/short-lived-client.js.map +1 -0
  39. package/out/zero-cache/src/db/specs.d.ts +12 -3
  40. package/out/zero-cache/src/db/specs.d.ts.map +1 -1
  41. package/out/zero-cache/src/db/specs.js +6 -1
  42. package/out/zero-cache/src/db/specs.js.map +1 -1
  43. package/out/zero-cache/src/db/transaction-pool.d.ts +7 -2
  44. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  45. package/out/zero-cache/src/db/transaction-pool.js +42 -8
  46. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  47. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  48. package/out/zero-cache/src/server/change-streamer.js +34 -9
  49. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  50. package/out/zero-cache/src/server/life-cycle.d.ts +1 -1
  51. package/out/zero-cache/src/server/life-cycle.d.ts.map +1 -1
  52. package/out/zero-cache/src/server/life-cycle.js +2 -3
  53. package/out/zero-cache/src/server/life-cycle.js.map +1 -1
  54. package/out/zero-cache/src/server/logging.d.ts.map +1 -1
  55. package/out/zero-cache/src/server/logging.js +2 -15
  56. package/out/zero-cache/src/server/logging.js.map +1 -1
  57. package/out/zero-cache/src/server/main.js +28 -10
  58. package/out/zero-cache/src/server/main.js.map +1 -1
  59. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  60. package/out/zero-cache/src/server/replicator.js +6 -5
  61. package/out/zero-cache/src/server/replicator.js.map +1 -1
  62. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  63. package/out/zero-cache/src/server/syncer.js +16 -12
  64. package/out/zero-cache/src/server/syncer.js.map +1 -1
  65. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -3
  66. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  67. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +2 -3
  68. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  69. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +153 -2
  70. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  71. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +136 -19
  72. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  73. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +17 -9
  74. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/change-streamer/change-streamer.js +4 -2
  76. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +1 -0
  78. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/forwarder.js +9 -2
  80. package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/pg/change-source.d.ts +10 -0
  82. package/out/zero-cache/src/services/change-streamer/pg/change-source.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/change-streamer/pg/change-source.js +171 -24
  84. package/out/zero-cache/src/services/change-streamer/pg/change-source.js.map +1 -1
  85. package/out/zero-cache/src/services/change-streamer/pg/initial-sync.d.ts.map +1 -1
  86. package/out/zero-cache/src/services/change-streamer/pg/initial-sync.js +32 -18
  87. package/out/zero-cache/src/services/change-streamer/pg/initial-sync.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/pg/schema/ddl.d.ts +62 -39
  89. package/out/zero-cache/src/services/change-streamer/pg/schema/ddl.d.ts.map +1 -1
  90. package/out/zero-cache/src/services/change-streamer/pg/schema/ddl.js +8 -40
  91. package/out/zero-cache/src/services/change-streamer/pg/schema/ddl.js.map +1 -1
  92. package/out/zero-cache/src/services/change-streamer/pg/schema/init.d.ts +8 -0
  93. package/out/zero-cache/src/services/change-streamer/pg/schema/init.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/change-streamer/pg/schema/init.js +41 -8
  95. package/out/zero-cache/src/services/change-streamer/pg/schema/init.js.map +1 -1
  96. package/out/zero-cache/src/services/change-streamer/pg/schema/published.d.ts +83 -13
  97. package/out/zero-cache/src/services/change-streamer/pg/schema/published.d.ts.map +1 -1
  98. package/out/zero-cache/src/services/change-streamer/pg/schema/published.js +15 -5
  99. package/out/zero-cache/src/services/change-streamer/pg/schema/published.js.map +1 -1
  100. package/out/zero-cache/src/services/change-streamer/pg/schema/shard.d.ts +39 -3
  101. package/out/zero-cache/src/services/change-streamer/pg/schema/shard.d.ts.map +1 -1
  102. package/out/zero-cache/src/services/change-streamer/pg/schema/shard.js +67 -36
  103. package/out/zero-cache/src/services/change-streamer/pg/schema/shard.js.map +1 -1
  104. package/out/zero-cache/src/services/change-streamer/pg/schema/validation.d.ts +8 -0
  105. package/out/zero-cache/src/services/change-streamer/pg/schema/validation.d.ts.map +1 -0
  106. package/out/zero-cache/src/services/change-streamer/pg/schema/validation.js +33 -0
  107. package/out/zero-cache/src/services/change-streamer/pg/schema/validation.js.map +1 -0
  108. package/out/zero-cache/src/services/change-streamer/schema/change.d.ts +5 -1
  109. package/out/zero-cache/src/services/change-streamer/schema/change.d.ts.map +1 -1
  110. package/out/zero-cache/src/services/change-streamer/schema/change.js +3 -0
  111. package/out/zero-cache/src/services/change-streamer/schema/change.js.map +1 -1
  112. package/out/zero-cache/src/services/change-streamer/schema/init.d.ts.map +1 -1
  113. package/out/zero-cache/src/services/change-streamer/schema/init.js +4 -6
  114. package/out/zero-cache/src/services/change-streamer/schema/init.js.map +1 -1
  115. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +6 -1
  116. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  117. package/out/zero-cache/src/services/change-streamer/schema/tables.js +19 -4
  118. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  119. package/out/zero-cache/src/services/change-streamer/storer.d.ts +29 -2
  120. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  121. package/out/zero-cache/src/services/change-streamer/storer.js +90 -8
  122. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  123. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +1 -0
  124. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  125. package/out/zero-cache/src/services/change-streamer/subscriber.js +18 -3
  126. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  127. package/out/zero-cache/src/services/dispatcher/dispatcher.d.ts +5 -3
  128. package/out/zero-cache/src/services/dispatcher/dispatcher.d.ts.map +1 -1
  129. package/out/zero-cache/src/services/dispatcher/dispatcher.js +20 -5
  130. package/out/zero-cache/src/services/dispatcher/dispatcher.js.map +1 -1
  131. package/out/zero-cache/src/services/mutagen/mutagen.d.ts +6 -5
  132. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  133. package/out/zero-cache/src/services/mutagen/mutagen.js +26 -20
  134. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  135. package/out/zero-cache/src/services/mutagen/write-authorizer.d.ts +7 -6
  136. package/out/zero-cache/src/services/mutagen/write-authorizer.d.ts.map +1 -1
  137. package/out/zero-cache/src/services/mutagen/write-authorizer.js +10 -18
  138. package/out/zero-cache/src/services/mutagen/write-authorizer.js.map +1 -1
  139. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
  140. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  141. package/out/zero-cache/src/services/replicator/incremental-sync.js +8 -8
  142. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  143. package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts.map +1 -1
  144. package/out/zero-cache/src/services/replicator/schema/replication-state.js +1 -10
  145. package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
  146. package/out/zero-cache/src/services/running-state.d.ts +6 -1
  147. package/out/zero-cache/src/services/running-state.d.ts.map +1 -1
  148. package/out/zero-cache/src/services/running-state.js +23 -5
  149. package/out/zero-cache/src/services/running-state.js.map +1 -1
  150. package/out/zero-cache/src/services/view-syncer/schema/types.d.ts +49 -29
  151. package/out/zero-cache/src/services/view-syncer/schema/types.d.ts.map +1 -1
  152. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  153. package/out/zero-cache/src/services/view-syncer/view-syncer.js +2 -1
  154. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  155. package/out/zero-cache/src/types/lexi-version.d.ts +3 -2
  156. package/out/zero-cache/src/types/lexi-version.d.ts.map +1 -1
  157. package/out/zero-cache/src/types/lexi-version.js +8 -6
  158. package/out/zero-cache/src/types/lexi-version.js.map +1 -1
  159. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  160. package/out/zero-cache/src/types/processes.js +1 -0
  161. package/out/zero-cache/src/types/processes.js.map +1 -1
  162. package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
  163. package/out/zero-cache/src/workers/replicator.js +2 -4
  164. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  165. package/out/zero-cache/src/workers/syncer.js +1 -1
  166. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  167. package/out/zero-client/src/client/crud.d.ts +56 -25
  168. package/out/zero-client/src/client/crud.d.ts.map +1 -1
  169. package/out/zero-client/src/client/http-string.d.ts +1 -0
  170. package/out/zero-client/src/client/http-string.d.ts.map +1 -1
  171. package/out/zero-client/src/client/log-options.d.ts +2 -1
  172. package/out/zero-client/src/client/log-options.d.ts.map +1 -1
  173. package/out/zero-client/src/client/options.d.ts +8 -8
  174. package/out/zero-client/src/client/options.d.ts.map +1 -1
  175. package/out/zero-client/src/client/protocol-version.d.ts +2 -0
  176. package/out/zero-client/src/client/protocol-version.d.ts.map +1 -0
  177. package/out/zero-client/src/client/server-option.d.ts.map +1 -1
  178. package/out/zero-client/src/client/zero-poke-handler.d.ts +1 -1
  179. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  180. package/out/zero-client/src/client/zero.d.ts +26 -14
  181. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  182. package/out/zero-client/src/mod.d.ts +4 -2
  183. package/out/zero-client/src/mod.d.ts.map +1 -1
  184. package/out/zero-protocol/src/ast.d.ts +37 -21
  185. package/out/zero-protocol/src/ast.d.ts.map +1 -1
  186. package/out/zero-protocol/src/ast.js +21 -6
  187. package/out/zero-protocol/src/ast.js.map +1 -1
  188. package/out/zero-protocol/src/change-desired-queries.d.ts +16 -8
  189. package/out/zero-protocol/src/change-desired-queries.d.ts.map +1 -1
  190. package/out/zero-protocol/src/connect.d.ts +16 -8
  191. package/out/zero-protocol/src/connect.d.ts.map +1 -1
  192. package/out/zero-protocol/src/down.d.ts +16 -8
  193. package/out/zero-protocol/src/down.d.ts.map +1 -1
  194. package/out/zero-protocol/src/poke.d.ts +32 -16
  195. package/out/zero-protocol/src/poke.d.ts.map +1 -1
  196. package/out/zero-protocol/src/push.d.ts +18 -18
  197. package/out/zero-protocol/src/push.d.ts.map +1 -1
  198. package/out/zero-protocol/src/push.js +5 -5
  199. package/out/zero-protocol/src/push.js.map +1 -1
  200. package/out/zero-protocol/src/queries-patch.d.ts +24 -12
  201. package/out/zero-protocol/src/queries-patch.d.ts.map +1 -1
  202. package/out/zero-protocol/src/up.d.ts +18 -10
  203. package/out/zero-protocol/src/up.d.ts.map +1 -1
  204. package/out/zero-react/src/use-zero.d.ts.map +1 -1
  205. package/out/zero-schema/src/authorization.d.ts +25 -0
  206. package/out/zero-schema/src/authorization.d.ts.map +1 -0
  207. package/out/zero-schema/src/compiled-authorization.d.ts +379 -0
  208. package/out/zero-schema/src/compiled-authorization.d.ts.map +1 -0
  209. package/out/zero-schema/src/compiled-authorization.js +15 -0
  210. package/out/zero-schema/src/compiled-authorization.js.map +1 -0
  211. package/out/zero-schema/src/mod.d.ts +1 -0
  212. package/out/zero-schema/src/mod.d.ts.map +1 -1
  213. package/out/{zero-client/src/client → zero-schema/src}/normalized-schema.d.ts +2 -2
  214. package/out/zero-schema/src/normalized-schema.d.ts.map +1 -0
  215. package/out/zero-schema/src/table-schema.d.ts +15 -7
  216. package/out/zero-schema/src/table-schema.d.ts.map +1 -1
  217. package/out/zero-schema/src/table-schema.js.map +1 -1
  218. package/out/zero.js +9 -13
  219. package/out/zql/src/builder/builder.d.ts +1 -1
  220. package/out/zql/src/builder/builder.d.ts.map +1 -1
  221. package/out/zql/src/builder/builder.js +74 -30
  222. package/out/zql/src/builder/builder.js.map +1 -1
  223. package/out/zql/src/builder/filter.d.ts +2 -1
  224. package/out/zql/src/builder/filter.d.ts.map +1 -1
  225. package/out/zql/src/builder/filter.js +18 -0
  226. package/out/zql/src/builder/filter.js.map +1 -1
  227. package/out/zql/src/builder/like.d.ts +2 -2
  228. package/out/zql/src/builder/like.d.ts.map +1 -1
  229. package/out/zql/src/ivm/change.d.ts +1 -0
  230. package/out/zql/src/ivm/change.d.ts.map +1 -1
  231. package/out/zql/src/ivm/change.js +4 -1
  232. package/out/zql/src/ivm/change.js.map +1 -1
  233. package/out/zql/src/ivm/exists.d.ts +18 -0
  234. package/out/zql/src/ivm/exists.d.ts.map +1 -0
  235. package/out/zql/src/ivm/exists.js +186 -0
  236. package/out/zql/src/ivm/exists.js.map +1 -0
  237. package/out/zql/src/ivm/fan-in.d.ts +1 -1
  238. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  239. package/out/zql/src/ivm/fan-in.js +3 -3
  240. package/out/zql/src/ivm/fan-in.js.map +1 -1
  241. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  242. package/out/zql/src/ivm/fan-out.js +4 -7
  243. package/out/zql/src/ivm/fan-out.js.map +1 -1
  244. package/out/zql/src/ivm/filter.js +1 -1
  245. package/out/zql/src/ivm/filter.js.map +1 -1
  246. package/out/zql/src/ivm/memory-source.d.ts +10 -6
  247. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  248. package/out/zql/src/ivm/memory-source.js +60 -75
  249. package/out/zql/src/ivm/memory-source.js.map +1 -1
  250. package/out/zql/src/ivm/skip.js +1 -1
  251. package/out/zql/src/ivm/skip.js.map +1 -1
  252. package/out/zql/src/ivm/take.d.ts +1 -1
  253. package/out/zql/src/ivm/take.d.ts.map +1 -1
  254. package/out/zql/src/ivm/take.js +11 -7
  255. package/out/zql/src/ivm/take.js.map +1 -1
  256. package/out/zql/src/query/auth-query.d.ts +7 -3
  257. package/out/zql/src/query/auth-query.d.ts.map +1 -1
  258. package/out/zql/src/query/dnf.d.ts +10 -0
  259. package/out/zql/src/query/dnf.d.ts.map +1 -0
  260. package/out/zql/src/query/expression.d.ts +40 -23
  261. package/out/zql/src/query/expression.d.ts.map +1 -1
  262. package/out/zql/src/query/query-impl.d.ts +7 -6
  263. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  264. package/out/zql/src/query/query.d.ts +17 -46
  265. package/out/zql/src/query/query.d.ts.map +1 -1
  266. package/out/zqlite/src/db.d.ts.map +1 -1
  267. package/out/zqlite/src/db.js +19 -6
  268. package/out/zqlite/src/db.js.map +1 -1
  269. package/out/zqlite/src/table-source.d.ts +12 -3
  270. package/out/zqlite/src/table-source.d.ts.map +1 -1
  271. package/out/zqlite/src/table-source.js +81 -2
  272. package/out/zqlite/src/table-source.js.map +1 -1
  273. package/package.json +7 -11
  274. package/out/chunk-INJ4WJHS.js.map +0 -7
  275. package/out/datadog/src/datadog-log-sink.js +0 -231
  276. package/out/datadog/src/datadog-log-sink.js.map +0 -1
  277. package/out/datadog/src/mod.js +0 -2
  278. package/out/datadog/src/mod.js.map +0 -1
  279. package/out/shared/src/immutable.js +0 -2
  280. package/out/shared/src/immutable.js.map +0 -1
  281. package/out/shared/src/sorted-entries.js +0 -6
  282. package/out/shared/src/sorted-entries.js.map +0 -1
  283. package/out/shared/src/writable.js +0 -2
  284. package/out/shared/src/writable.js.map +0 -1
  285. package/out/zero/src/config.d.ts +0 -2
  286. package/out/zero/src/config.d.ts.map +0 -1
  287. package/out/zero/src/config.js +0 -2
  288. package/out/zero/src/config.js.map +0 -1
  289. package/out/zero-cache/src/config/config-query.d.ts +0 -19
  290. package/out/zero-cache/src/config/config-query.d.ts.map +0 -1
  291. package/out/zero-cache/src/config/config-query.js +0 -22
  292. package/out/zero-cache/src/config/config-query.js.map +0 -1
  293. package/out/zero-cache/src/config/define-config.d.ts +0 -43
  294. package/out/zero-cache/src/config/define-config.d.ts.map +0 -1
  295. package/out/zero-cache/src/config/define-config.js +0 -121
  296. package/out/zero-cache/src/config/define-config.js.map +0 -1
  297. package/out/zero-cache/src/config/refs.d.ts +0 -3
  298. package/out/zero-cache/src/config/refs.d.ts.map +0 -1
  299. package/out/zero-cache/src/config/refs.js +0 -14
  300. package/out/zero-cache/src/config/refs.js.map +0 -1
  301. package/out/zero-client/src/client/normalized-schema.d.ts.map +0 -1
  302. package/out/zero-client/src/client/normalized-schema.js +0 -31
  303. package/out/zero-client/src/client/normalized-schema.js.map +0 -1
  304. package/out/zero-protocol/src/ast-hash.js +0 -14
  305. package/out/zero-protocol/src/ast-hash.js.map +0 -1
  306. package/out/zero-schema/src/mod.js +0 -4
  307. package/out/zero-schema/src/mod.js.map +0 -1
  308. package/out/zero-schema/src/normalize-table-schema.js +0 -116
  309. package/out/zero-schema/src/normalize-table-schema.js.map +0 -1
  310. package/out/zero-schema/src/schema.js +0 -4
  311. package/out/zero-schema/src/schema.js.map +0 -1
  312. package/out/zql/src/ivm/array-view.js +0 -70
  313. package/out/zql/src/ivm/array-view.js.map +0 -1
  314. package/out/zql/src/ivm/view-apply-change.js +0 -156
  315. package/out/zql/src/ivm/view-apply-change.js.map +0 -1
  316. package/out/zql/src/ivm/view.js +0 -2
  317. package/out/zql/src/ivm/view.js.map +0 -1
  318. package/out/zql/src/query/auth-query.js +0 -26
  319. package/out/zql/src/query/auth-query.js.map +0 -1
  320. package/out/zql/src/query/expression.js +0 -121
  321. package/out/zql/src/query/expression.js.map +0 -1
  322. package/out/zql/src/query/query-impl.js +0 -291
  323. package/out/zql/src/query/query-impl.js.map +0 -1
  324. package/out/zql/src/query/query-internal.js +0 -2
  325. package/out/zql/src/query/query-internal.js.map +0 -1
  326. package/out/zql/src/query/query.js +0 -3
  327. package/out/zql/src/query/query.js.map +0 -1
  328. package/out/zql/src/query/typed-view.js +0 -2
  329. package/out/zql/src/query/typed-view.js.map +0 -1
  330. /package/out/{internal.js.map → advanced.js.map} +0 -0
@@ -564,6 +564,9 @@ var WriteImplBase = class {
564
564
  function getBrowserGlobal(name) {
565
565
  return globalThis[name];
566
566
  }
567
+ function getBrowserGlobalMethod(name) {
568
+ return globalThis[name]?.bind(globalThis);
569
+ }
567
570
  function mustGetBrowserGlobal(name) {
568
571
  const r = getBrowserGlobal(name);
569
572
  if (r === void 0) {
@@ -9236,121 +9239,186 @@ function getKVStoreProvider(lc, kvStore) {
9236
9239
  // ../replicache/src/mod.ts
9237
9240
  import { consoleLogSink as consoleLogSink3 } from "@rocicorp/logger";
9238
9241
 
9239
- // ../zql/src/query/expression.ts
9240
- function cmp(field, opOrValue, value) {
9241
- let op;
9242
- if (value === void 0) {
9243
- value = opOrValue;
9244
- op = "=";
9245
- } else {
9246
- op = opOrValue;
9242
+ // ../zero-schema/src/table-schema.ts
9243
+ function createTableSchema(schema) {
9244
+ return schema;
9245
+ }
9246
+ function isFieldRelationship(relationship) {
9247
+ return relationship.junction === void 0;
9248
+ }
9249
+ function isJunctionRelationship(relationship) {
9250
+ return !isFieldRelationship(relationship);
9251
+ }
9252
+
9253
+ // ../shared/src/sorted-entries.ts
9254
+ function sortedEntries(object16) {
9255
+ return Object.entries(object16).sort((a, b) => stringCompare(a[0], b[0]));
9256
+ }
9257
+
9258
+ // ../zero-schema/src/normalize-table-schema.ts
9259
+ var NormalizedTableSchema = class {
9260
+ tableName;
9261
+ primaryKey;
9262
+ columns;
9263
+ relationships;
9264
+ constructor(tableSchema, tableSchemaCache) {
9265
+ this.tableName = tableSchema.tableName;
9266
+ const primaryKey = normalizePrimaryKey(tableSchema.primaryKey);
9267
+ this.primaryKey = primaryKey;
9268
+ this.columns = normalizeColumns(tableSchema.columns, primaryKey);
9269
+ tableSchemaCache.set(tableSchema, this);
9270
+ this.relationships = normalizeRelationships(
9271
+ tableSchema.relationships,
9272
+ tableSchemaCache
9273
+ );
9247
9274
  }
9248
- return {
9249
- type: "simple",
9250
- field,
9251
- op,
9252
- value
9253
- };
9275
+ };
9276
+ function normalizeTableSchema(tableSchema) {
9277
+ return normalizeTableSchemaWithCache(
9278
+ tableSchema,
9279
+ tableSchema.tableName,
9280
+ /* @__PURE__ */ new Map()
9281
+ );
9254
9282
  }
9255
- function and(...conditions) {
9256
- if (conditions.length === 1) {
9257
- return conditions[0];
9283
+ function normalizeTableSchemaWithCache(tableSchema, expectedName, tableSchemaCache) {
9284
+ if (tableSchema instanceof NormalizedTableSchema) {
9285
+ return tableSchema;
9258
9286
  }
9259
- const ands = conditions.flatMap((c) => {
9260
- if (c.type === "and") {
9261
- return c.conditions;
9262
- } else if (c.type === "simple") {
9263
- return [c];
9264
- }
9265
- return [];
9266
- });
9267
- const ors = conditions.filter(
9268
- (c) => c.type === "or"
9287
+ assert(
9288
+ tableSchema.tableName === expectedName,
9289
+ `Table name mismatch: "${tableSchema.tableName}" !== "${expectedName}"`
9290
+ );
9291
+ let normalizedTableSchema = tableSchemaCache.get(tableSchema);
9292
+ if (normalizedTableSchema) {
9293
+ return normalizedTableSchema;
9294
+ }
9295
+ normalizedTableSchema = new NormalizedTableSchema(
9296
+ tableSchema,
9297
+ tableSchemaCache
9269
9298
  );
9270
- if (ors.length === 0) {
9271
- return { type: "and", conditions: ands };
9299
+ return normalizedTableSchema;
9300
+ }
9301
+ function isSorted(arr) {
9302
+ for (let i = 1; i < arr.length; i++) {
9303
+ if (arr[i - 1] >= arr[i]) {
9304
+ return false;
9305
+ }
9306
+ }
9307
+ return true;
9308
+ }
9309
+ function assertNoDuplicates(arr) {
9310
+ for (let i = 1; i < arr.length; i++) {
9311
+ assert(arr[i - 1] !== arr[i], "Primary key must not contain duplicates");
9312
+ }
9313
+ }
9314
+ function normalizePrimaryKey(arr) {
9315
+ if (isSorted(arr)) {
9316
+ return arr;
9317
+ }
9318
+ arr = [...arr].sort();
9319
+ assertNoDuplicates(arr);
9320
+ return arr;
9321
+ }
9322
+ function normalizeColumns(columns, primaryKey) {
9323
+ const rv = {};
9324
+ for (const pk of primaryKey) {
9325
+ const schemaValue = columns[pk];
9326
+ assert(schemaValue, `Primary key column "${pk}" not found`);
9327
+ const { type, optional } = schemaValue;
9328
+ assert(!optional, `Primary key column "${pk}" cannot be optional`);
9329
+ assert(
9330
+ type === "string" || type === "number" || type === "boolean",
9331
+ `Primary key column "${pk}" must be a string, number, or boolean. Got ${type}`
9332
+ );
9272
9333
  }
9273
- const flatOrs = flatten("or", ors);
9274
- const flatAnds = flatten("and", ands);
9334
+ for (const [name, column] of sortedEntries(columns)) {
9335
+ rv[name] = normalizeSchemaValue(column);
9336
+ }
9337
+ return rv;
9338
+ }
9339
+ function normalizeSchemaValue(value) {
9275
9340
  return {
9276
- type: "or",
9277
- conditions: flatOrs.conditions.map((part) => ({
9278
- type: "and",
9279
- conditions: [
9280
- ...part.type === "and" ? part.conditions : [part],
9281
- ...flatAnds.conditions
9282
- ]
9283
- }))
9341
+ type: value.type,
9342
+ optional: value.optional ?? false
9284
9343
  };
9285
9344
  }
9286
- function or(...conditions) {
9287
- if (conditions.length === 1) {
9288
- return conditions[0];
9345
+ function normalizeRelationships(relationships, tableSchemaCache) {
9346
+ const rv = {};
9347
+ for (const [name, relationship] of sortedEntries(relationships)) {
9348
+ rv[name] = normalizeRelationship(relationship, tableSchemaCache);
9289
9349
  }
9290
- return flatten("or", conditions);
9350
+ return rv;
9291
9351
  }
9292
- function not(expr) {
9293
- switch (expr.type) {
9294
- case "and":
9295
- return {
9296
- type: "or",
9297
- conditions: expr.conditions.map(not)
9298
- };
9299
- case "or":
9300
- return {
9301
- type: "and",
9302
- conditions: expr.conditions.map(not)
9303
- };
9304
- default:
9305
- return {
9306
- type: "simple",
9307
- op: negateOperator(expr.op),
9308
- field: expr.field,
9309
- value: expr.value
9310
- };
9352
+ function normalizeRelationship(relationship, tableSchemaCache) {
9353
+ if (isFieldRelationship(relationship)) {
9354
+ return normalizeFieldRelationship(relationship, tableSchemaCache);
9311
9355
  }
9356
+ return normalizeJunctionRelationship(relationship, tableSchemaCache);
9312
9357
  }
9313
- function flatten(type, conditions) {
9314
- const flattened2 = [];
9315
- for (const c of conditions) {
9316
- if (c.type === type) {
9317
- flattened2.push(...c.conditions);
9318
- } else {
9319
- flattened2.push(c);
9358
+ function normalizeFieldRelationship(relationship, tableSchemaCache) {
9359
+ return {
9360
+ source: relationship.source,
9361
+ dest: {
9362
+ field: relationship.dest.field,
9363
+ schema: normalizeLazyTableSchema(
9364
+ relationship.dest.schema,
9365
+ tableSchemaCache
9366
+ )
9320
9367
  }
9321
- }
9368
+ };
9369
+ }
9370
+ function normalizeJunctionRelationship(relationship, tableSchemaCache) {
9322
9371
  return {
9323
- type,
9324
- conditions: flattened2
9372
+ source: relationship.source,
9373
+ junction: {
9374
+ sourceField: relationship.junction.sourceField,
9375
+ destField: relationship.junction.destField,
9376
+ schema: normalizeLazyTableSchema(
9377
+ relationship.junction.schema,
9378
+ tableSchemaCache
9379
+ )
9380
+ },
9381
+ dest: {
9382
+ field: relationship.dest.field,
9383
+ schema: normalizeLazyTableSchema(
9384
+ relationship.dest.schema,
9385
+ tableSchemaCache
9386
+ )
9387
+ }
9325
9388
  };
9326
9389
  }
9327
- function negateOperator(op) {
9328
- switch (op) {
9329
- case "=":
9330
- return "!=";
9331
- case "!=":
9332
- return "=";
9333
- case "<":
9334
- return ">=";
9335
- case ">":
9336
- return "<=";
9337
- case ">=":
9338
- return "<";
9339
- case "<=":
9340
- return ">";
9341
- case "IN":
9342
- return "NOT IN";
9343
- case "NOT IN":
9344
- return "IN";
9345
- case "LIKE":
9346
- return "NOT LIKE";
9347
- case "NOT LIKE":
9348
- return "LIKE";
9349
- case "ILIKE":
9350
- return "NOT ILIKE";
9351
- case "NOT ILIKE":
9352
- return "ILIKE";
9390
+ function normalizeLazyTableSchema(tableSchema, buildCache) {
9391
+ const tableSchemaInstance = typeof tableSchema === "function" ? tableSchema() : tableSchema;
9392
+ return normalizeTableSchemaWithCache(
9393
+ tableSchemaInstance,
9394
+ tableSchemaInstance.tableName,
9395
+ // Don't care about name here.
9396
+ buildCache
9397
+ );
9398
+ }
9399
+
9400
+ // ../zero-schema/src/normalized-schema.ts
9401
+ function normalizeSchema(schema) {
9402
+ if (schema instanceof NormalizedSchema) {
9403
+ return schema;
9404
+ }
9405
+ return new NormalizedSchema(schema);
9406
+ }
9407
+ var NormalizedSchema = class {
9408
+ version;
9409
+ tables;
9410
+ constructor(schema) {
9411
+ this.version = schema.version;
9412
+ this.tables = normalizeTables(schema.tables);
9413
+ }
9414
+ };
9415
+ function normalizeTables(tables) {
9416
+ const rv = {};
9417
+ const tableSchemaCache = /* @__PURE__ */ new Map();
9418
+ for (const [name, table] of sortedEntries(tables)) {
9419
+ rv[name] = normalizeTableSchemaWithCache(table, name, tableSchemaCache);
9353
9420
  }
9421
+ return rv;
9354
9422
  }
9355
9423
 
9356
9424
  // ../zql/src/query/query-impl.ts
@@ -9395,7 +9463,12 @@ var primitiveSchema = valita_exports.union(
9395
9463
  valita_exports.boolean(),
9396
9464
  valita_exports.null()
9397
9465
  );
9398
- var equalityOpsSchema = valita_exports.union(valita_exports.literal("="), valita_exports.literal("!="));
9466
+ var equalityOpsSchema = valita_exports.union(
9467
+ valita_exports.literal("="),
9468
+ valita_exports.literal("!="),
9469
+ valita_exports.literal("IS"),
9470
+ valita_exports.literal("IS NOT")
9471
+ );
9399
9472
  var orderOpsSchema = valita_exports.union(
9400
9473
  valita_exports.literal("<"),
9401
9474
  valita_exports.literal(">"),
@@ -9423,6 +9496,7 @@ var simpleConditionSchema = valita_exports.object({
9423
9496
  valita_exports.string(),
9424
9497
  valita_exports.number(),
9425
9498
  valita_exports.boolean(),
9499
+ valita_exports.null(),
9426
9500
  readonlyArray(valita_exports.union(valita_exports.string(), valita_exports.number(), valita_exports.boolean())),
9427
9501
  valita_exports.object({
9428
9502
  type: valita_exports.literal("static"),
@@ -9431,10 +9505,20 @@ var simpleConditionSchema = valita_exports.object({
9431
9505
  })
9432
9506
  )
9433
9507
  });
9508
+ var correlatedSubqueryConditionOperatorSchema = valita_exports.union(
9509
+ valita_exports.literal("EXISTS"),
9510
+ valita_exports.literal("NOT EXISTS")
9511
+ );
9512
+ var correlatedSubqueryConditionSchema = readonlyObject({
9513
+ type: valita_exports.literal("correlatedSubquery"),
9514
+ related: valita_exports.lazy(() => correlatedSubquerySchema),
9515
+ op: correlatedSubqueryConditionOperatorSchema
9516
+ });
9434
9517
  var conditionSchema = valita_exports.union(
9435
9518
  simpleConditionSchema,
9436
9519
  valita_exports.lazy(() => conjunctionSchema),
9437
- valita_exports.lazy(() => disjunctionSchema)
9520
+ valita_exports.lazy(() => disjunctionSchema),
9521
+ correlatedSubqueryConditionSchema
9438
9522
  );
9439
9523
  var conjunctionSchema = readonlyObject({
9440
9524
  type: valita_exports.literal("and"),
@@ -9501,7 +9585,7 @@ function normalizeAST(ast) {
9501
9585
  return normalized;
9502
9586
  }
9503
9587
  function sortedWhere(where) {
9504
- if (where.type === "simple") {
9588
+ if (where.type === "simple" || where.type === "correlatedSubquery") {
9505
9589
  return where;
9506
9590
  }
9507
9591
  return {
@@ -9525,6 +9609,15 @@ function cmpCondition(a, b) {
9525
9609
  if (b.type === "simple") {
9526
9610
  return 1;
9527
9611
  }
9612
+ if (a.type === "correlatedSubquery") {
9613
+ if (b.type !== "correlatedSubquery") {
9614
+ return -1;
9615
+ }
9616
+ return cmpRelated(a.related, b.related) || compareUTF8MaybeNull(a.op, b.op);
9617
+ }
9618
+ if (b.type === "correlatedSubquery") {
9619
+ return -1;
9620
+ }
9528
9621
  const val = compareUTF8MaybeNull(a.type, b.type);
9529
9622
  if (val !== 0) {
9530
9623
  return val;
@@ -9544,7 +9637,7 @@ function flattened(cond) {
9544
9637
  if (cond === void 0) {
9545
9638
  return void 0;
9546
9639
  }
9547
- if (cond.type === "simple") {
9640
+ if (cond.type === "simple" || cond.type === "correlatedSubquery") {
9548
9641
  return cond;
9549
9642
  }
9550
9643
  const conditions = defined(
@@ -9590,31 +9683,275 @@ function hashOfAST(ast) {
9590
9683
  return hash;
9591
9684
  }
9592
9685
 
9593
- // ../zql/src/ivm/fan-in.ts
9594
- var FanIn = class {
9595
- #inputs;
9596
- #fanOut;
9597
- #output;
9598
- #schema;
9599
- constructor(fanOut, inputs) {
9600
- this.#inputs = inputs;
9601
- this.#schema = inputs[0].getSchema();
9602
- this.#fanOut = fanOut;
9603
- for (const input of inputs) {
9604
- input.setOutput(this);
9605
- assert(this.#schema === input.getSchema(), `Schema mismatch in fan-in`);
9606
- }
9686
+ // ../zql/src/ivm/change.ts
9687
+ function rowForChange(change) {
9688
+ const { type } = change;
9689
+ return type === "add" || type === "remove" ? change.node.row : change.row;
9690
+ }
9691
+
9692
+ // ../zql/src/ivm/data.ts
9693
+ import { compareUTF8 as compareUTF84 } from "compare-utf8";
9694
+ function compareValues(a, b) {
9695
+ a = normalizeUndefined(a);
9696
+ b = normalizeUndefined(b);
9697
+ if (a === b) {
9698
+ return 0;
9607
9699
  }
9608
- setOutput(output) {
9609
- this.#output = output;
9700
+ if (a === null) {
9701
+ return -1;
9610
9702
  }
9611
- destroy() {
9612
- for (const input of this.#inputs) {
9613
- input.destroy();
9614
- }
9703
+ if (b === null) {
9704
+ return 1;
9615
9705
  }
9616
- getSchema() {
9617
- return this.#inputs[0].getSchema();
9706
+ if (typeof a === "boolean") {
9707
+ assertBoolean(b);
9708
+ return a ? 1 : -1;
9709
+ }
9710
+ if (typeof a === "number") {
9711
+ assertNumber(b);
9712
+ return a - b;
9713
+ }
9714
+ if (typeof a === "string") {
9715
+ assertString(b);
9716
+ return compareUTF84(a, b);
9717
+ }
9718
+ throw new Error(`Unsupported type: ${a}`);
9719
+ }
9720
+ function normalizeUndefined(v2) {
9721
+ return v2 ?? null;
9722
+ }
9723
+ function makeComparator(order) {
9724
+ return (a, b) => {
9725
+ for (const ord of order) {
9726
+ const field = ord[0];
9727
+ const comp = compareValues(a[field], b[field]);
9728
+ if (comp !== 0) {
9729
+ return ord[1] === "asc" ? comp : -comp;
9730
+ }
9731
+ }
9732
+ return 0;
9733
+ };
9734
+ }
9735
+ function valuesEqual(a, b) {
9736
+ a = normalizeUndefined(a);
9737
+ b = normalizeUndefined(b);
9738
+ if (a === null || b === null) {
9739
+ return false;
9740
+ }
9741
+ return a === b;
9742
+ }
9743
+
9744
+ // ../zql/src/ivm/stream.ts
9745
+ function* take(stream, limit) {
9746
+ if (limit < 1) {
9747
+ return;
9748
+ }
9749
+ let count = 0;
9750
+ for (const v2 of stream) {
9751
+ yield v2;
9752
+ if (++count === limit) {
9753
+ break;
9754
+ }
9755
+ }
9756
+ }
9757
+ function first(stream) {
9758
+ const it = stream[Symbol.iterator]();
9759
+ const { value } = it.next();
9760
+ it.return?.();
9761
+ return value;
9762
+ }
9763
+
9764
+ // ../zql/src/ivm/exists.ts
9765
+ var Exists = class {
9766
+ #input;
9767
+ #relationshipName;
9768
+ #storage;
9769
+ #not;
9770
+ #output;
9771
+ constructor(input, storage, relationshipName, type) {
9772
+ this.#input = input;
9773
+ this.#relationshipName = relationshipName;
9774
+ this.#input.setOutput(this);
9775
+ this.#storage = storage;
9776
+ assert(this.#input.getSchema().relationships[relationshipName]);
9777
+ this.#not = type === "NOT EXISTS";
9778
+ }
9779
+ setOutput(output) {
9780
+ this.#output = output;
9781
+ }
9782
+ destroy() {
9783
+ this.#input.destroy();
9784
+ }
9785
+ getSchema() {
9786
+ return this.#input.getSchema();
9787
+ }
9788
+ *fetch(req) {
9789
+ for (const node of this.#input.fetch(req)) {
9790
+ if (this.#filter(node.row)) {
9791
+ yield node;
9792
+ }
9793
+ }
9794
+ }
9795
+ *cleanup(req) {
9796
+ for (const node of this.#input.cleanup(req)) {
9797
+ if (this.#filter(node.row)) {
9798
+ yield node;
9799
+ }
9800
+ this.#delSize(node.row);
9801
+ }
9802
+ }
9803
+ push(change) {
9804
+ assert(this.#output, "Output not set");
9805
+ switch (change.type) {
9806
+ case "add":
9807
+ case "edit": {
9808
+ this.#pushWithFilter(change);
9809
+ return;
9810
+ }
9811
+ case "remove": {
9812
+ this.#pushWithFilter(change);
9813
+ this.#delSize(change.node.row);
9814
+ return;
9815
+ }
9816
+ case "child":
9817
+ if (change.child.relationshipName !== this.#relationshipName || change.child.change.type === "edit" || change.child.change.type === "child") {
9818
+ this.#pushWithFilter(change);
9819
+ return;
9820
+ }
9821
+ switch (change.child.change.type) {
9822
+ case "add": {
9823
+ let size = this.#getSize(change.row);
9824
+ if (size !== void 0) {
9825
+ size++;
9826
+ this.#setSize(change.row, size);
9827
+ } else {
9828
+ size = this.#fetchSize(change.row);
9829
+ }
9830
+ if (size === 1) {
9831
+ this.#output.push({
9832
+ type: this.#not ? "remove" : "add",
9833
+ node: this.#fetchNodeForRow(change.row)
9834
+ });
9835
+ } else {
9836
+ this.#pushWithFilter(change, size);
9837
+ }
9838
+ return;
9839
+ }
9840
+ case "remove": {
9841
+ let size = this.#getSize(change.row);
9842
+ if (size !== void 0) {
9843
+ assert(size > 0);
9844
+ size--;
9845
+ this.#setSize(change.row, size);
9846
+ } else {
9847
+ size = this.#fetchSize(change.row);
9848
+ }
9849
+ if (size === 0) {
9850
+ this.#output.push({
9851
+ type: this.#not ? "add" : "remove",
9852
+ node: this.#fetchNodeForRow(change.row)
9853
+ });
9854
+ } else {
9855
+ this.#pushWithFilter(change, size);
9856
+ }
9857
+ return;
9858
+ }
9859
+ }
9860
+ return;
9861
+ default:
9862
+ unreachable(change);
9863
+ }
9864
+ }
9865
+ /**
9866
+ * Returns whether or not the change's row's this.#relationshipName
9867
+ * relationship passes the exist/not exists filter condition.
9868
+ * If the optional `size` is passed it is used.
9869
+ * Otherwise, if there is a stored size for the row it is used.
9870
+ * Otherwise the size is computed by fetching a node for the row from
9871
+ * this.#input (this computed size is also stored).
9872
+ */
9873
+ #filter(row, size) {
9874
+ const exists = (size ?? this.#getOrFetchSize(row)) > 0;
9875
+ return this.#not ? !exists : exists;
9876
+ }
9877
+ /**
9878
+ * Pushes a change if this.#filter is true for its row.
9879
+ */
9880
+ #pushWithFilter(change, size) {
9881
+ const row = rowForChange(change);
9882
+ if (this.#filter(row, size)) {
9883
+ must(this.#output).push(change);
9884
+ }
9885
+ }
9886
+ #getSize(row) {
9887
+ return this.#storage.get(this.#makeSizeStorageKey(row));
9888
+ }
9889
+ #setSize(row, size) {
9890
+ this.#storage.set(this.#makeSizeStorageKey(row), size);
9891
+ }
9892
+ #delSize(row) {
9893
+ this.#storage.del(this.#makeSizeStorageKey(row));
9894
+ }
9895
+ #getOrFetchSize(row) {
9896
+ const size = this.#getSize(row);
9897
+ if (size !== void 0) {
9898
+ return size;
9899
+ }
9900
+ return this.#fetchSize(row);
9901
+ }
9902
+ #fetchSize(row) {
9903
+ const relationship = this.#fetchNodeForRow(row).relationships[this.#relationshipName];
9904
+ assert(relationship);
9905
+ let size = 0;
9906
+ for (const _relatedNode of relationship) {
9907
+ size++;
9908
+ }
9909
+ this.#setSize(row, size);
9910
+ return size;
9911
+ }
9912
+ #fetchNodeForRow(row) {
9913
+ return must(
9914
+ first(
9915
+ this.#input.fetch({
9916
+ start: { row, basis: "at" }
9917
+ })
9918
+ )
9919
+ );
9920
+ }
9921
+ #makeSizeStorageKey(row) {
9922
+ const primaryKey = [];
9923
+ for (const key of this.#input.getSchema().primaryKey) {
9924
+ primaryKey.push(normalizeUndefined(row[key]));
9925
+ }
9926
+ return JSON.stringify(["size", primaryKey]);
9927
+ }
9928
+ };
9929
+
9930
+ // ../zql/src/ivm/fan-in.ts
9931
+ var FanIn = class {
9932
+ #inputs;
9933
+ #fanOut;
9934
+ #schema;
9935
+ #output;
9936
+ constructor(fanOut, inputs) {
9937
+ this.#inputs = inputs;
9938
+ this.#schema = fanOut.getSchema();
9939
+ this.#fanOut = fanOut;
9940
+ for (const input of inputs) {
9941
+ input.setOutput(this);
9942
+ assert(this.#schema === input.getSchema(), `Schema mismatch in fan-in`);
9943
+ }
9944
+ }
9945
+ setOutput(output) {
9946
+ this.#output = output;
9947
+ }
9948
+ destroy() {
9949
+ for (const input of this.#inputs) {
9950
+ input.destroy();
9951
+ }
9952
+ }
9953
+ getSchema() {
9954
+ return this.#schema;
9618
9955
  }
9619
9956
  fetch(req) {
9620
9957
  return this.#fetchOrCleanup((input) => input.fetch(req));
@@ -9639,19 +9976,16 @@ var FanIn = class {
9639
9976
  // ../zql/src/ivm/fan-out.ts
9640
9977
  var FanOut = class {
9641
9978
  #input;
9642
- #outputs;
9979
+ #outputs = [];
9643
9980
  // FanOut is paired with a FanIn.
9644
9981
  // Once FanIn has received a push from FanOut along
9645
9982
  // any branch, FanOut no longer needs to push that value
9646
9983
  // across the rest of its outputs..
9647
- #fanInReceivedPush;
9648
- #destroyCount;
9984
+ #fanInReceivedPush = false;
9985
+ #destroyCount = 0;
9649
9986
  constructor(input) {
9650
9987
  this.#input = input;
9651
- this.#input.setOutput(this);
9652
- this.#outputs = [];
9653
- this.#fanInReceivedPush = false;
9654
- this.#destroyCount = 0;
9988
+ input.setOutput(this);
9655
9989
  }
9656
9990
  setOutput(output) {
9657
9991
  this.#outputs.push(output);
@@ -9724,7 +10058,7 @@ var Filter = class {
9724
10058
  this.#input = input;
9725
10059
  this.#mode = mode;
9726
10060
  this.#predicate = predicate;
9727
- this.#input.setOutput(this);
10061
+ input.setOutput(this);
9728
10062
  }
9729
10063
  setOutput(output) {
9730
10064
  this.#output = output;
@@ -9771,78 +10105,6 @@ var Filter = class {
9771
10105
  }
9772
10106
  };
9773
10107
 
9774
- // ../zql/src/ivm/data.ts
9775
- import { compareUTF8 as compareUTF84 } from "compare-utf8";
9776
- function compareValues(a, b) {
9777
- a = normalizeUndefined(a);
9778
- b = normalizeUndefined(b);
9779
- if (a === b) {
9780
- return 0;
9781
- }
9782
- if (a === null) {
9783
- return -1;
9784
- }
9785
- if (b === null) {
9786
- return 1;
9787
- }
9788
- if (typeof a === "boolean") {
9789
- assertBoolean(b);
9790
- return a ? 1 : -1;
9791
- }
9792
- if (typeof a === "number") {
9793
- assertNumber(b);
9794
- return a - b;
9795
- }
9796
- if (typeof a === "string") {
9797
- assertString(b);
9798
- return compareUTF84(a, b);
9799
- }
9800
- throw new Error(`Unsupported type: ${a}`);
9801
- }
9802
- function normalizeUndefined(v2) {
9803
- return v2 ?? null;
9804
- }
9805
- function makeComparator(order) {
9806
- return (a, b) => {
9807
- for (const ord of order) {
9808
- const field = ord[0];
9809
- const comp = compareValues(a[field], b[field]);
9810
- if (comp !== 0) {
9811
- return ord[1] === "asc" ? comp : -comp;
9812
- }
9813
- }
9814
- return 0;
9815
- };
9816
- }
9817
- function valuesEqual(a, b) {
9818
- a = normalizeUndefined(a);
9819
- b = normalizeUndefined(b);
9820
- if (a === null || b === null) {
9821
- return false;
9822
- }
9823
- return a === b;
9824
- }
9825
-
9826
- // ../zql/src/ivm/stream.ts
9827
- function* take(stream, limit) {
9828
- if (limit < 1) {
9829
- return;
9830
- }
9831
- let count = 0;
9832
- for (const v2 of stream) {
9833
- yield v2;
9834
- if (++count === limit) {
9835
- break;
9836
- }
9837
- }
9838
- }
9839
- function first(stream) {
9840
- const it = stream[Symbol.iterator]();
9841
- const { value } = it.next();
9842
- it.return?.();
9843
- return value;
9844
- }
9845
-
9846
10108
  // ../zql/src/ivm/join.ts
9847
10109
  var Join = class {
9848
10110
  #parent;
@@ -10139,7 +10401,7 @@ var Skip = class {
10139
10401
  this.#input = input;
10140
10402
  this.#bound = bound;
10141
10403
  this.#comparator = input.getSchema().compareRows;
10142
- this.#input.setOutput(this);
10404
+ input.setOutput(this);
10143
10405
  }
10144
10406
  getSchema() {
10145
10407
  return this.#input.getSchema();
@@ -10230,10 +10492,10 @@ var Take = class {
10230
10492
  this.#partitionKey = partitionKey;
10231
10493
  assert(limit >= 0);
10232
10494
  assertOrderingIncludesPK(
10233
- this.#input.getSchema().sort,
10234
- this.#input.getSchema().primaryKey
10495
+ input.getSchema().sort,
10496
+ input.getSchema().primaryKey
10235
10497
  );
10236
- this.#input.setOutput(this);
10498
+ input.setOutput(this);
10237
10499
  }
10238
10500
  setOutput(output) {
10239
10501
  this.#output = output;
@@ -10355,8 +10617,7 @@ var Take = class {
10355
10617
  return;
10356
10618
  }
10357
10619
  assert(this.#output, "Output not set");
10358
- assert(change.type !== "child", "child changes are not supported");
10359
- const { takeState, takeStateKey, maxBound, constraint } = this.#getStateAndConstraint(change.node.row);
10620
+ const { takeState, takeStateKey, maxBound, constraint } = this.#getStateAndConstraint(rowForChange(change));
10360
10621
  if (!takeState) {
10361
10622
  return;
10362
10623
  }
@@ -10475,6 +10736,10 @@ var Take = class {
10475
10736
  maxBound
10476
10737
  );
10477
10738
  this.#output.push(change);
10739
+ } else if (change.type === "child") {
10740
+ if (takeState.bound && compareRows(change.row, takeState.bound) <= 0) {
10741
+ this.#output.push(change);
10742
+ }
10478
10743
  }
10479
10744
  }
10480
10745
  #pushEditChange(change) {
@@ -10722,10 +10987,17 @@ function patternToRegExp(source, flags = "") {
10722
10987
 
10723
10988
  // ../zql/src/builder/filter.ts
10724
10989
  function createPredicate(condition) {
10725
- const impl = createPredicateImpl(
10726
- condition.value,
10727
- condition.op
10728
- );
10990
+ switch (condition.op) {
10991
+ case "IS":
10992
+ case "IS NOT": {
10993
+ const impl2 = createIsPredicate(condition.value, condition.op);
10994
+ return (row) => impl2(row[condition.field]);
10995
+ }
10996
+ }
10997
+ if (condition.value === null || condition.value === void 0) {
10998
+ return (_row) => false;
10999
+ }
11000
+ const impl = createPredicateImpl(condition.value, condition.op);
10729
11001
  return (row) => {
10730
11002
  const lhs = row[condition.field];
10731
11003
  if (lhs === null || lhs === void 0) {
@@ -10734,6 +11006,14 @@ function createPredicate(condition) {
10734
11006
  return impl(lhs);
10735
11007
  };
10736
11008
  }
11009
+ function createIsPredicate(rhs, operator) {
11010
+ switch (operator) {
11011
+ case "IS":
11012
+ return (lhs) => lhs === rhs;
11013
+ case "IS NOT":
11014
+ return (lhs) => lhs !== rhs;
11015
+ }
11016
+ }
10737
11017
  function createPredicateImpl(rhs, operator) {
10738
11018
  switch (operator) {
10739
11019
  case "=":
@@ -10751,11 +11031,11 @@ function createPredicateImpl(rhs, operator) {
10751
11031
  case "LIKE":
10752
11032
  return getLikePredicate(rhs, "");
10753
11033
  case "NOT LIKE":
10754
- return not2(getLikePredicate(rhs, ""));
11034
+ return not(getLikePredicate(rhs, ""));
10755
11035
  case "ILIKE":
10756
11036
  return getLikePredicate(rhs, "i");
10757
11037
  case "NOT ILIKE":
10758
- return not2(getLikePredicate(rhs, "i"));
11038
+ return not(getLikePredicate(rhs, "i"));
10759
11039
  case "IN": {
10760
11040
  assert(Array.isArray(rhs));
10761
11041
  const set = new Set(rhs);
@@ -10771,7 +11051,7 @@ function createPredicateImpl(rhs, operator) {
10771
11051
  throw new Error(`Unexpected operator: ${operator}`);
10772
11052
  }
10773
11053
  }
10774
- function not2(f) {
11054
+ function not(f) {
10775
11055
  return (lhs) => !f(lhs);
10776
11056
  }
10777
11057
 
@@ -10798,10 +11078,22 @@ function bindStaticParameters(ast, staticQueryParameters) {
10798
11078
  return node;
10799
11079
  };
10800
11080
  function bindCondition(condition) {
10801
- return condition.type === "simple" ? {
10802
- ...condition,
10803
- value: bindValue(condition.value)
10804
- } : {
11081
+ if (condition.type === "simple") {
11082
+ return {
11083
+ ...condition,
11084
+ value: bindValue(condition.value)
11085
+ };
11086
+ }
11087
+ if (condition.type === "correlatedSubquery") {
11088
+ return {
11089
+ ...condition,
11090
+ related: {
11091
+ ...condition.related,
11092
+ subquery: visit(condition.related.subquery)
11093
+ }
11094
+ };
11095
+ }
11096
+ return {
10805
11097
  ...condition,
10806
11098
  conditions: condition.conditions.map(bindCondition)
10807
11099
  };
@@ -10837,57 +11129,45 @@ function buildPipelineInternal(ast, delegate, staticQueryParameters, partitionKe
10837
11129
  if (ast.start) {
10838
11130
  end = new Skip(end, ast.start);
10839
11131
  }
11132
+ for (const csq of gatherCorrelatedSubqueryQueriesFromCondition(ast.where)) {
11133
+ end = applyCorrelatedSubQuery(csq, delegate, staticQueryParameters, end);
11134
+ }
10840
11135
  if (ast.where) {
10841
- end = applyWhere(end, ast.where, appliedFilters);
11136
+ end = applyWhere(end, ast.where, appliedFilters, delegate);
10842
11137
  }
10843
11138
  if (ast.limit) {
10844
11139
  end = new Take(end, delegate.createStorage(), ast.limit, partitionKey);
10845
11140
  }
10846
11141
  if (ast.related) {
10847
- for (const sq of ast.related) {
10848
- assert(sq.subquery.alias, "Subquery must have an alias");
10849
- const child = buildPipelineInternal(
10850
- sq.subquery,
10851
- delegate,
10852
- staticQueryParameters,
10853
- sq.correlation.childField
10854
- );
10855
- end = new Join({
10856
- parent: end,
10857
- child,
10858
- storage: delegate.createStorage(),
10859
- parentKey: sq.correlation.parentField,
10860
- childKey: sq.correlation.childField,
10861
- relationshipName: sq.subquery.alias,
10862
- hidden: sq.hidden ?? false
10863
- });
11142
+ for (const csq of ast.related) {
11143
+ end = applyCorrelatedSubQuery(csq, delegate, staticQueryParameters, end);
10864
11144
  }
10865
11145
  }
10866
11146
  return end;
10867
11147
  }
10868
- function applyWhere(input, condition, appliedFilters) {
11148
+ function applyWhere(input, condition, appliedFilters, delegate) {
10869
11149
  switch (condition.type) {
10870
11150
  case "and":
10871
- return applyAnd(input, condition, appliedFilters);
11151
+ return applyAnd(input, condition, appliedFilters, delegate);
10872
11152
  case "or":
10873
- return applyOr(input, condition, appliedFilters);
11153
+ return applyOr(input, condition, appliedFilters, delegate);
11154
+ case "correlatedSubquery":
11155
+ return applyCorrelatedSubqueryCondition(input, condition, delegate);
10874
11156
  default:
10875
11157
  return applySimpleCondition(input, condition, appliedFilters);
10876
11158
  }
10877
11159
  }
10878
- function applyAnd(input, condition, appliedFilters) {
11160
+ function applyAnd(input, condition, appliedFilters, delegate) {
10879
11161
  for (const subCondition of condition.conditions) {
10880
- input = applyWhere(input, subCondition, appliedFilters);
11162
+ input = applyWhere(input, subCondition, appliedFilters, delegate);
10881
11163
  }
10882
11164
  return input;
10883
11165
  }
10884
- function applyOr(input, condition, appliedFilters) {
11166
+ function applyOr(input, condition, appliedFilters, delegate) {
10885
11167
  const fanOut = new FanOut(input);
10886
- const branches = [];
10887
- for (const subCondition of condition.conditions) {
10888
- branches.push(applyWhere(fanOut, subCondition, appliedFilters));
10889
- }
10890
- assert(branches.length > 0, "Or condition must have at least one branch");
11168
+ const branches = condition.conditions.map(
11169
+ (subCondition) => applyWhere(fanOut, subCondition, appliedFilters, delegate)
11170
+ );
10891
11171
  return new FanIn(fanOut, branches);
10892
11172
  }
10893
11173
  function applySimpleCondition(input, condition, appliedFilters) {
@@ -10897,6 +11177,58 @@ function applySimpleCondition(input, condition, appliedFilters) {
10897
11177
  createPredicate(condition)
10898
11178
  );
10899
11179
  }
11180
+ function applyCorrelatedSubQuery(sq, delegate, staticQueryParameters, end) {
11181
+ assert(sq.subquery.alias, "Subquery must have an alias");
11182
+ const child = buildPipelineInternal(
11183
+ sq.subquery,
11184
+ delegate,
11185
+ staticQueryParameters,
11186
+ sq.correlation.childField
11187
+ );
11188
+ end = new Join({
11189
+ parent: end,
11190
+ child,
11191
+ storage: delegate.createStorage(),
11192
+ parentKey: sq.correlation.parentField,
11193
+ childKey: sq.correlation.childField,
11194
+ relationshipName: sq.subquery.alias,
11195
+ hidden: sq.hidden ?? false
11196
+ });
11197
+ return end;
11198
+ }
11199
+ function applyCorrelatedSubqueryCondition(input, condition, delegate) {
11200
+ assert(condition.op === "EXISTS" || condition.op === "NOT EXISTS");
11201
+ return new Exists(
11202
+ input,
11203
+ delegate.createStorage(),
11204
+ must(condition.related.subquery.alias),
11205
+ condition.op
11206
+ );
11207
+ }
11208
+ function gatherCorrelatedSubqueryQueriesFromCondition(condition) {
11209
+ const csqs = [];
11210
+ const gather = (condition2) => {
11211
+ if (condition2.type === "correlatedSubquery") {
11212
+ assert(condition2.op === "EXISTS" || condition2.op === "NOT EXISTS");
11213
+ csqs.push({
11214
+ ...condition2.related,
11215
+ subquery: { ...condition2.related.subquery, limit: EXISTS_LIMIT }
11216
+ });
11217
+ return;
11218
+ }
11219
+ if (condition2.type === "and" || condition2.type === "or") {
11220
+ for (const c of condition2.conditions) {
11221
+ gather(c);
11222
+ }
11223
+ return;
11224
+ }
11225
+ };
11226
+ if (condition) {
11227
+ gather(condition);
11228
+ }
11229
+ return csqs;
11230
+ }
11231
+ var EXISTS_LIMIT = 5;
10900
11232
  function assertOrderingIncludesPK(ordering, pk) {
10901
11233
  const orderingFields = ordering.map(([field]) => field);
10902
11234
  const missingFields = pk.filter((pkField) => !orderingFields.includes(pkField));
@@ -10928,8 +11260,8 @@ var ArrayView = class {
10928
11260
  this.#input = input;
10929
11261
  this.#schema = input.getSchema();
10930
11262
  this.#format = format;
10931
- this.#input.setOutput(this);
10932
11263
  this.#root = { "": format.singular ? void 0 : [] };
11264
+ input.setOutput(this);
10933
11265
  this.#hydrate();
10934
11266
  }
10935
11267
  get data() {
@@ -10977,159 +11309,198 @@ var ArrayView = class {
10977
11309
  }
10978
11310
  };
10979
11311
 
10980
- // ../shared/src/sorted-entries.ts
10981
- function sortedEntries(object16) {
10982
- return Object.entries(object16).sort((a, b) => stringCompare(a[0], b[0]));
10983
- }
10984
-
10985
- // ../zero-schema/src/table-schema.ts
10986
- function isFieldRelationship(relationship) {
10987
- return relationship.junction === void 0;
10988
- }
10989
- function isJunctionRelationship(relationship) {
10990
- return !isFieldRelationship(relationship);
10991
- }
10992
-
10993
- // ../zero-schema/src/normalize-table-schema.ts
10994
- var NormalizedTableSchema = class {
10995
- tableName;
10996
- primaryKey;
10997
- columns;
10998
- relationships;
10999
- constructor(tableSchema, tableSchemaCache) {
11000
- this.tableName = tableSchema.tableName;
11001
- const primaryKey = normalizePrimaryKey(tableSchema.primaryKey);
11002
- this.primaryKey = primaryKey;
11003
- this.columns = normalizeColumns(tableSchema.columns, primaryKey);
11004
- tableSchemaCache.set(tableSchema, this);
11005
- this.relationships = normalizeRelationships(
11006
- tableSchema.relationships,
11007
- tableSchemaCache
11008
- );
11312
+ // ../zql/src/query/expression.ts
11313
+ var ExpressionBuilder = class {
11314
+ #exists;
11315
+ constructor(exists) {
11316
+ this.#exists = exists;
11317
+ this.exists = this.exists.bind(this);
11318
+ }
11319
+ get eb() {
11320
+ return this;
11321
+ }
11322
+ cmp(field, opOrValue, value) {
11323
+ return cmp(field, opOrValue, value);
11324
+ }
11325
+ and = and;
11326
+ or = or;
11327
+ not = not2;
11328
+ exists(relationship, cb) {
11329
+ return this.#exists(relationship, cb);
11009
11330
  }
11010
11331
  };
11011
- function normalizeTableSchema(tableSchema) {
11012
- return normalizeTableSchemaWithCache(
11013
- tableSchema,
11014
- tableSchema.tableName,
11015
- /* @__PURE__ */ new Map()
11016
- );
11017
- }
11018
- function normalizeTableSchemaWithCache(tableSchema, expectedName, tableSchemaCache) {
11019
- if (tableSchema instanceof NormalizedTableSchema) {
11020
- return tableSchema;
11332
+ function and(...conditions) {
11333
+ const expressions = filterTrue(filterUndefined(conditions));
11334
+ if (expressions.length === 1) {
11335
+ return expressions[0];
11021
11336
  }
11022
- assert(
11023
- tableSchema.tableName === expectedName,
11024
- `Table name mismatch: "${tableSchema.tableName}" !== "${expectedName}"`
11025
- );
11026
- let normalizedTableSchema = tableSchemaCache.get(tableSchema);
11027
- if (normalizedTableSchema) {
11028
- return normalizedTableSchema;
11337
+ if (expressions.some(isAlwaysFalse)) {
11338
+ return FALSE;
11029
11339
  }
11030
- normalizedTableSchema = new NormalizedTableSchema(
11031
- tableSchema,
11032
- tableSchemaCache
11033
- );
11034
- return normalizedTableSchema;
11340
+ return { type: "and", conditions: expressions };
11035
11341
  }
11036
- function isSorted(arr) {
11037
- for (let i = 1; i < arr.length; i++) {
11038
- if (arr[i - 1] >= arr[i]) {
11039
- return false;
11040
- }
11342
+ function or(...conditions) {
11343
+ const expressions = filterFalse(filterUndefined(conditions));
11344
+ if (expressions.length === 1) {
11345
+ return expressions[0];
11041
11346
  }
11042
- return true;
11043
- }
11044
- function assertNoDuplicates(arr) {
11045
- for (let i = 1; i < arr.length; i++) {
11046
- assert(arr[i - 1] !== arr[i], "Primary key must not contain duplicates");
11347
+ if (expressions.some(isAlwaysTrue)) {
11348
+ return TRUE;
11047
11349
  }
11350
+ return { type: "or", conditions: expressions };
11048
11351
  }
11049
- function normalizePrimaryKey(arr) {
11050
- if (isSorted(arr)) {
11051
- return arr;
11352
+ function not2(expression) {
11353
+ switch (expression.type) {
11354
+ case "and":
11355
+ return {
11356
+ type: "or",
11357
+ conditions: expression.conditions.map(not2)
11358
+ };
11359
+ case "or":
11360
+ return {
11361
+ type: "and",
11362
+ conditions: expression.conditions.map(not2)
11363
+ };
11364
+ case "correlatedSubquery":
11365
+ return {
11366
+ type: "correlatedSubquery",
11367
+ related: expression.related,
11368
+ op: negateOperator(expression.op)
11369
+ };
11370
+ default:
11371
+ return {
11372
+ type: "simple",
11373
+ op: negateOperator(expression.op),
11374
+ field: expression.field,
11375
+ value: expression.value
11376
+ };
11052
11377
  }
11053
- arr = [...arr].sort();
11054
- assertNoDuplicates(arr);
11055
- return arr;
11056
11378
  }
11057
- function normalizeColumns(columns, primaryKey) {
11058
- const rv = {};
11059
- for (const pk of primaryKey) {
11060
- const schemaValue = columns[pk];
11061
- assert(schemaValue, `Primary key column "${pk}" not found`);
11062
- const { type, optional } = schemaValue;
11063
- assert(!optional, `Primary key column "${pk}" cannot be optional`);
11064
- assert(
11065
- type === "string" || type === "number" || type === "boolean",
11066
- `Primary key column "${pk}" must be a string, number, or boolean. Got ${type}`
11067
- );
11068
- }
11069
- for (const [name, column] of sortedEntries(columns)) {
11070
- rv[name] = normalizeSchemaValue(column);
11379
+ function cmp(field, opOrValue, value) {
11380
+ let op;
11381
+ if (value === void 0) {
11382
+ value = opOrValue;
11383
+ op = "=";
11384
+ } else {
11385
+ op = opOrValue;
11071
11386
  }
11072
- return rv;
11073
- }
11074
- function normalizeSchemaValue(value) {
11075
11387
  return {
11076
- type: value.type,
11077
- optional: value.optional ?? false
11388
+ type: "simple",
11389
+ field,
11390
+ op,
11391
+ value
11078
11392
  };
11079
11393
  }
11080
- function normalizeRelationships(relationships, tableSchemaCache) {
11081
- const rv = {};
11082
- for (const [name, relationship] of sortedEntries(relationships)) {
11083
- rv[name] = normalizeRelationship(relationship, tableSchemaCache);
11084
- }
11085
- return rv;
11394
+ var TRUE = {
11395
+ type: "and",
11396
+ conditions: []
11397
+ };
11398
+ var FALSE = {
11399
+ type: "or",
11400
+ conditions: []
11401
+ };
11402
+ function isAlwaysTrue(condition) {
11403
+ return condition.type === "and" && condition.conditions.length === 0;
11086
11404
  }
11087
- function normalizeRelationship(relationship, tableSchemaCache) {
11088
- if (isFieldRelationship(relationship)) {
11089
- return normalizeFieldRelationship(relationship, tableSchemaCache);
11090
- }
11091
- return normalizeJunctionRelationship(relationship, tableSchemaCache);
11405
+ function isAlwaysFalse(condition) {
11406
+ return condition.type === "or" && condition.conditions.length === 0;
11092
11407
  }
11093
- function normalizeFieldRelationship(relationship, tableSchemaCache) {
11094
- return {
11095
- source: relationship.source,
11096
- dest: {
11097
- field: relationship.dest.field,
11098
- schema: normalizeLazyTableSchema(
11099
- relationship.dest.schema,
11100
- tableSchemaCache
11101
- )
11408
+ function flatten(type, conditions) {
11409
+ const flattened2 = [];
11410
+ for (const c of conditions) {
11411
+ if (c.type === type) {
11412
+ flattened2.push(...c.conditions);
11413
+ } else {
11414
+ flattened2.push(c);
11102
11415
  }
11103
- };
11416
+ }
11417
+ return flattened2;
11418
+ }
11419
+ var negateSimpleOperatorMap = {
11420
+ ["="]: "!=",
11421
+ ["!="]: "=",
11422
+ ["<"]: ">=",
11423
+ [">"]: "<=",
11424
+ [">="]: "<",
11425
+ ["<="]: ">",
11426
+ ["IN"]: "NOT IN",
11427
+ ["NOT IN"]: "IN",
11428
+ ["LIKE"]: "NOT LIKE",
11429
+ ["NOT LIKE"]: "LIKE",
11430
+ ["ILIKE"]: "NOT ILIKE",
11431
+ ["NOT ILIKE"]: "ILIKE",
11432
+ ["IS"]: "IS NOT",
11433
+ ["IS NOT"]: "IS"
11434
+ };
11435
+ var negateOperatorMap = {
11436
+ ...negateSimpleOperatorMap,
11437
+ ["EXISTS"]: "NOT EXISTS",
11438
+ ["NOT EXISTS"]: "EXISTS"
11439
+ };
11440
+ function negateOperator(op) {
11441
+ return must(negateOperatorMap[op]);
11104
11442
  }
11105
- function normalizeJunctionRelationship(relationship, tableSchemaCache) {
11106
- return {
11107
- source: relationship.source,
11108
- junction: {
11109
- sourceField: relationship.junction.sourceField,
11110
- destField: relationship.junction.destField,
11111
- schema: normalizeLazyTableSchema(
11112
- relationship.junction.schema,
11113
- tableSchemaCache
11114
- )
11115
- },
11116
- dest: {
11117
- field: relationship.dest.field,
11118
- schema: normalizeLazyTableSchema(
11119
- relationship.dest.schema,
11120
- tableSchemaCache
11121
- )
11443
+ function filterUndefined(array9) {
11444
+ return array9.filter((e) => e !== void 0);
11445
+ }
11446
+ function filterTrue(conditions) {
11447
+ return conditions.filter((c) => !isAlwaysTrue(c));
11448
+ }
11449
+ function filterFalse(conditions) {
11450
+ return conditions.filter((c) => !isAlwaysFalse(c));
11451
+ }
11452
+
11453
+ // ../zql/src/query/dnf.ts
11454
+ function dnf(condition) {
11455
+ return unwrap(dnfInner(condition));
11456
+ }
11457
+ function dnfInner(condition) {
11458
+ switch (condition.type) {
11459
+ case "simple":
11460
+ case "correlatedSubquery":
11461
+ return { type: "or", conditions: [condition] };
11462
+ case "and":
11463
+ return distributeAnd(condition.conditions.map(dnfInner));
11464
+ case "or":
11465
+ return {
11466
+ type: "or",
11467
+ conditions: flatten(
11468
+ "or",
11469
+ condition.conditions.map(dnfInner).flatMap((c) => c.conditions)
11470
+ )
11471
+ };
11472
+ default:
11473
+ unreachable(condition);
11474
+ }
11475
+ }
11476
+ function distributeAnd(conditions) {
11477
+ if (conditions.length === 0) {
11478
+ return { type: "or", conditions: [TRUE] };
11479
+ }
11480
+ return conditions.reduce((acc, orCondition) => {
11481
+ const newConditions = [];
11482
+ for (const accCondition of acc.conditions) {
11483
+ for (const orSubCondition of orCondition.conditions) {
11484
+ newConditions.push({
11485
+ type: "and",
11486
+ conditions: [accCondition, orSubCondition]
11487
+ });
11488
+ }
11122
11489
  }
11123
- };
11490
+ return {
11491
+ type: "or",
11492
+ conditions: flatten("or", newConditions)
11493
+ };
11494
+ });
11124
11495
  }
11125
- function normalizeLazyTableSchema(tableSchema, buildCache) {
11126
- const tableSchemaInstance = typeof tableSchema === "function" ? tableSchema() : tableSchema;
11127
- return normalizeTableSchemaWithCache(
11128
- tableSchemaInstance,
11129
- tableSchemaInstance.tableName,
11130
- // Don't care about name here.
11131
- buildCache
11132
- );
11496
+ function unwrap(c) {
11497
+ if (c.type === "simple" || c.type === "correlatedSubquery") {
11498
+ return c;
11499
+ }
11500
+ if (c.conditions.length === 1) {
11501
+ return unwrap(c.conditions[0]);
11502
+ }
11503
+ return { type: c.type, conditions: flatten(c.type, c.conditions.map(unwrap)) };
11133
11504
  }
11134
11505
 
11135
11506
  // ../zql/src/query/query-impl.ts
@@ -11139,6 +11510,15 @@ function newQuery(delegate, tableSchema) {
11139
11510
  function newQueryWithDetails(delegate, schema, ast, format) {
11140
11511
  return new QueryImpl(delegate, schema, ast, format);
11141
11512
  }
11513
+ function staticParam(anchorClass, field) {
11514
+ return {
11515
+ type: "static",
11516
+ anchor: anchorClass,
11517
+ field
11518
+ };
11519
+ }
11520
+ var subqueryFilterCount = 0;
11521
+ var SUBQ_PREFIX = "zsubq_";
11142
11522
  var AbstractQuery = class {
11143
11523
  #ast;
11144
11524
  #schema;
@@ -11160,9 +11540,6 @@ var AbstractQuery = class {
11160
11540
  }
11161
11541
  return this.#hash;
11162
11542
  }
11163
- select(..._fields) {
11164
- return this._newQuery(this.#schema, this.#ast, this.#format);
11165
- }
11166
11543
  one() {
11167
11544
  return this._newQuery(
11168
11545
  this.#schema,
@@ -11176,13 +11553,21 @@ var AbstractQuery = class {
11176
11553
  }
11177
11554
  );
11178
11555
  }
11556
+ whereExists(relationship, cb = (q) => q) {
11557
+ return this.where(({ exists }) => exists(relationship, cb));
11558
+ }
11179
11559
  related(relationship, cb = (q) => q) {
11560
+ if (relationship.startsWith(SUBQ_PREFIX)) {
11561
+ throw new Error(
11562
+ `Relationship names may not start with "${SUBQ_PREFIX}". That is a reserved prefix.`
11563
+ );
11564
+ }
11180
11565
  const related = this.#schema.relationships[relationship];
11181
11566
  assert(related, "Invalid relationship");
11182
- const related1 = related;
11183
- const related2 = related;
11184
- if (isFieldRelationship(related1)) {
11185
- const destSchema = related1.dest.schema;
11567
+ const fieldRelationship = related;
11568
+ const junctionRelationship = related;
11569
+ if (isFieldRelationship(fieldRelationship)) {
11570
+ const destSchema = fieldRelationship.dest.schema;
11186
11571
  const sq = cb(
11187
11572
  this._newQuery(
11188
11573
  destSchema,
@@ -11201,8 +11586,8 @@ var AbstractQuery = class {
11201
11586
  ...this.#ast.related ?? [],
11202
11587
  {
11203
11588
  correlation: {
11204
- parentField: related1.source,
11205
- childField: related1.dest.field,
11589
+ parentField: fieldRelationship.source,
11590
+ childField: fieldRelationship.dest.field,
11206
11591
  op: "="
11207
11592
  },
11208
11593
  subquery: addPrimaryKeysToAst(destSchema, sq.#ast)
@@ -11218,9 +11603,9 @@ var AbstractQuery = class {
11218
11603
  }
11219
11604
  );
11220
11605
  }
11221
- if (isJunctionRelationship(related2)) {
11222
- const destSchema = related2.dest.schema;
11223
- const junctionSchema = related2.junction.schema;
11606
+ if (isJunctionRelationship(junctionRelationship)) {
11607
+ const destSchema = junctionRelationship.dest.schema;
11608
+ const junctionSchema = junctionRelationship.junction.schema;
11224
11609
  const sq = cb(
11225
11610
  this._newQuery(
11226
11611
  destSchema,
@@ -11239,8 +11624,8 @@ var AbstractQuery = class {
11239
11624
  ...this.#ast.related ?? [],
11240
11625
  {
11241
11626
  correlation: {
11242
- parentField: related2.source,
11243
- childField: related2.junction.sourceField,
11627
+ parentField: junctionRelationship.source,
11628
+ childField: junctionRelationship.junction.sourceField,
11244
11629
  op: "="
11245
11630
  },
11246
11631
  subquery: {
@@ -11250,8 +11635,8 @@ var AbstractQuery = class {
11250
11635
  related: [
11251
11636
  {
11252
11637
  correlation: {
11253
- parentField: related2.junction.destField,
11254
- childField: related2.dest.field,
11638
+ parentField: junctionRelationship.junction.destField,
11639
+ childField: junctionRelationship.dest.field,
11255
11640
  op: "="
11256
11641
  },
11257
11642
  hidden: true,
@@ -11273,13 +11658,13 @@ var AbstractQuery = class {
11273
11658
  }
11274
11659
  throw new Error(`Invalid relationship ${relationship}`);
11275
11660
  }
11276
- where(field, opOrValue, value) {
11661
+ where(fieldOrExpressionFactory, opOrValue, value) {
11277
11662
  let cond;
11278
- if (opOrValue === void 0 && value === void 0) {
11279
- assert(typeof field !== "string", `Invalid condition: ${field}`);
11280
- cond = field;
11663
+ if (typeof fieldOrExpressionFactory === "function") {
11664
+ cond = fieldOrExpressionFactory(new ExpressionBuilder(this.#exists));
11281
11665
  } else {
11282
- cond = cmp(field, opOrValue, value);
11666
+ assert(opOrValue !== void 0, "Invalid condition");
11667
+ cond = cmp(fieldOrExpressionFactory, opOrValue, value);
11283
11668
  }
11284
11669
  const existingWhere = this.#ast.where;
11285
11670
  if (existingWhere) {
@@ -11289,7 +11674,7 @@ var AbstractQuery = class {
11289
11674
  this.#schema,
11290
11675
  {
11291
11676
  ...this.#ast,
11292
- where: cond
11677
+ where: dnf(cond)
11293
11678
  },
11294
11679
  this.#format
11295
11680
  );
@@ -11333,6 +11718,81 @@ var AbstractQuery = class {
11333
11718
  this.#format
11334
11719
  );
11335
11720
  }
11721
+ #exists = (relationship, cb = (q) => q) => {
11722
+ ++subqueryFilterCount;
11723
+ const related = this.#schema.relationships[relationship];
11724
+ assert(related, "Invalid relationship");
11725
+ const fieldRelationship = related;
11726
+ const junctionRelationship = related;
11727
+ if (isFieldRelationship(fieldRelationship)) {
11728
+ const destSchema = fieldRelationship.dest.schema;
11729
+ const sq = cb(
11730
+ this._newQuery(
11731
+ destSchema,
11732
+ {
11733
+ table: destSchema.tableName,
11734
+ alias: `${SUBQ_PREFIX}${subqueryFilterCount}_${relationship}`
11735
+ },
11736
+ void 0
11737
+ )
11738
+ );
11739
+ return {
11740
+ type: "correlatedSubquery",
11741
+ related: {
11742
+ correlation: {
11743
+ parentField: fieldRelationship.source,
11744
+ childField: fieldRelationship.dest.field,
11745
+ op: "="
11746
+ },
11747
+ subquery: addPrimaryKeysToAst(destSchema, sq.#ast)
11748
+ },
11749
+ op: "EXISTS"
11750
+ };
11751
+ }
11752
+ if (isJunctionRelationship(junctionRelationship)) {
11753
+ const destSchema = junctionRelationship.dest.schema;
11754
+ const junctionSchema = junctionRelationship.junction.schema;
11755
+ const queryToDest = cb(
11756
+ this._newQuery(
11757
+ destSchema,
11758
+ {
11759
+ table: destSchema.tableName,
11760
+ alias: `${SUBQ_PREFIX}${subqueryFilterCount}_${relationship}`
11761
+ },
11762
+ void 0
11763
+ )
11764
+ );
11765
+ return {
11766
+ type: "correlatedSubquery",
11767
+ related: {
11768
+ correlation: {
11769
+ parentField: junctionRelationship.source,
11770
+ childField: junctionRelationship.junction.sourceField,
11771
+ op: "="
11772
+ },
11773
+ subquery: {
11774
+ table: junctionSchema.tableName,
11775
+ alias: `${SUBQ_PREFIX}${subqueryFilterCount}_${relationship}`,
11776
+ orderBy: addPrimaryKeys(junctionSchema, void 0),
11777
+ where: {
11778
+ type: "correlatedSubquery",
11779
+ related: {
11780
+ correlation: {
11781
+ parentField: junctionRelationship.junction.destField,
11782
+ childField: junctionRelationship.dest.field,
11783
+ op: "="
11784
+ },
11785
+ subquery: addPrimaryKeysToAst(destSchema, queryToDest.#ast)
11786
+ },
11787
+ op: "EXISTS"
11788
+ }
11789
+ }
11790
+ },
11791
+ op: "EXISTS"
11792
+ };
11793
+ }
11794
+ throw new Error(`Invalid relationship ${relationship}`);
11795
+ };
11336
11796
  #completedAST;
11337
11797
  _completeAst() {
11338
11798
  if (!this.#completedAST) {
@@ -11444,6 +11904,113 @@ function arrayViewFactory(_query, input, format, onDestroy, onTransactionCommit)
11444
11904
  return v2;
11445
11905
  }
11446
11906
 
11907
+ // ../zql/src/query/auth-query.ts
11908
+ var AuthQuery = class _AuthQuery extends AbstractQuery {
11909
+ constructor(schema, ast = { table: schema.tableName }, format) {
11910
+ super(schema, ast, format);
11911
+ }
11912
+ _newQuery(schema, ast, format) {
11913
+ return new _AuthQuery(schema, ast, format);
11914
+ }
11915
+ get ast() {
11916
+ return this._completeAst();
11917
+ }
11918
+ materialize() {
11919
+ throw new Error("AuthQuery cannot be materialized");
11920
+ }
11921
+ run() {
11922
+ throw new Error("AuthQuery cannot be run");
11923
+ }
11924
+ preload() {
11925
+ throw new Error("AuthQuery cannot be preloaded");
11926
+ }
11927
+ };
11928
+
11929
+ // ../zero-schema/src/authorization.ts
11930
+ async function defineAuthorization(schema, definer) {
11931
+ const normalizedSchema = normalizeSchema(schema);
11932
+ const queries = {};
11933
+ for (const [name, tableSchema] of Object.entries(normalizedSchema.tables)) {
11934
+ queries[name] = new AuthQuery(tableSchema);
11935
+ }
11936
+ const config = await definer(queries);
11937
+ return compileAuthorization(config);
11938
+ }
11939
+ function compileAuthorization(authz) {
11940
+ if (!authz) {
11941
+ return void 0;
11942
+ }
11943
+ const ret = {};
11944
+ for (const [tableName, tableConfig] of Object.entries(authz)) {
11945
+ ret[tableName] = {
11946
+ row: compileRowConfig(tableConfig.row),
11947
+ cell: compileCellConfig(tableConfig.cell)
11948
+ };
11949
+ }
11950
+ return ret;
11951
+ }
11952
+ function compileRowConfig(rowRules) {
11953
+ if (!rowRules) {
11954
+ return void 0;
11955
+ }
11956
+ return {
11957
+ select: compileInstanceRules(rowRules.select),
11958
+ insert: compileInstanceRules(rowRules.insert),
11959
+ update: compileInstanceRules(rowRules.update),
11960
+ delete: compileInstanceRules(rowRules.delete)
11961
+ };
11962
+ }
11963
+ function compileInstanceRules(rules) {
11964
+ if (!rules) {
11965
+ return void 0;
11966
+ }
11967
+ return rules.map(
11968
+ (rule) => [
11969
+ "allow",
11970
+ rule(
11971
+ authDataRef,
11972
+ preMutationRowRef
11973
+ ).ast
11974
+ ]
11975
+ );
11976
+ }
11977
+ function compileCellConfig(cellRules) {
11978
+ if (!cellRules) {
11979
+ return void 0;
11980
+ }
11981
+ const ret = {};
11982
+ for (const [columnName, rules] of Object.entries(cellRules)) {
11983
+ ret[columnName] = {
11984
+ select: compileInstanceRules(rules.select),
11985
+ insert: compileInstanceRules(rules.insert),
11986
+ update: compileInstanceRules(rules.update),
11987
+ delete: compileInstanceRules(rules.delete)
11988
+ };
11989
+ }
11990
+ return ret;
11991
+ }
11992
+ var authDataRef = new Proxy(
11993
+ {},
11994
+ {
11995
+ get(_target, prop, _receiver) {
11996
+ return staticParam("authData", prop);
11997
+ }
11998
+ }
11999
+ );
12000
+ var preMutationRowRef = new Proxy(
12001
+ {},
12002
+ {
12003
+ get(_target, prop, _receiver) {
12004
+ return staticParam("preMutationRow", prop);
12005
+ }
12006
+ }
12007
+ );
12008
+
12009
+ // ../zero-schema/src/schema.ts
12010
+ function createSchema(schema) {
12011
+ return schema;
12012
+ }
12013
+
11447
12014
  // ../zql/src/query/escape-like.ts
11448
12015
  function escapeLike(val) {
11449
12016
  return val.replace(/[%_]/g, "\\$&");
@@ -11685,14 +12252,14 @@ var pingMessageSchema = valita_exports.tuple([valita_exports.literal("ping"), pi
11685
12252
 
11686
12253
  // ../zero-protocol/src/push.ts
11687
12254
  var CRUD_MUTATION_NAME = "_zero_crud";
11688
- var createOpSchema = valita_exports.object({
11689
- op: valita_exports.literal("create"),
12255
+ var insertOpSchema = valita_exports.object({
12256
+ op: valita_exports.literal("insert"),
11690
12257
  tableName: valita_exports.string(),
11691
12258
  primaryKey: primaryKeySchema,
11692
12259
  value: rowSchema
11693
12260
  });
11694
- var setOpSchema = valita_exports.object({
11695
- op: valita_exports.literal("set"),
12261
+ var upsertOpSchema = valita_exports.object({
12262
+ op: valita_exports.literal("upsert"),
11696
12263
  tableName: valita_exports.string(),
11697
12264
  primaryKey: primaryKeySchema,
11698
12265
  value: rowSchema
@@ -11712,8 +12279,8 @@ var deleteOpSchema = valita_exports.object({
11712
12279
  value: primaryKeyValueRecordSchema
11713
12280
  });
11714
12281
  var crudOpSchema = valita_exports.union(
11715
- createOpSchema,
11716
- setOpSchema,
12282
+ insertOpSchema,
12283
+ upsertOpSchema,
11717
12284
  updateOpSchema2,
11718
12285
  deleteOpSchema
11719
12286
  );
@@ -13482,6 +14049,8 @@ var MemorySource = class {
13482
14049
  };
13483
14050
  }
13484
14051
  connect(sort, optionalFilters) {
14052
+ const filteredOptionalFilters = filterOptionalFilters(optionalFilters);
14053
+ const predicates = filteredOptionalFilters.filters.map((c) => createPredicate(c));
13485
14054
  const input = {
13486
14055
  getSchema: () => schema,
13487
14056
  fetch: (req) => this.#fetch(req, connection),
@@ -13492,11 +14061,8 @@ var MemorySource = class {
13492
14061
  destroy: () => {
13493
14062
  this.#disconnect(input);
13494
14063
  },
13495
- appliedFilters: false
14064
+ appliedFilters: filteredOptionalFilters.allApplied
13496
14065
  };
13497
- const predicates = filteredOptionalFilters(
13498
- optionalFilters
13499
- ).filters.map((c) => createPredicate(c));
13500
14066
  const connection = {
13501
14067
  input,
13502
14068
  output: void 0,
@@ -13752,87 +14318,74 @@ function* generateWithOverlay(startAt, rows, constraint, overlay, compare) {
13752
14318
  yield* generateWithOverlayInner(rows, overlays, compare);
13753
14319
  }
13754
14320
  function computeOverlays(startAt, constraint, overlay, compare) {
13755
- let secondOverlay;
13756
- if (overlay?.change.type === "edit" && compare(overlay.change.row, overlay.change.oldRow) !== 0) {
13757
- [overlay, secondOverlay] = splitEditChange(overlay, compare);
14321
+ let overlays = {
14322
+ add: void 0,
14323
+ remove: void 0
14324
+ };
14325
+ switch (overlay?.change.type) {
14326
+ case "add":
14327
+ overlays = {
14328
+ add: overlay.change.row,
14329
+ remove: void 0
14330
+ };
14331
+ break;
14332
+ case "remove":
14333
+ overlays = {
14334
+ add: void 0,
14335
+ remove: overlay.change.row
14336
+ };
14337
+ break;
14338
+ case "edit":
14339
+ overlays = {
14340
+ add: overlay.change.row,
14341
+ remove: overlay.change.oldRow
14342
+ };
14343
+ break;
13758
14344
  }
13759
14345
  if (startAt) {
13760
- overlay = overlayForStartAt(overlay, startAt, compare);
13761
- secondOverlay = overlayForStartAt(secondOverlay, startAt, compare);
14346
+ overlays = overlaysForStartAt(overlays, startAt, compare);
13762
14347
  }
13763
14348
  if (constraint) {
13764
- overlay = overlayForConstraint(overlay, constraint);
13765
- secondOverlay = overlayForConstraint(secondOverlay, constraint);
13766
- }
13767
- if (secondOverlay !== void 0 && overlay === void 0) {
13768
- overlay = secondOverlay;
13769
- secondOverlay = void 0;
14349
+ overlays = overlaysForConstraint(overlays, constraint);
13770
14350
  }
13771
- return [overlay, secondOverlay];
14351
+ return overlays;
13772
14352
  }
13773
- function overlayForStartAt(overlay, startAt, compare) {
13774
- if (!overlay) {
13775
- return void 0;
13776
- }
13777
- if (compare(overlay.change.row, startAt) < 0) {
13778
- return void 0;
13779
- }
13780
- return overlay;
13781
- }
13782
- function overlayForConstraint(overlay, constraint) {
13783
- if (!overlay) {
13784
- return void 0;
13785
- }
13786
- if (!valuesEqual(overlay.change.row[constraint.key], constraint.value)) {
13787
- return void 0;
13788
- }
13789
- return overlay;
13790
- }
13791
- function splitEditChange(overlay, compare) {
13792
- const { oldRow, row } = overlay.change;
13793
- const removeOverlay = {
13794
- outputIndex: overlay.outputIndex,
13795
- change: { type: "remove", row: oldRow }
14353
+ function overlaysForStartAt({ add, remove }, startAt, compare) {
14354
+ const undefinedIfBeforeStartAt = (row) => row === void 0 || compare(row, startAt) < 0 ? void 0 : row;
14355
+ return {
14356
+ add: undefinedIfBeforeStartAt(add),
14357
+ remove: undefinedIfBeforeStartAt(remove)
13796
14358
  };
13797
- const addOverlay = {
13798
- outputIndex: overlay.outputIndex,
13799
- change: { type: "add", row }
14359
+ }
14360
+ function overlaysForConstraint({ add, remove }, constraint) {
14361
+ const undefinedIfDoesntMatchConstraint = (row) => row === void 0 || !valuesEqual(row[constraint.key], constraint.value) ? void 0 : row;
14362
+ return {
14363
+ add: undefinedIfDoesntMatchConstraint(add),
14364
+ remove: undefinedIfDoesntMatchConstraint(remove)
13800
14365
  };
13801
- const cmp2 = compare(oldRow, row);
13802
- assert(cmp2 !== 0, "We should not split edit change with same PK");
13803
- if (cmp2 < 0) {
13804
- return [removeOverlay, addOverlay];
13805
- }
13806
- return [addOverlay, removeOverlay];
13807
14366
  }
13808
14367
  function* generateWithOverlayInner(rowIterator, overlays, compare) {
13809
- let [overlay, secondOverlay] = overlays;
14368
+ let addOverlayYielded = false;
14369
+ let removeOverlaySkipped = false;
13810
14370
  for (const row of rowIterator) {
13811
- if (overlay) {
13812
- if (overlay.change.type === "add" || overlay.change.type === "edit") {
13813
- const cmp2 = compare(overlay.change.row, row);
13814
- if (cmp2 < 0) {
13815
- yield { row: overlay.change.row, relationships: {} };
13816
- overlay = secondOverlay;
13817
- secondOverlay = void 0;
13818
- }
14371
+ if (!addOverlayYielded && overlays.add) {
14372
+ const cmp2 = compare(overlays.add, row);
14373
+ if (cmp2 < 0) {
14374
+ addOverlayYielded = true;
14375
+ yield { row: overlays.add, relationships: {} };
13819
14376
  }
13820
- if (overlay?.change.type === "remove") {
13821
- const cmp2 = compare(overlay.change.row, row);
13822
- if (cmp2 < 0) {
13823
- overlay = secondOverlay;
13824
- secondOverlay = void 0;
13825
- } else if (cmp2 === 0) {
13826
- overlay = secondOverlay;
13827
- secondOverlay = void 0;
13828
- continue;
13829
- }
14377
+ }
14378
+ if (!removeOverlaySkipped && overlays.remove) {
14379
+ const cmp2 = compare(overlays.remove, row);
14380
+ if (cmp2 === 0) {
14381
+ removeOverlaySkipped = true;
14382
+ continue;
13830
14383
  }
13831
14384
  }
13832
14385
  yield { row, relationships: {} };
13833
14386
  }
13834
- if (overlay && overlay.change.type === "add") {
13835
- yield { row: overlay.change.row, relationships: {} };
14387
+ if (!addOverlayYielded && overlays.add) {
14388
+ yield { row: overlays.add, relationships: {} };
13836
14389
  }
13837
14390
  }
13838
14391
  var minValue = Symbol("min-value");
@@ -13867,7 +14420,7 @@ function compareBounds(a, b) {
13867
14420
  }
13868
14421
  return compareValues(a, b);
13869
14422
  }
13870
- function filteredOptionalFilters(optionalFilters) {
14423
+ function filterOptionalFilters(optionalFilters) {
13871
14424
  if (optionalFilters) {
13872
14425
  if (optionalFilters.type === "or" && optionalFilters.conditions.length === 1) {
13873
14426
  optionalFilters = optionalFilters.conditions[0];
@@ -14075,7 +14628,7 @@ var ZeroContext = class {
14075
14628
  function makeCRUDMutate(schema, repMutate) {
14076
14629
  const { [CRUD_MUTATION_NAME]: zeroCRUD } = repMutate;
14077
14630
  let inBatch = false;
14078
- const mutate = async (body) => {
14631
+ const mutateBatch = async (body) => {
14079
14632
  if (inBatch) {
14080
14633
  throw new Error("Cannot call mutate inside a batch");
14081
14634
  }
@@ -14098,6 +14651,7 @@ function makeCRUDMutate(schema, repMutate) {
14098
14651
  throw new Error(`Cannot call mutate.${tableName}.${op} inside a batch`);
14099
14652
  }
14100
14653
  };
14654
+ const mutate = {};
14101
14655
  for (const [name, tableSchema] of Object.entries(schema.tables)) {
14102
14656
  mutate[name] = makeEntityCRUDMutate(
14103
14657
  name,
@@ -14106,24 +14660,27 @@ function makeCRUDMutate(schema, repMutate) {
14106
14660
  assertNotInBatch
14107
14661
  );
14108
14662
  }
14109
- return mutate;
14663
+ return {
14664
+ mutate,
14665
+ mutateBatch
14666
+ };
14110
14667
  }
14111
14668
  function makeEntityCRUDMutate(tableName, primaryKey, zeroCRUD, assertNotInBatch) {
14112
14669
  return {
14113
- create: (value) => {
14114
- assertNotInBatch(tableName, "create");
14670
+ insert: (value) => {
14671
+ assertNotInBatch(tableName, "insert");
14115
14672
  const op = {
14116
- op: "create",
14673
+ op: "insert",
14117
14674
  tableName,
14118
14675
  primaryKey,
14119
14676
  value
14120
14677
  };
14121
14678
  return zeroCRUD({ ops: [op] });
14122
14679
  },
14123
- set: (value) => {
14124
- assertNotInBatch(tableName, "set");
14680
+ upsert: (value) => {
14681
+ assertNotInBatch(tableName, "upsert");
14125
14682
  const op = {
14126
- op: "set",
14683
+ op: "upsert",
14127
14684
  tableName,
14128
14685
  primaryKey,
14129
14686
  value
@@ -14155,9 +14712,9 @@ function makeEntityCRUDMutate(tableName, primaryKey, zeroCRUD, assertNotInBatch)
14155
14712
  function makeBatchCRUDMutate(tableName, schema, ops) {
14156
14713
  const { primaryKey } = schema.tables[tableName];
14157
14714
  return {
14158
- create: (value) => {
14715
+ insert: (value) => {
14159
14716
  const op = {
14160
- op: "create",
14717
+ op: "insert",
14161
14718
  tableName,
14162
14719
  primaryKey,
14163
14720
  value
@@ -14165,9 +14722,9 @@ function makeBatchCRUDMutate(tableName, schema, ops) {
14165
14722
  ops.push(op);
14166
14723
  return promiseVoid;
14167
14724
  },
14168
- set: (value) => {
14725
+ upsert: (value) => {
14169
14726
  const op = {
14170
- op: "set",
14727
+ op: "upsert",
14171
14728
  tableName,
14172
14729
  primaryKey,
14173
14730
  value
@@ -14201,11 +14758,11 @@ function makeCRUDMutator(schema) {
14201
14758
  return async function zeroCRUDMutator(tx, crudArg) {
14202
14759
  for (const op of crudArg.ops) {
14203
14760
  switch (op.op) {
14204
- case "create":
14205
- await createImpl(tx, op, schema);
14761
+ case "insert":
14762
+ await insertImpl(tx, op, schema);
14206
14763
  break;
14207
- case "set":
14208
- await setImpl(tx, op, schema);
14764
+ case "upsert":
14765
+ await upsertImpl(tx, op, schema);
14209
14766
  break;
14210
14767
  case "update":
14211
14768
  await updateImpl(tx, op, schema);
@@ -14217,23 +14774,40 @@ function makeCRUDMutator(schema) {
14217
14774
  }
14218
14775
  };
14219
14776
  }
14220
- async function createImpl(tx, arg, schema) {
14777
+ function defaultOptionalFieldsToNull(schema, value) {
14778
+ let rv = value;
14779
+ for (const name in schema.columns) {
14780
+ if (rv[name] === void 0) {
14781
+ rv = { ...rv, [name]: null };
14782
+ }
14783
+ }
14784
+ return rv;
14785
+ }
14786
+ async function insertImpl(tx, arg, schema) {
14221
14787
  const key = toPrimaryKeyString(
14222
14788
  arg.tableName,
14223
14789
  schema.tables[arg.tableName].primaryKey,
14224
14790
  arg.value
14225
14791
  );
14226
14792
  if (!await tx.has(key)) {
14227
- await tx.set(key, arg.value);
14793
+ const val = defaultOptionalFieldsToNull(
14794
+ schema.tables[arg.tableName],
14795
+ arg.value
14796
+ );
14797
+ await tx.set(key, val);
14228
14798
  }
14229
14799
  }
14230
- async function setImpl(tx, arg, schema) {
14800
+ async function upsertImpl(tx, arg, schema) {
14231
14801
  const key = toPrimaryKeyString(
14232
14802
  arg.tableName,
14233
14803
  schema.tables[arg.tableName].primaryKey,
14234
14804
  arg.value
14235
14805
  );
14236
- await tx.set(key, arg.value);
14806
+ const val = defaultOptionalFieldsToNull(
14807
+ schema.tables[arg.tableName],
14808
+ arg.value
14809
+ );
14810
+ await tx.set(key, val);
14237
14811
  }
14238
14812
  async function updateImpl(tx, arg, schema) {
14239
14813
  const key = toPrimaryKeyString(
@@ -14246,7 +14820,12 @@ async function updateImpl(tx, arg, schema) {
14246
14820
  return;
14247
14821
  }
14248
14822
  const update = arg.value;
14249
- const next = { ...prev, ...update };
14823
+ const next = { ...prev };
14824
+ for (const k in update) {
14825
+ if (update[k] !== void 0) {
14826
+ next[k] = update[k];
14827
+ }
14828
+ }
14250
14829
  await tx.set(key, next);
14251
14830
  }
14252
14831
  async function deleteImpl(tx, arg, schema) {
@@ -14277,6 +14856,9 @@ function shouldEnableAnalytics(server, enableAnalytics = true) {
14277
14856
  function toWSString(url) {
14278
14857
  return "ws" + url.slice(4);
14279
14858
  }
14859
+ function appendPath(url, toAppend) {
14860
+ return url + (url.endsWith("/") ? toAppend.substring(1) : toAppend);
14861
+ }
14280
14862
 
14281
14863
  // ../zero-client/src/client/log-options.ts
14282
14864
  import {
@@ -14503,7 +15085,7 @@ function makeMessage(message, context, logLevel) {
14503
15085
  }
14504
15086
 
14505
15087
  // ../zero-client/src/client/version.ts
14506
- var version2 = "0.5.2024110200+4ba53b";
15088
+ var version2 = "0.6.2024111600+92a1ea";
14507
15089
 
14508
15090
  // ../zero-client/src/client/log-options.ts
14509
15091
  var LevelFilterLogSink = class {
@@ -14537,9 +15119,9 @@ function createLogOptions(options, createDatadogLogSink = (options2) => new Data
14537
15119
  };
14538
15120
  }
14539
15121
  const serverURL = new URL(server);
14540
- const socketHostname = serverURL.hostname;
14541
- const datadogServiceLabel = socketHostname.endsWith(ZERO_SASS_DOMAIN) ? socketHostname.substring(0, socketHostname.length - ZERO_SASS_DOMAIN.length).toLowerCase() : socketHostname;
14542
- const baseURL = new URL("/api/logs/v0/log", server);
15122
+ const { hostname } = serverURL;
15123
+ const datadogServiceLabel = hostname.endsWith(ZERO_SASS_DOMAIN) ? hostname.substring(0, hostname.length - ZERO_SASS_DOMAIN.length).toLowerCase() : hostname;
15124
+ const baseURL = new URL(appendPath(server, "/logs/v0/log"));
14543
15125
  const logLevel = consoleLogLevel === "debug" ? "debug" : "info";
14544
15126
  const logSink = new TeeLogSink2([
14545
15127
  new LevelFilterLogSink(consoleLogSink4, consoleLogLevel),
@@ -14789,30 +15371,6 @@ var State = class {
14789
15371
  }
14790
15372
  };
14791
15373
 
14792
- // ../zero-client/src/client/normalized-schema.ts
14793
- function normalizeSchema(schema) {
14794
- if (schema instanceof NormalizedSchema) {
14795
- return schema;
14796
- }
14797
- return new NormalizedSchema(schema);
14798
- }
14799
- var NormalizedSchema = class {
14800
- version;
14801
- tables;
14802
- constructor(schema) {
14803
- this.version = schema.version;
14804
- this.tables = normalizeTables(schema.tables);
14805
- }
14806
- };
14807
- function normalizeTables(tables) {
14808
- const rv = {};
14809
- const tableSchemaCache = /* @__PURE__ */ new Map();
14810
- for (const [name, table] of sortedEntries(tables)) {
14811
- rv[name] = normalizeTableSchemaWithCache(table, name, tableSchemaCache);
14812
- }
14813
- return rv;
14814
- }
14815
-
14816
15374
  // ../zero-client/src/client/query-manager.ts
14817
15375
  var QueryManager = class {
14818
15376
  #clientID;
@@ -14993,7 +15551,7 @@ function isAuthErrorKind(kind) {
14993
15551
  // ../zero-client/src/client/server-option.ts
14994
15552
  function validateServerParam(paramName, server) {
14995
15553
  const expectedProtocol = "http";
14996
- const forExample = () => ` For example: "${expectedProtocol}s://myapp-myteam.zero.ms/".`;
15554
+ const forExample = (path2 = "") => ` For example: "${expectedProtocol}s://myapp-myteam.zero.ms/${path2}".`;
14997
15555
  if (!server.startsWith(`${expectedProtocol}://`) && !server.startsWith(`${expectedProtocol}s://`)) {
14998
15556
  throw new Error(
14999
15557
  `ZeroOptions.${paramName} must use the "${expectedProtocol}" or "${expectedProtocol}s" scheme.`
@@ -15008,9 +15566,18 @@ function validateServerParam(paramName, server) {
15008
15566
  );
15009
15567
  }
15010
15568
  const urlString = url.toString();
15011
- if (url.pathname !== "/") {
15569
+ const pathComponents = url.pathname.split("/");
15570
+ if (pathComponents[0] === "") {
15571
+ pathComponents.shift();
15572
+ }
15573
+ if (pathComponents[pathComponents.length - 1] === "") {
15574
+ pathComponents.pop();
15575
+ }
15576
+ if (pathComponents.length > 1) {
15012
15577
  throw new Error(
15013
- `ZeroOptions.${paramName} must not contain a path component (other than "/").${forExample()}`
15578
+ `ZeroOptions.${paramName} may have at most one path component.${forExample(
15579
+ "zero"
15580
+ )}`
15014
15581
  );
15015
15582
  }
15016
15583
  for (const [property, invalidEndsWith] of [
@@ -15050,6 +15617,7 @@ var PokeHandler = class {
15050
15617
  // order poke errors.
15051
15618
  #pokeLock = new Lock3();
15052
15619
  #schema;
15620
+ #raf = getBrowserGlobalMethod("requestAnimationFrame") ?? rafFallback;
15053
15621
  constructor(replicachePoke, onPokeError, clientID, schema, lc) {
15054
15622
  this.#replicachePoke = replicachePoke;
15055
15623
  this.#onPokeError = onPokeError;
@@ -15107,7 +15675,7 @@ var PokeHandler = class {
15107
15675
  #startPlaybackLoop() {
15108
15676
  this.#lc.debug?.("starting playback loop");
15109
15677
  this.#pokePlaybackLoopRunning = true;
15110
- requestAnimationFrame(this.#rafCallback);
15678
+ this.#raf(this.#rafCallback);
15111
15679
  }
15112
15680
  #rafCallback = async () => {
15113
15681
  const rafLC = this.#lc.withContext("rafAt", Math.floor(performance.now()));
@@ -15116,7 +15684,7 @@ var PokeHandler = class {
15116
15684
  this.#pokePlaybackLoopRunning = false;
15117
15685
  return;
15118
15686
  }
15119
- requestAnimationFrame(this.#rafCallback);
15687
+ this.#raf(this.#rafCallback);
15120
15688
  const start = performance.now();
15121
15689
  rafLC.debug?.(
15122
15690
  "raf fired, processing pokes. Since last raf",
@@ -15305,6 +15873,12 @@ function rowsPatchOpToReplicachePatchOp(op, schema) {
15305
15873
  throw new Error("to be implemented");
15306
15874
  }
15307
15875
  }
15876
+ function rafFallback(callback) {
15877
+ setTimeout(callback, 0);
15878
+ }
15879
+
15880
+ // ../zero-client/src/client/protocol-version.ts
15881
+ var PROTOCOL_VERSION = 1;
15308
15882
 
15309
15883
  // ../zero-client/src/client/zero.ts
15310
15884
  var onSetConnectionStateSymbol = Symbol();
@@ -15318,7 +15892,6 @@ var DEFAULT_DISCONNECT_HIDDEN_DELAY_MS = 5e3;
15318
15892
  var CONNECT_TIMEOUT_MS = 1e4;
15319
15893
  var CHECK_CONNECTIVITY_ON_ERROR_FREQUENCY = 6;
15320
15894
  var NULL_LAST_MUTATION_ID_SENT = { clientID: "", id: -1 };
15321
- var REFLECT_VERSION = 1;
15322
15895
  function convertOnUpdateNeededReason(reason) {
15323
15896
  return { type: reason.type };
15324
15897
  }
@@ -15502,7 +16075,8 @@ var Zero = class {
15502
16075
  const server = getServer(options.server);
15503
16076
  this.#enableAnalytics = shouldEnableAnalytics(
15504
16077
  server,
15505
- options.enableAnalytics
16078
+ false
16079
+ // Reenable analytics
15506
16080
  );
15507
16081
  if (jurisdiction !== void 0 && jurisdiction !== "eu") {
15508
16082
  throw new Error('ZeroOptions.jurisdiction must be "eu" if present.');
@@ -15572,7 +16146,12 @@ var Zero = class {
15572
16146
  reason ?? ON_CLIENT_STATE_NOT_FOUND_REASON_CLIENT
15573
16147
  );
15574
16148
  };
15575
- this.mutate = makeCRUDMutate(normalizedSchema, rep.mutate);
16149
+ const { mutate, mutateBatch } = makeCRUDMutate(
16150
+ normalizedSchema,
16151
+ rep.mutate
16152
+ );
16153
+ this.mutate = mutate;
16154
+ this.mutateBatch = mutateBatch;
15576
16155
  this.#queryManager = new QueryManager(
15577
16156
  rep.clientID,
15578
16157
  (msg) => this.#sendChangeDesiredQueries(msg),
@@ -15666,30 +16245,42 @@ var Zero = class {
15666
16245
  return this.#rep.clientGroupID;
15667
16246
  }
15668
16247
  /**
15669
- * Provides facilities to write data to Zero.
16248
+ * Provides simple "CRUD" mutations for the tables in the schema.
15670
16249
  *
15671
- * `mutate` is a function as well as a "namespace" object for doing CRUD style
15672
- * mutations. When used as a function it is used to batch multiple mutations.
16250
+ * Each table has `create`, `set`, `update`, and `delete` methods.
15673
16251
  *
15674
16252
  * ```ts
15675
- * await zero.mutate.issue.create({id: '1', title: 'First issue'});
16253
+ * await zero.mutate.issue.create({id: '1', title: 'First issue', priority: 'high'});
15676
16254
  * await zero.mutate.comment.create({id: '1', text: 'First comment', issueID: '1'});
16255
+ * ```
16256
+ *
16257
+ * The `update` methods support partials. Unspecified or `undefined` fields
16258
+ * are left unchanged:
15677
16259
  *
15678
- * // or as a function:
15679
- * await zero.mutate(m => {
16260
+ * ```ts
16261
+ * // Priority left unchanged.
16262
+ * await zero.mutate.issue.update({id: '1', title: 'Updated title'});
16263
+ * ```
16264
+ */
16265
+ mutate;
16266
+ /**
16267
+ * Provides a way to batch multiple CRUD mutations together:
16268
+ *
16269
+ * ```ts
16270
+ * await zero.mutateBatch(m => {
15680
16271
  * await m.issue.create({id: '1', title: 'First issue'});
15681
16272
  * await m.comment.create({id: '1', text: 'First comment', issueID: '1'});
15682
16273
  * });
15683
16274
  * ```
15684
16275
  *
15685
- * The benefit of using the function form is that it allows you to batch
15686
- * multiple mutations together. This can be more efficient than making
15687
- * individual calls to `create`, `update`, `set`, and `delete`.
16276
+ * Batch sends all mutations in a single transaction. If one fails, all are
16277
+ * rolled back together. Batch can also be more efficient than making many
16278
+ * individual mutations.
15688
16279
  *
15689
- * The function form of `mutate` is not allowed to be called inside another
15690
- * `mutate` function. Doing so will throw an error.
16280
+ * `mutateBatch` is not allowed inside another `mutateBatch` call. Doing so
16281
+ * will throw an error.
15691
16282
  */
15692
- mutate;
16283
+ mutateBatch;
15693
16284
  /**
15694
16285
  * Whether this Zero instance has been closed. Once a Zero instance has
15695
16286
  * been closed it no longer syncs and you can no longer read or write data out
@@ -15760,11 +16351,8 @@ var Zero = class {
15760
16351
  rejectInvalidMessage();
15761
16352
  }
15762
16353
  };
15763
- #onOpen = (e) => {
15764
- const l = addWebSocketIDFromSocketToLogContext(
15765
- e.target,
15766
- this.#lc
15767
- );
16354
+ #onOpen = () => {
16355
+ const l = addWebSocketIDFromSocketToLogContext(this.#socket, this.#lc);
15768
16356
  if (this.#connectStart === void 0) {
15769
16357
  l.error?.(
15770
16358
  "Got open event but connect start time is undefined. This should not happen."
@@ -15779,10 +16367,7 @@ var Zero = class {
15779
16367
  }
15780
16368
  };
15781
16369
  #onClose = (e) => {
15782
- const l = addWebSocketIDFromSocketToLogContext(
15783
- e.target,
15784
- this.#lc
15785
- );
16370
+ const l = addWebSocketIDFromSocketToLogContext(this.#socket, this.#lc);
15786
16371
  const { code, reason, wasClean } = e;
15787
16372
  l.info?.("Got socket close event", { code, reason, wasClean });
15788
16373
  const closeKind = wasClean ? "CleanClose" : "AbruptClose";
@@ -16264,16 +16849,6 @@ var Zero = class {
16264
16849
  }
16265
16850
  if (gotError) {
16266
16851
  this.#setOnline(false);
16267
- let cfGetCheckSucceeded = false;
16268
- const cfGetCheckURL = new URL(this.#server);
16269
- cfGetCheckURL.pathname = "/api/canary/v0/get";
16270
- cfGetCheckURL.searchParams.set("id", nanoid());
16271
- const cfGetCheckController = new AbortController();
16272
- fetch(cfGetCheckURL, { signal: cfGetCheckController.signal }).then((_) => {
16273
- cfGetCheckSucceeded = true;
16274
- }).catch((_) => {
16275
- cfGetCheckSucceeded = false;
16276
- });
16277
16852
  lc.debug?.(
16278
16853
  "Sleeping",
16279
16854
  RUN_LOOP_INTERVAL_MS,
@@ -16281,13 +16856,6 @@ var Zero = class {
16281
16856
  this.#connectionState
16282
16857
  );
16283
16858
  await sleep(RUN_LOOP_INTERVAL_MS);
16284
- cfGetCheckController.abort();
16285
- if (!cfGetCheckSucceeded) {
16286
- lc.info?.(
16287
- "Canary request failed, resetting total time to connect start time."
16288
- );
16289
- this.#totalToConnectStart = void 0;
16290
- }
16291
16859
  }
16292
16860
  }
16293
16861
  }
@@ -16420,8 +16988,9 @@ var Zero = class {
16420
16988
  }
16421
16989
  };
16422
16990
  async function createSocket(rep, queryManager, socketOrigin, baseCookie, clientID, clientGroupID, schemaVersion, userID, auth, jurisdiction, lmid, wsid, debugPerf, lc, maxHeaderLength = 1024 * 8) {
16423
- const url = new URL(socketOrigin);
16424
- url.pathname = `/api/sync/v${REFLECT_VERSION}/connect`;
16991
+ const url = new URL(
16992
+ appendPath(socketOrigin, `/sync/v${PROTOCOL_VERSION}/connect`)
16993
+ );
16425
16994
  const { searchParams } = url;
16426
16995
  searchParams.set("clientID", clientID);
16427
16996
  searchParams.set("clientGroupID", clientGroupID);
@@ -16484,12 +17053,10 @@ export {
16484
17053
  makeIDBName,
16485
17054
  dropDatabase,
16486
17055
  dropAllDatabases,
16487
- cmp,
16488
- and,
16489
- or,
16490
- not,
16491
- QueryImpl,
17056
+ createTableSchema,
17057
+ defineAuthorization,
17058
+ createSchema,
16492
17059
  escapeLike,
16493
17060
  Zero
16494
17061
  };
16495
- //# sourceMappingURL=chunk-INJ4WJHS.js.map
17062
+ //# sourceMappingURL=chunk-V5NTGJ4X.js.map