@rocicorp/zero 1.10.0-canary.21 → 1.10.0-canary.23

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 (334) hide show
  1. package/out/analyze-query/src/bin-analyze.js +1 -1
  2. package/out/analyze-query/src/bin-analyze.js.map +1 -1
  3. package/out/replicache/src/dag/gc.d.ts.map +1 -1
  4. package/out/replicache/src/dag/gc.js +2 -1
  5. package/out/replicache/src/dag/gc.js.map +1 -1
  6. package/out/replicache/src/dag/invalid-ref-count-error.d.ts +12 -0
  7. package/out/replicache/src/dag/invalid-ref-count-error.d.ts.map +1 -0
  8. package/out/replicache/src/dag/invalid-ref-count-error.js +19 -0
  9. package/out/replicache/src/dag/invalid-ref-count-error.js.map +1 -0
  10. package/out/replicache/src/dag/store-impl.d.ts +12 -2
  11. package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
  12. package/out/replicache/src/dag/store-impl.js +22 -8
  13. package/out/replicache/src/dag/store-impl.js.map +1 -1
  14. package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
  15. package/out/replicache/src/kv/expo-sqlite/store.js +1 -1
  16. package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
  17. package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts +15 -5
  18. package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts.map +1 -1
  19. package/out/replicache/src/kv/idb-store-with-mem-fallback.js +25 -25
  20. package/out/replicache/src/kv/idb-store-with-mem-fallback.js.map +1 -1
  21. package/out/replicache/src/kv/idb-store.d.ts +9 -0
  22. package/out/replicache/src/kv/idb-store.d.ts.map +1 -1
  23. package/out/replicache/src/kv/idb-store.js +14 -2
  24. package/out/replicache/src/kv/idb-store.js.map +1 -1
  25. package/out/replicache/src/kv/mem-store.d.ts +1 -0
  26. package/out/replicache/src/kv/mem-store.d.ts.map +1 -1
  27. package/out/replicache/src/kv/mem-store.js +3 -0
  28. package/out/replicache/src/kv/mem-store.js.map +1 -1
  29. package/out/replicache/src/kv/op-sqlite/store.d.ts.map +1 -1
  30. package/out/replicache/src/kv/op-sqlite/store.js +1 -1
  31. package/out/replicache/src/kv/op-sqlite/store.js.map +1 -1
  32. package/out/replicache/src/kv/sqlite-store.d.ts +2 -1
  33. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  34. package/out/replicache/src/kv/sqlite-store.js +6 -1
  35. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  36. package/out/replicache/src/kv/store.d.ts +6 -0
  37. package/out/replicache/src/kv/store.d.ts.map +1 -1
  38. package/out/replicache/src/persist/collect-idb-databases.d.ts +10 -5
  39. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  40. package/out/replicache/src/persist/collect-idb-databases.js +16 -9
  41. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  42. package/out/replicache/src/replicache-impl.d.ts +14 -3
  43. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  44. package/out/replicache/src/replicache-impl.js +104 -9
  45. package/out/replicache/src/replicache-impl.js.map +1 -1
  46. package/out/shared/src/arrays.js +1 -15
  47. package/out/shared/src/arrays.js.map +1 -1
  48. package/out/shared/src/hash.d.ts +1 -0
  49. package/out/shared/src/hash.d.ts.map +1 -1
  50. package/out/shared/src/hash.js +10 -28
  51. package/out/shared/src/hash.js.map +1 -1
  52. package/out/shared/src/iterables.d.ts +2 -0
  53. package/out/shared/src/iterables.d.ts.map +1 -1
  54. package/out/shared/src/iterables.js +18 -1
  55. package/out/shared/src/iterables.js.map +1 -1
  56. package/out/shared/src/json.d.ts.map +1 -1
  57. package/out/shared/src/json.js +2 -2
  58. package/out/shared/src/json.js.map +1 -1
  59. package/out/shared/src/ring-buffer.d.ts +8 -0
  60. package/out/shared/src/ring-buffer.d.ts.map +1 -1
  61. package/out/shared/src/ring-buffer.js +22 -1
  62. package/out/shared/src/ring-buffer.js.map +1 -1
  63. package/out/shared/src/xxhash32.d.ts +36 -0
  64. package/out/shared/src/xxhash32.d.ts.map +1 -0
  65. package/out/shared/src/xxhash32.js +51 -0
  66. package/out/shared/src/xxhash32.js.map +1 -0
  67. package/out/z2s/src/compiler.js +1 -1
  68. package/out/zero/package.js +1 -1
  69. package/out/zero/package.js.map +1 -1
  70. package/out/zero-cache/src/auth/read-authorizer.js +1 -1
  71. package/out/zero-cache/src/config/zero-config.d.ts +8 -0
  72. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  73. package/out/zero-cache/src/config/zero-config.js +28 -1
  74. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  75. package/out/zero-cache/src/custom-queries/transform-query.js +1 -1
  76. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  77. package/out/zero-cache/src/server/change-streamer.js +11 -3
  78. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  79. package/out/zero-cache/src/server/inspector-delegate.d.ts +18 -2
  80. package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
  81. package/out/zero-cache/src/server/inspector-delegate.js +23 -9
  82. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  83. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  84. package/out/zero-cache/src/server/main.js +8 -1
  85. package/out/zero-cache/src/server/main.js.map +1 -1
  86. package/out/zero-cache/src/server/mutator.js +2 -0
  87. package/out/zero-cache/src/server/mutator.js.map +1 -1
  88. package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
  89. package/out/zero-cache/src/server/reaper.js +2 -0
  90. package/out/zero-cache/src/server/reaper.js.map +1 -1
  91. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  92. package/out/zero-cache/src/server/replicator.js +2 -0
  93. package/out/zero-cache/src/server/replicator.js.map +1 -1
  94. package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
  95. package/out/zero-cache/src/server/runner/zero-dispatcher.js +3 -0
  96. package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
  97. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  98. package/out/zero-cache/src/server/syncer.js +2 -0
  99. package/out/zero-cache/src/server/syncer.js.map +1 -1
  100. package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/analyze.js +3 -2
  102. package/out/zero-cache/src/services/analyze.js.map +1 -1
  103. package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
  104. package/out/zero-cache/src/services/change-source/common/backfill-manager.js +14 -1
  105. package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
  106. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
  107. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +15 -3
  108. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
  109. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
  110. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +3 -0
  111. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  112. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +3 -1
  113. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  114. package/out/zero-cache/src/services/mutagen/mutagen.d.ts +5 -0
  115. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  116. package/out/zero-cache/src/services/mutagen/mutagen.js +7 -1
  117. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  118. package/out/zero-cache/src/services/mutagen/pusher.js +3 -2
  119. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  120. package/out/zero-cache/src/services/profz.d.ts +7 -0
  121. package/out/zero-cache/src/services/profz.d.ts.map +1 -0
  122. package/out/zero-cache/src/services/profz.js +103 -0
  123. package/out/zero-cache/src/services/profz.js.map +1 -0
  124. package/out/zero-cache/src/services/run-ast.d.ts +12 -0
  125. package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
  126. package/out/zero-cache/src/services/run-ast.js +27 -15
  127. package/out/zero-cache/src/services/run-ast.js.map +1 -1
  128. package/out/zero-cache/src/services/runner.d.ts.map +1 -1
  129. package/out/zero-cache/src/services/runner.js +1 -1
  130. package/out/zero-cache/src/services/runner.js.map +1 -1
  131. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +45 -0
  132. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  133. package/out/zero-cache/src/services/view-syncer/cvr.js +133 -1
  134. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  135. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts +14 -1
  136. package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts.map +1 -1
  137. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +30 -4
  138. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
  139. package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts +33 -0
  140. package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts.map +1 -0
  141. package/out/zero-cache/src/services/view-syncer/hydration-budget.js +62 -0
  142. package/out/zero-cache/src/services/view-syncer/hydration-budget.js.map +1 -0
  143. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts +51 -0
  144. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts.map +1 -0
  145. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js +78 -0
  146. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js.map +1 -0
  147. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +1 -1
  148. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
  149. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
  150. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  151. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +2 -1
  152. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  153. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +33 -18
  154. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  155. package/out/zero-cache/src/services/view-syncer/query-covering.d.ts.map +1 -1
  156. package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
  157. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +4 -1
  158. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  159. package/out/zero-cache/src/services/view-syncer/snapshotter.js +9 -3
  160. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  161. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +11 -1
  162. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  163. package/out/zero-cache/src/services/view-syncer/view-syncer.js +470 -90
  164. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  165. package/out/zero-cache/src/types/processes.d.ts +32 -0
  166. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  167. package/out/zero-cache/src/types/processes.js +43 -4
  168. package/out/zero-cache/src/types/processes.js.map +1 -1
  169. package/out/zero-cache/src/types/profiler.d.ts +12 -0
  170. package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
  171. package/out/zero-cache/src/types/profiler.js +46 -1
  172. package/out/zero-cache/src/types/profiler.js.map +1 -1
  173. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
  174. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +21 -16
  175. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  176. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  177. package/out/zero-cache/src/workers/syncer.js +10 -1
  178. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  179. package/out/zero-client/src/client/connection-manager.d.ts +20 -0
  180. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  181. package/out/zero-client/src/client/connection-manager.js +32 -14
  182. package/out/zero-client/src/client/connection-manager.js.map +1 -1
  183. package/out/zero-client/src/client/connection-status-enum.d.ts +2 -0
  184. package/out/zero-client/src/client/connection-status-enum.d.ts.map +1 -1
  185. package/out/zero-client/src/client/connection-status-enum.js +3 -1
  186. package/out/zero-client/src/client/connection-status-enum.js.map +1 -1
  187. package/out/zero-client/src/client/connection.d.ts +6 -0
  188. package/out/zero-client/src/client/connection.d.ts.map +1 -1
  189. package/out/zero-client/src/client/connection.js +2 -1
  190. package/out/zero-client/src/client/connection.js.map +1 -1
  191. package/out/zero-client/src/client/context.d.ts +22 -12
  192. package/out/zero-client/src/client/context.d.ts.map +1 -1
  193. package/out/zero-client/src/client/context.js +92 -25
  194. package/out/zero-client/src/client/context.js.map +1 -1
  195. package/out/zero-client/src/client/custom.js +2 -2
  196. package/out/zero-client/src/client/custom.js.map +1 -1
  197. package/out/zero-client/src/client/error.js +1 -1
  198. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  199. package/out/zero-client/src/client/ivm-branch.js +20 -3
  200. package/out/zero-client/src/client/ivm-branch.js.map +1 -1
  201. package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
  202. package/out/zero-client/src/client/mutator-proxy.js +2 -1
  203. package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
  204. package/out/zero-client/src/client/options.d.ts +3 -0
  205. package/out/zero-client/src/client/options.d.ts.map +1 -1
  206. package/out/zero-client/src/client/options.js.map +1 -1
  207. package/out/zero-client/src/client/query-manager.d.ts +2 -0
  208. package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
  209. package/out/zero-client/src/client/query-manager.js +48 -9
  210. package/out/zero-client/src/client/query-manager.js.map +1 -1
  211. package/out/zero-client/src/client/version.js +1 -1
  212. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  213. package/out/zero-client/src/client/zero-rep.js +1 -1
  214. package/out/zero-client/src/client/zero-rep.js.map +1 -1
  215. package/out/zero-client/src/client/zero.d.ts +18 -3
  216. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  217. package/out/zero-client/src/client/zero.js +61 -14
  218. package/out/zero-client/src/client/zero.js.map +1 -1
  219. package/out/zero-client/src/types/query-result.d.ts +2 -0
  220. package/out/zero-client/src/types/query-result.d.ts.map +1 -1
  221. package/out/zero-protocol/src/ast.d.ts +64 -1
  222. package/out/zero-protocol/src/ast.d.ts.map +1 -1
  223. package/out/zero-protocol/src/ast.js +223 -51
  224. package/out/zero-protocol/src/ast.js.map +1 -1
  225. package/out/zero-protocol/src/error.d.ts +1 -1
  226. package/out/zero-protocol/src/query-hash-visitor.d.ts +81 -0
  227. package/out/zero-protocol/src/query-hash-visitor.d.ts.map +1 -0
  228. package/out/zero-protocol/src/query-hash-visitor.js +324 -0
  229. package/out/zero-protocol/src/query-hash-visitor.js.map +1 -0
  230. package/out/zero-protocol/src/query-hash.d.ts +7 -2
  231. package/out/zero-protocol/src/query-hash.d.ts.map +1 -1
  232. package/out/zero-protocol/src/query-hash.js +12 -9
  233. package/out/zero-protocol/src/query-hash.js.map +1 -1
  234. package/out/zero-react/src/use-query.d.ts +5 -4
  235. package/out/zero-react/src/use-query.d.ts.map +1 -1
  236. package/out/zero-react/src/use-query.js +86 -9
  237. package/out/zero-react/src/use-query.js.map +1 -1
  238. package/out/zero-solid/src/solid-view.d.ts +17 -0
  239. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  240. package/out/zero-solid/src/solid-view.js +39 -1
  241. package/out/zero-solid/src/solid-view.js.map +1 -1
  242. package/out/zero-solid/src/use-query.js +5 -3
  243. package/out/zero-solid/src/use-query.js.map +1 -1
  244. package/out/zql/src/builder/debug-delegate.d.ts +6 -1
  245. package/out/zql/src/builder/debug-delegate.d.ts.map +1 -1
  246. package/out/zql/src/builder/debug-delegate.js +14 -2
  247. package/out/zql/src/builder/debug-delegate.js.map +1 -1
  248. package/out/zql/src/ivm/array-view.d.ts +29 -0
  249. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  250. package/out/zql/src/ivm/array-view.js +58 -9
  251. package/out/zql/src/ivm/array-view.js.map +1 -1
  252. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  253. package/out/zql/src/ivm/cap.js +5 -3
  254. package/out/zql/src/ivm/cap.js.map +1 -1
  255. package/out/zql/src/ivm/deferred-input.d.ts.map +1 -1
  256. package/out/zql/src/ivm/deferred-input.js +3 -2
  257. package/out/zql/src/ivm/deferred-input.js.map +1 -1
  258. package/out/zql/src/ivm/exists.d.ts +1 -1
  259. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  260. package/out/zql/src/ivm/exists.js +1 -1
  261. package/out/zql/src/ivm/exists.js.map +1 -1
  262. package/out/zql/src/ivm/fan-in.d.ts +2 -2
  263. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  264. package/out/zql/src/ivm/fan-in.js +6 -5
  265. package/out/zql/src/ivm/fan-in.js.map +1 -1
  266. package/out/zql/src/ivm/fan-out.d.ts +2 -2
  267. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  268. package/out/zql/src/ivm/fan-out.js.map +1 -1
  269. package/out/zql/src/ivm/filter-operators.d.ts +4 -4
  270. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  271. package/out/zql/src/ivm/filter-operators.js +10 -8
  272. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  273. package/out/zql/src/ivm/filter.d.ts +2 -2
  274. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  275. package/out/zql/src/ivm/filter.js +7 -4
  276. package/out/zql/src/ivm/filter.js.map +1 -1
  277. package/out/zql/src/ivm/flipped-join.js +2 -2
  278. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  279. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
  280. package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
  281. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +6 -4
  282. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
  283. package/out/zql/src/ivm/memory-source.d.ts +15 -3
  284. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  285. package/out/zql/src/ivm/memory-source.js +35 -9
  286. package/out/zql/src/ivm/memory-source.js.map +1 -1
  287. package/out/zql/src/ivm/take.d.ts.map +1 -1
  288. package/out/zql/src/ivm/take.js +3 -4
  289. package/out/zql/src/ivm/take.js.map +1 -1
  290. package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
  291. package/out/zql/src/ivm/union-fan-in.js +9 -7
  292. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  293. package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
  294. package/out/zql/src/ivm/view-apply-change.js +3 -3
  295. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  296. package/out/zql/src/ivm/view.d.ts +15 -0
  297. package/out/zql/src/ivm/view.d.ts.map +1 -1
  298. package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
  299. package/out/zql/src/mutate/mutator-registry.js +2 -2
  300. package/out/zql/src/mutate/mutator-registry.js.map +1 -1
  301. package/out/zql/src/query/query-delegate-base.d.ts +4 -2
  302. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  303. package/out/zql/src/query/query-delegate-base.js +69 -36
  304. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  305. package/out/zql/src/query/query-delegate.d.ts +33 -6
  306. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  307. package/out/zql/src/query/query-impl.d.ts +25 -14
  308. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  309. package/out/zql/src/query/query-impl.js +414 -94
  310. package/out/zql/src/query/query-impl.js.map +1 -1
  311. package/out/zql/src/query/query-internals.d.ts +21 -11
  312. package/out/zql/src/query/query-internals.d.ts.map +1 -1
  313. package/out/zql/src/query/query-internals.js.map +1 -1
  314. package/out/zql/src/query/query-transitions.d.ts +171 -0
  315. package/out/zql/src/query/query-transitions.d.ts.map +1 -0
  316. package/out/zql/src/query/query-transitions.js +207 -0
  317. package/out/zql/src/query/query-transitions.js.map +1 -0
  318. package/out/zql/src/query/query.d.ts +11 -2
  319. package/out/zql/src/query/query.d.ts.map +1 -1
  320. package/out/zql/src/query/runnable-query-impl.d.ts +3 -2
  321. package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
  322. package/out/zql/src/query/runnable-query-impl.js +23 -2
  323. package/out/zql/src/query/runnable-query-impl.js.map +1 -1
  324. package/out/zql/src/query/typed-view.d.ts +1 -1
  325. package/out/zql/src/query/typed-view.d.ts.map +1 -1
  326. package/out/zqlite/src/db.d.ts +9 -1
  327. package/out/zqlite/src/db.d.ts.map +1 -1
  328. package/out/zqlite/src/db.js +8 -2
  329. package/out/zqlite/src/db.js.map +1 -1
  330. package/out/zqlite/src/table-source.d.ts +1 -0
  331. package/out/zqlite/src/table-source.d.ts.map +1 -1
  332. package/out/zqlite/src/table-source.js +10 -5
  333. package/out/zqlite/src/table-source.js.map +1 -1
  334. package/package.json +1 -1
@@ -1,11 +1,57 @@
1
+ import { deepEqual } from "../../shared/src/json.js";
1
2
  import { asQueryInternals } from "../../zql/src/query/query-internals.js";
2
3
  import { addContextToQuery } from "../../zql/src/query/query-registry.js";
3
4
  import { DEFAULT_TTL_MS } from "../../zql/src/query/ttl.js";
4
5
  import { useZero } from "./zero-provider.js";
5
6
  import "./bindings.js";
6
7
  import { resolver } from "@rocicorp/resolver";
7
- import React, { useSyncExternalStore } from "react";
8
+ import React, { useRef, useSyncExternalStore } from "react";
8
9
  //#region ../zero-react/src/use-query.tsx
10
+ /**
11
+ * Resolves a query request against the Zero context, reusing the previous
12
+ * result while the request means the same thing.
13
+ *
14
+ * Interning already makes an unchanged *plain* query come back as the same
15
+ * object, so this is aimed at the query-request form -- `queries.issue({id})`
16
+ * -- where every render allocates a fresh request and `addContextToQuery`
17
+ * re-runs the definition. That costs argument validation (a zod parse of
18
+ * byte-identical args) plus a walk of the builder chain, neither of which
19
+ * interning removes: it makes rebuilding the chain cheap and gives the same
20
+ * object back, but only after the work has been done again.
21
+ *
22
+ * A request resolves to the previous query when it names the same
23
+ * `CustomQuery`, the same context, and deep-equal args. Those are exactly the
24
+ * inputs the definition is allowed to depend on: a named query is re-derived
25
+ * on the server from its name and args, so it has to be a pure function of
26
+ * them, or client and server would build different queries.
27
+ *
28
+ * The ref is written during render. That is safe here because it is a pure
29
+ * cache: an entry is derived only from the inputs, so a StrictMode double
30
+ * render or a discarded concurrent render leaves it valid either way.
31
+ */
32
+ function useStableQuery(query, zero) {
33
+ const cacheRef = useRef(void 0);
34
+ if (!query) return;
35
+ const cache = cacheRef.current;
36
+ if (cache && cache.zero === zero) {
37
+ if (cache.rawQuery === query) return cache.q;
38
+ if ("query" in query && cache.customQuery === query.query && cache.context === zero.context && deepEqual(cache.args, query.args)) {
39
+ cache.rawQuery = query;
40
+ return cache.q;
41
+ }
42
+ }
43
+ const q = addContextToQuery(query, zero.context);
44
+ const isRequest = "query" in query;
45
+ cacheRef.current = {
46
+ zero,
47
+ context: zero.context,
48
+ rawQuery: query,
49
+ customQuery: isRequest ? query.query : void 0,
50
+ args: isRequest ? query.args : void 0,
51
+ q
52
+ };
53
+ return q;
54
+ }
9
55
  var reactUse = React.use;
10
56
  var suspend = reactUse ? reactUse : (p) => {
11
57
  throw p;
@@ -16,7 +62,7 @@ function useQuery(query, options) {
16
62
  if (typeof options === "boolean") enabled = options;
17
63
  else if (options) ({enabled = true, ttl = DEFAULT_TTL_MS} = options);
18
64
  const zero = useZero();
19
- const q = query ? addContextToQuery(query, zero.context) : void 0;
65
+ const q = useStableQuery(query, zero);
20
66
  const view = q ? viewStore.getView(zero, q, enabled, ttl) : void 0;
21
67
  return useSyncExternalStore(view?.subscribeReactInternals ?? disabledSubscriber, view?.getSnapshot ?? getDisabledSnapshot, view?.getSnapshot ?? getDisabledSnapshot);
22
68
  }
@@ -27,7 +73,7 @@ function useSuspenseQuery(query, options) {
27
73
  if (typeof options === "boolean") enabled = options;
28
74
  else if (options) ({enabled = true, ttl = DEFAULT_TTL_MS, suspendUntil = "complete"} = options);
29
75
  const zero = useZero();
30
- const q = query ? addContextToQuery(query, zero.context) : void 0;
76
+ const q = useStableQuery(query, zero);
31
77
  const view = q ? viewStore.getView(zero, q, enabled, ttl) : void 0;
32
78
  const snapshot = useSyncExternalStore(view?.subscribeReactInternals ?? disabledSubscriber, view?.getSnapshot ?? getDisabledSnapshot, view?.getSnapshot ?? getDisabledSnapshot);
33
79
  if (view && enabled) {
@@ -39,14 +85,17 @@ function useSuspenseQuery(query, options) {
39
85
  var emptyArray = [];
40
86
  var disabledSubscriber = () => () => {};
41
87
  var resultTypeUnknown = { type: "unknown" };
88
+ var resultTypeCached = { type: "cached" };
42
89
  var resultTypeComplete = { type: "complete" };
43
90
  var resultTypeError = { type: "error" };
44
91
  var disabledQuerySnapshot = [void 0, resultTypeUnknown];
45
92
  var getDisabledSnapshot = () => disabledQuerySnapshot;
46
93
  var emptySnapshotSingularUnknown = [void 0, resultTypeUnknown];
94
+ var emptySnapshotSingularCached = [void 0, resultTypeCached];
47
95
  var emptySnapshotSingularComplete = [void 0, resultTypeComplete];
48
96
  var emptySnapshotSingularErrorUnknown = [void 0, resultTypeError];
49
97
  var emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown];
98
+ var emptySnapshotPluralCached = [emptyArray, resultTypeCached];
50
99
  var emptySnapshotPluralComplete = [emptyArray, resultTypeComplete];
51
100
  var emptySnapshotErrorUnknown = [emptyArray, resultTypeError];
52
101
  function getDefaultSnapshot(singular) {
@@ -63,6 +112,7 @@ function getSnapshot(singular, data, resultType, retryFn, error) {
63
112
  return emptySnapshotSingularErrorUnknown;
64
113
  case "complete": return emptySnapshotSingularComplete;
65
114
  case "unknown": return emptySnapshotSingularUnknown;
115
+ case "cached": return emptySnapshotSingularCached;
66
116
  }
67
117
  if (!singular && data.length === 0) switch (resultType) {
68
118
  case "error":
@@ -70,6 +120,7 @@ function getSnapshot(singular, data, resultType, retryFn, error) {
70
120
  return emptySnapshotErrorUnknown;
71
121
  case "complete": return emptySnapshotPluralComplete;
72
122
  case "unknown": return emptySnapshotPluralUnknown;
123
+ case "cached": return emptySnapshotPluralCached;
73
124
  }
74
125
  switch (resultType) {
75
126
  case "error":
@@ -82,6 +133,7 @@ function getSnapshot(singular, data, resultType, retryFn, error) {
82
133
  })];
83
134
  case "complete": return [data, resultTypeComplete];
84
135
  case "unknown": return [data, resultTypeUnknown];
136
+ case "cached": return [data, resultTypeCached];
85
137
  }
86
138
  }
87
139
  function makeError(retry, error) {
@@ -146,6 +198,17 @@ function makeError(retry, error) {
146
198
  * Swapping `useState` to `useRef` has similar problems.
147
199
  */
148
200
  var ViewStore = class {
201
+ /**
202
+ * Client id, then query hash.
203
+ *
204
+ * Nested rather than keyed by the two joined together, because this is
205
+ * looked up on every render of every `useQuery`. Joining them builds a
206
+ * string that V8 has to hash from scratch, where both halves on their own
207
+ * are strings it has already hashed and cached -- `hash()` is memoized on an
208
+ * interned query, so the same string comes back each render. Measured over a
209
+ * rebuild-and-look-up of one chain, that is the difference between 202ns and
210
+ * 123ns; the join cost more than rebuilding and hashing the whole query.
211
+ */
149
212
  #views = /* @__PURE__ */ new Map();
150
213
  constructor() {}
151
214
  getView(zero, q, enabled, ttl) {
@@ -159,15 +222,23 @@ var ViewStore = class {
159
222
  complete: false,
160
223
  nonEmpty: false
161
224
  };
162
- const hash = qi.hash() + JSON.stringify(qi.format) + zero.clientID;
163
- let existing = this.#views.get(hash);
225
+ const { clientID } = zero;
226
+ const hash = qi.hash();
227
+ let byHash = this.#views.get(clientID);
228
+ let existing = byHash?.get(hash);
164
229
  if (!existing) {
165
230
  existing = new ViewWrapper(q, zero, ttl, (view) => {
166
- const currentView = this.#views.get(hash);
231
+ const views = this.#views.get(clientID);
232
+ const currentView = views?.get(hash);
167
233
  if (currentView && currentView !== view) return;
168
- this.#views.delete(hash);
234
+ views?.delete(hash);
235
+ if (views?.size === 0) this.#views.delete(clientID);
169
236
  });
170
- this.#views.set(hash, existing);
237
+ if (!byHash) {
238
+ byHash = /* @__PURE__ */ new Map();
239
+ this.#views.set(clientID, byHash);
240
+ }
241
+ byHash.set(hash, existing);
171
242
  } else existing.updateTTL(ttl);
172
243
  return existing;
173
244
  }
@@ -224,6 +295,7 @@ var ViewWrapper = class {
224
295
  }
225
296
  #onData = (snap, resultType, error) => {
226
297
  const data = snap;
298
+ const wasCached = this.#snapshot[1].type === "cached";
227
299
  this.#snapshot = getSnapshot(this.#singular, data, resultType, this.#retry, error);
228
300
  if (resultType === "complete" || resultType === "error") {
229
301
  this.#complete = true;
@@ -231,9 +303,13 @@ var ViewWrapper = class {
231
303
  this.#nonEmpty = true;
232
304
  this.#nonEmptyResolver.resolve();
233
305
  }
234
- if (this.#singular ? this.#snapshot[0] !== void 0 : this.#snapshot[0].length !== 0) {
306
+ const hasData = this.#singular ? this.#snapshot[0] !== void 0 : this.#snapshot[0].length !== 0;
307
+ if (resultType === "cached" || hasData) {
235
308
  this.#nonEmpty = true;
236
309
  this.#nonEmptyResolver.resolve();
310
+ } else if (wasCached && resultType === "unknown") {
311
+ this.#nonEmpty = false;
312
+ this.#nonEmptyResolver = resolver();
237
313
  }
238
314
  for (const internals of this.#reactInternals) internals();
239
315
  };
@@ -276,6 +352,7 @@ var ViewWrapper = class {
276
352
  };
277
353
  };
278
354
  updateTTL(ttl) {
355
+ if (this.#ttl === ttl) return;
279
356
  this.#ttl = ttl;
280
357
  this.#view?.updateTTL(ttl);
281
358
  }
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useSyncExternalStore} from 'react';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' (in which case results may be\n * empty). This is useful for suspending until there are partial\n * optimistic local results, or the query has completed loading from the\n * server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<ViewStore, Map<string, AnyViewWrapper>>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n return allViews.get(store)?.size ?? 0;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n #views = new Map<string, AnyViewWrapper>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const hash = qi.hash() + JSON.stringify(qi.format) + zero.clientID;\n let existing = this.#views.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const currentView = this.#views.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n this.#views.delete(hash);\n });\n this.#views.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n if (\n this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0\n ) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;AAwEA,IAAM,WAAY,MAAgD;AAClE,IAAM,UAAyC,WAC3C,YACA,MAAK;CACH,MAAM;AACR;AAsCJ,SAAgB,SAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CAAC,UAAU,MAAM,MAAM,kBAAkB;CAG5C,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,KAAA;CAI5D,OAAO,qBACL,MAAM,2BAA2B,oBACjC,MAAM,eACH,qBACH,MAAM,eACH,mBACL;AACF;AAsCA,SAAgB,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","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useRef, useSyncExternalStore} from 'react';\nimport {deepEqual} from '../../shared/src/json.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\ntype StableQueryCache = {\n zero: unknown;\n context: unknown;\n /** The last input, so an unchanged one is an identity compare and nothing else. */\n rawQuery: object;\n /** The `CustomQuery` a query request names; undefined for a plain query. */\n customQuery: unknown;\n args: ReadonlyJSONValue | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n q: Query<any, any, any>;\n};\n\n/**\n * Resolves a query request against the Zero context, reusing the previous\n * result while the request means the same thing.\n *\n * Interning already makes an unchanged *plain* query come back as the same\n * object, so this is aimed at the query-request form -- `queries.issue({id})`\n * -- where every render allocates a fresh request and `addContextToQuery`\n * re-runs the definition. That costs argument validation (a zod parse of\n * byte-identical args) plus a walk of the builder chain, neither of which\n * interning removes: it makes rebuilding the chain cheap and gives the same\n * object back, but only after the work has been done again.\n *\n * A request resolves to the previous query when it names the same\n * `CustomQuery`, the same context, and deep-equal args. Those are exactly the\n * inputs the definition is allowed to depend on: a named query is re-derived\n * on the server from its name and args, so it has to be a pure function of\n * them, or client and server would build different queries.\n *\n * The ref is written during render. That is safe here because it is a pure\n * cache: an entry is derived only from the inputs, so a StrictMode double\n * render or a discarded concurrent render leaves it valid either way.\n */\nfunction useStableQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema,\n TReturn,\n TContext extends BaseDefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n zero: Zero<TSchema, undefined, TContext>,\n): Query<TTable, TSchema, TReturn> | undefined {\n const cacheRef = useRef<StableQueryCache | undefined>(undefined);\n\n // Deliberately kept rather than cleared: a query toggled off and back on\n // reuses what it had.\n if (!query) {\n return undefined;\n }\n\n const cache = cacheRef.current;\n if (cache && cache.zero === zero) {\n if (cache.rawQuery === query) {\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n if (\n 'query' in query &&\n cache.customQuery === query.query &&\n cache.context === zero.context &&\n deepEqual(cache.args, query.args)\n ) {\n // Same meaning, new wrapper object: remember it so the next render is\n // the identity compare above.\n cache.rawQuery = query;\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n }\n\n const q = addContextToQuery(query, zero.context);\n const isRequest = 'query' in query;\n cacheRef.current = {\n zero: zero,\n context: zero.context,\n rawQuery: query,\n customQuery: isRequest ? query.query : undefined,\n args: isRequest ? query.args : undefined,\n q,\n };\n return q;\n}\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' or 'cached' (in which case\n * results may be empty: a server-confirmed empty answer, from this\n * connection or a previous one, is something to render). This is useful\n * for suspending until there are partial optimistic local results, or\n * the query has completed loading from the server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeCached = {type: 'cached'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularCached = [undefined, resultTypeCached] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralCached = [emptyArray, resultTypeCached] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotSingularCached as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotPluralCached as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n case 'cached':\n return [data, resultTypeCached];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<\n ViewStore,\n Map<string, Map<string, AnyViewWrapper>>\n>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n let size = 0;\n for (const byHash of allViews.get(store)?.values() ?? []) {\n size += byHash.size;\n }\n return size;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n /**\n * Client id, then query hash.\n *\n * Nested rather than keyed by the two joined together, because this is\n * looked up on every render of every `useQuery`. Joining them builds a\n * string that V8 has to hash from scratch, where both halves on their own\n * are strings it has already hashed and cached -- `hash()` is memoized on an\n * interned query, so the same string comes back each render. Measured over a\n * rebuild-and-look-up of one chain, that is the difference between 202ns and\n * 123ns; the join cost more than rebuilding and hashing the whole query.\n */\n #views = new Map<string, Map<string, AnyViewWrapper>>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const {clientID} = zero;\n const hash = qi.hash();\n let byHash = this.#views.get(clientID);\n let existing = byHash?.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const views = this.#views.get(clientID);\n const currentView = views?.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n views?.delete(hash);\n if (views?.size === 0) {\n // Nothing is left for this client, so drop its map rather than\n // keeping one per client id the page has ever seen.\n this.#views.delete(clientID);\n }\n });\n if (!byHash) {\n byHash = new Map();\n this.#views.set(clientID, byHash);\n }\n byHash.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n const wasCached = this.#snapshot[1].type === 'cached';\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n const hasData = this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0;\n // A 'cached' result is the server-confirmed answer from a previous\n // session, so even an empty one is something to render. It never\n // satisfies `complete`; only a confirmation on this connection does.\n if (resultType === 'cached' || hasData) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n } else if (wasCached && resultType === 'unknown') {\n // The cached claim was revoked (the got key was evicted before this\n // connection confirmed the query) and the view is empty: there is\n // nothing to render again until rows or a confirmation arrive.\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n // `getView` calls this on every render, and forwarding an unchanged TTL\n // reaches the query manager, which re-derives the query's id from its AST\n // to find the entry. Nothing downstream distinguishes a repeat, so skip\n // it. A change in how the same duration is spelled ('60s' vs 60000) is\n // still a change here and still propagates, as it did before.\n if (this.#ttl === ttl) {\n return;\n }\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty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AAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKZ,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EAMxB,IAAI,KAAKK,SAAS,KAChB;EAEF,KAAKA,OAAO;EACZ,KAAKQ,OAAO,UAAU,GAAG;CAC3B;CAEA,IAAI,WAAW;EACb,OAAO,KAAKJ;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;CAEA,IAAI,WAAW;EACb,OAAO,KAAKC;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;AACF"}
@@ -3,6 +3,7 @@ import { type Change, type Entry, type ErroredQuery, type Format, type Input, ty
3
3
  export type State = [Entry, QueryResultDetails];
4
4
  export declare const COMPLETE: QueryResultDetails;
5
5
  export declare const UNKNOWN: QueryResultDetails;
6
+ export declare const CACHED: QueryResultDetails;
6
7
  /**
7
8
  * SolidView bridges Zero's incremental view updates with Solid's reactive
8
9
  * store.
@@ -49,6 +50,22 @@ export declare class SolidView implements Output {
49
50
  #private;
50
51
  constructor(input: Input, onTransactionCommit: (cb: () => void) => void, format: Format, onDestroy: () => void, queryComplete: true | ErroredQuery | Promise<true>, updateTTL: (ttl: TTL) => void, setState: SetStoreFunction<State>, retry: () => void);
51
52
  destroy(): void;
53
+ /**
54
+ * The store holds the server-confirmed result of this query from a
55
+ * previous connection. Never downgrades 'complete'/'error'; freshness stays
56
+ * a promise only the connection can keep, so nothing that waits on
57
+ * 'complete' resolves here.
58
+ */
59
+ markCached(): void;
60
+ /** The got key was deleted (eviction) before this connection confirmed it. */
61
+ unmarkCached(): void;
62
+ /**
63
+ * Called before a deferred pipeline hydrates this view over several tasks
64
+ * (see `ViewFactory`). Rows already only reach the store at commit; this
65
+ * makes result type transitions wait for that commit too, including when
66
+ * the hydration produced no rows.
67
+ */
68
+ holdData(): void;
52
69
  push(change: Change): readonly never[];
53
70
  updateTTL(ttl: TTL): void;
54
71
  }
@@ -1 +1 @@
1
- {"version":3,"file":"solid-view.d.ts","sourceRoot":"","sources":["../../../../zero-solid/src/solid-view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,gBAAgB,EAAC,MAAM,gBAAgB,CAAC;AAUzE,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,MAAM,EACX,KAAK,KAAK,EAEV,KAAK,MAAM,EACX,KAAK,KAAK,EAEV,KAAK,kBAAkB,EACvB,KAAK,MAAM,EAEX,KAAK,GAAG,EACT,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,KAAK,GAAG,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AAEhD,eAAO,MAAM,QAAQ,EAAE,kBAAsD,CAAC;AAC9E,eAAO,MAAM,OAAO,EAAE,kBAAqD,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,qBAAa,SAAU,YAAW,MAAM;;gBAqBpC,KAAK,EAAE,KAAK,EACZ,mBAAmB,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,KAAK,IAAI,EAC7C,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,IAAI,EACrB,aAAa,EAAE,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,EAClD,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EAC7B,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,EAAE,MAAM,IAAI;IAiEnB,OAAO,IAAI,IAAI;IA0Bf,IAAI,CAAC,MAAM,EAAE,MAAM;IAyDnB,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI;CAG1B;AAsDD,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,gBAAgB,CAAC,KAAK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AY,GAAG,OAAO,CAAC,IAAI,CAAC,EAClD,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EAC7B,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,EAAE,MAAM,IAAI;IAmEnB,OAAO,IAAI,IAAI;IAIf;;;;;OAKG;IACH,UAAU,IAAI,IAAI;IAMlB,8EAA8E;IAC9E,YAAY,IAAI,IAAI;IAMpB;;;;;OAKG;IACH,QAAQ,IAAI,IAAI;IAiDhB,IAAI,CAAC,MAAM,EAAE,MAAM;IAyDnB,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI;CAG1B;AAsDD,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,EACjC,KAAK,CAAC,EAAE,MAAM,IAAI,IAGhB,MAAM,SAAS,MAAM,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,EAC/C,OAAO,SAAS,MAAM,EACtB,OAAO,UAEC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,SAChC,KAAK,UACJ,MAAM,aACH,MAAM,IAAI,uBACA,CAAC,EAAE,EAAE,MAAM,IAAI,KAAK,IAAI,iBAC9B,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,aACvC,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,eAiBhC"}
@@ -7,6 +7,7 @@ import { produce, reconcile } from "solid-js/store";
7
7
  //#region ../zero-solid/src/solid-view.ts
8
8
  var COMPLETE = Object.freeze({ type: "complete" });
9
9
  var UNKNOWN = Object.freeze({ type: "unknown" });
10
+ var CACHED = Object.freeze({ type: "cached" });
10
11
  /**
11
12
  * SolidView bridges Zero's incremental view updates with Solid's reactive
12
13
  * store.
@@ -57,6 +58,8 @@ var SolidView = class {
57
58
  #setState;
58
59
  #builderRoot;
59
60
  #pendingChanges = [];
61
+ #pendingResultType;
62
+ #held = false;
60
63
  #updateTTL;
61
64
  constructor(input, onTransactionCommit, format, onDestroy, queryComplete, updateTTL, setState, retry) {
62
65
  this.#input = input;
@@ -77,7 +80,7 @@ var SolidView = class {
77
80
  if (queryComplete !== true && !("error" in queryComplete)) queryComplete.then(() => {
78
81
  this.#setState((prev) => [prev[0], COMPLETE]);
79
82
  }).catch((error) => {
80
- this.#setState((prev) => [prev[0], this.#makeError(error)]);
83
+ this.#transitionResultType((prev) => [prev[0], this.#makeError(error)]);
81
84
  });
82
85
  }
83
86
  #makeError(error) {
@@ -96,7 +99,37 @@ var SolidView = class {
96
99
  destroy() {
97
100
  this.#onDestroy();
98
101
  }
102
+ /**
103
+ * The store holds the server-confirmed result of this query from a
104
+ * previous connection. Never downgrades 'complete'/'error'; freshness stays
105
+ * a promise only the connection can keep, so nothing that waits on
106
+ * 'complete' resolves here.
107
+ */
108
+ markCached() {
109
+ this.#transitionResultType((prev) => prev[1].type === "unknown" ? [prev[0], CACHED] : prev);
110
+ }
111
+ /** The got key was deleted (eviction) before this connection confirmed it. */
112
+ unmarkCached() {
113
+ this.#transitionResultType((prev) => prev[1].type === "cached" ? [prev[0], UNKNOWN] : prev);
114
+ }
115
+ /**
116
+ * Called before a deferred pipeline hydrates this view over several tasks
117
+ * (see `ViewFactory`). Rows already only reach the store at commit; this
118
+ * makes result type transitions wait for that commit too, including when
119
+ * the hydration produced no rows.
120
+ */
121
+ holdData() {
122
+ this.#held = true;
123
+ }
124
+ #transitionResultType(transition) {
125
+ if (this.#held || this.#hasUncommittedChanges()) this.#pendingResultType = transition;
126
+ else this.#setState(transition);
127
+ }
128
+ #hasUncommittedChanges() {
129
+ return this.#builderRoot !== void 0 && !isEmptyRoot(this.#builderRoot) || this.#pendingChanges.length > 0;
130
+ }
99
131
  #onTransactionCommit = () => {
132
+ this.#held = false;
100
133
  const builderRoot = this.#builderRoot;
101
134
  if (builderRoot) {
102
135
  if (!isEmptyRoot(builderRoot)) {
@@ -108,6 +141,11 @@ var SolidView = class {
108
141
  } finally {
109
142
  this.#pendingChanges = [];
110
143
  }
144
+ const pendingResultType = this.#pendingResultType;
145
+ if (pendingResultType) {
146
+ this.#pendingResultType = void 0;
147
+ this.#setState(pendingResultType);
148
+ }
111
149
  };
112
150
  push(change) {
113
151
  if (this.#builderRoot) this.#applyChangeToRoot(materializeRelationships(change), this.#builderRoot);
@@ -1 +1 @@
1
- {"version":3,"file":"solid-view.js","names":["#input","#format","#onDestroy","#retry","#updateTTL","#onTransactionCommit","#createEmptyRoot","#applyChangesToRoot","#setState","#makeError","#builderRoot","#applyChanges","#pendingChanges","#applyChangeToRoot"],"sources":["../../../../zero-solid/src/solid-view.ts"],"sourcesContent":["import {produce, reconcile, type SetStoreFunction} from 'solid-js/store';\nimport {emptyArray} from '../../shared/src/sentinels.ts';\nimport {ChangeIndex} from '../../zql/src/ivm/change-index.ts';\nimport {ChangeType} from '../../zql/src/ivm/change-type.ts';\nimport {\n applyChange,\n idSymbol,\n skipYields,\n type ViewChange,\n} from './bindings.ts';\nimport {\n type AnyViewFactory,\n type Change,\n type Entry,\n type ErroredQuery,\n type Format,\n type Input,\n type Node,\n type Output,\n type Query,\n type QueryErrorDetails,\n type QueryResultDetails,\n type Schema,\n type Stream,\n type TTL,\n} from './zero.ts';\n\nexport type State = [Entry, QueryResultDetails];\n\nexport const COMPLETE: QueryResultDetails = Object.freeze({type: 'complete'});\nexport const UNKNOWN: QueryResultDetails = Object.freeze({type: 'unknown'});\n\n/**\n * SolidView bridges Zero's incremental view updates with Solid's reactive\n * store.\n *\n * The challenge: Zero pushes individual row changes (add/remove/edit) as they\n * arrive, but updating Solid's store on each push is expensive. We batch\n * changes until transaction commit, then apply them all at once.\n *\n * Two code paths optimize for different scenarios:\n *\n * 1. BULK INSERT (builderRoot path): When building from empty, we skip\n * Solid's reactive tracking entirely and build a plain JS object. This is\n * 5x faster for large initial loads. Uses reconcile() to diff the final\n * result into Solid.\n *\n * 2. INCREMENTAL UPDATE (#pendingChanges path): For existing views, we queue\n * changes and apply them in-place within a produce() draft. produce()\n * creates a mutable draft, applyChange mutates it directly, then produce()\n * handles diffing and reactivity.\n *\n *\n * push(change)\n * │\n * ▼\n * ┌─────────────────────────────────┐\n * │ builderRoot defined? │\n * │ (building from empty) │\n * └─────────────────────────────────┘\n * │yes │no\n * ▼ ▼\n * Build plain JS Queue in\n * object (fast) #pendingChanges\n * │ │\n * └───────┬───────────┘\n * ▼\n * onTransactionCommit()\n * │\n * ┌───────┴──────────┐\n * │ │\n * builderRoot produce(draft =>\n * → reconcile() applyChange(draft, ..., mutate: true))\n */\nexport class SolidView implements Output {\n readonly #input: Input;\n readonly #format: Format;\n readonly #onDestroy: () => void;\n readonly #retry: () => void;\n\n #setState: SetStoreFunction<State>;\n\n // Optimization: if the store is currently empty we build up\n // the view on a plain old JS object stored at #builderRoot, and return\n // that for the new state on transaction commit. This avoids building up\n // large views from scratch via solid produce. The proxy object used by\n // solid produce is slow and in this case we don't care about solid tracking\n // the fine grained changes (everything has changed, it's all new). For a\n // test case with a view with 3000 rows, each row having 2 children, this\n // optimization reduced #applyChanges time from 743ms to 133ms.\n #builderRoot: Entry | undefined;\n #pendingChanges: ViewChange[] = [];\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n onTransactionCommit: (cb: () => void) => void,\n format: Format,\n onDestroy: () => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n setState: SetStoreFunction<State>,\n retry: () => void,\n ) {\n this.#input = input;\n onTransactionCommit(this.#onTransactionCommit);\n this.#format = format;\n this.#onDestroy = onDestroy;\n this.#updateTTL = updateTTL;\n this.#retry = retry;\n\n input.setOutput(this);\n\n const initialRoot = this.#createEmptyRoot();\n this.#applyChangesToRoot(\n skipYields(input.fetch({})),\n node => ({type: 'add', node}),\n initialRoot,\n );\n\n this.#setState = setState;\n this.#setState(\n reconcile(\n [\n initialRoot,\n queryComplete === true\n ? COMPLETE\n : 'error' in queryComplete\n ? this.#makeError(queryComplete)\n : UNKNOWN,\n ],\n {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n },\n ),\n );\n\n if (isEmptyRoot(initialRoot)) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n\n if (queryComplete !== true && !('error' in queryComplete)) {\n void queryComplete\n .then(() => {\n this.#setState(prev => [prev[0], COMPLETE]);\n })\n .catch((error: ErroredQuery) => {\n this.#setState(prev => [prev[0], this.#makeError(error)]);\n });\n }\n }\n\n #makeError(error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry: this.#retry,\n refetch: this.#retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n }\n\n destroy(): void {\n this.#onDestroy();\n }\n\n #onTransactionCommit = () => {\n const builderRoot = this.#builderRoot;\n if (builderRoot) {\n if (!isEmptyRoot(builderRoot)) {\n this.#setState(\n 0,\n reconcile(builderRoot, {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n }),\n );\n this.#builderRoot = undefined;\n }\n } else {\n try {\n this.#applyChanges(this.#pendingChanges, c => c);\n } finally {\n this.#pendingChanges = [];\n }\n }\n };\n\n push(change: Change) {\n // Delay updating the solid store state until the transaction commit\n // (because each update of the solid store is quite expensive). If\n // this.#builderRoot is defined apply the changes to it (we are building\n // from an empty root), otherwise queue the changes to be applied\n // using produce at the end of the transaction but read the relationships\n // now as they are only valid to read when the push is received.\n if (this.#builderRoot) {\n this.#applyChangeToRoot(\n materializeRelationships(change),\n this.#builderRoot,\n );\n } else {\n this.#pendingChanges.push(materializeRelationships(change));\n }\n return emptyArray;\n }\n\n #applyChanges<T>(changes: Iterable<T>, mapper: (v: T) => ViewChange): void {\n this.#setState(\n produce((draftState: State) => {\n this.#applyChangesToRoot<T>(changes, mapper, draftState[0]);\n if (isEmptyRoot(draftState[0])) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n }),\n );\n }\n\n #applyChangesToRoot<T>(\n changes: Iterable<T>,\n mapper: (v: T) => ViewChange,\n root: Entry,\n ) {\n for (const change of changes) {\n this.#applyChangeToRoot(mapper(change), root);\n }\n }\n\n #applyChangeToRoot(change: ViewChange, root: Entry) {\n applyChange(\n root,\n change,\n this.#input.getSchema(),\n '',\n this.#format,\n true /* withIDs */,\n true /* mutate */,\n );\n }\n\n #createEmptyRoot(): Entry {\n return {\n '': this.#format.singular ? undefined : [],\n };\n }\n\n updateTTL(ttl: TTL): void {\n this.#updateTTL(ttl);\n }\n}\n\nfunction materializeRelationships(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {\n type: 'add',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.REMOVE:\n return {\n type: 'remove',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: {row: change[ChangeIndex.NODE].row},\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: materializeRelationships(\n change[ChangeIndex.CHILD_DATA].change,\n ),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: {row: change[ChangeIndex.NODE].row},\n oldNode: {row: change[ChangeIndex.OLD_NODE].row},\n };\n }\n}\n\nfunction materializeNodeRelationships(node: Node): Node {\n const relationships: Record<string, () => Stream<Node>> = {};\n for (const relationship in node.relationships) {\n const materialized: Node[] = [];\n for (const n of skipYields(node.relationships[relationship]())) {\n materialized.push(materializeNodeRelationships(n));\n }\n relationships[relationship] = () => materialized;\n }\n return {\n row: node.row,\n relationships,\n };\n}\n\nfunction isEmptyRoot(entry: Entry) {\n const data = entry[''];\n return data === undefined || (Array.isArray(data) && data.length === 0);\n}\n\nexport function createSolidViewFactory(\n setState: SetStoreFunction<State>,\n retry?: () => void,\n) {\n function solidViewFactory<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n _query: Query<TTable, TSchema, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n return new SolidView(\n input,\n onTransactionCommit,\n format,\n onDestroy,\n queryComplete,\n updateTTL,\n setState,\n retry || (() => {}),\n );\n }\n\n solidViewFactory satisfies AnyViewFactory;\n\n return solidViewFactory;\n}\n"],"mappings":";;;;;;;AA6BA,IAAa,WAA+B,OAAO,OAAO,EAAC,MAAM,WAAU,CAAC;AAC5E,IAAa,UAA8B,OAAO,OAAO,EAAC,MAAM,UAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4C1E,IAAa,YAAb,MAAyC;CACvC;CACA;CACA;CACA;CAEA;CAUA;CACA,kBAAgC,CAAC;CACjC;CAEA,YACE,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,OACA;EACA,KAAKA,SAAS;EACd,oBAAoB,KAAKK,oBAAoB;EAC7C,KAAKJ,UAAU;EACf,KAAKC,aAAa;EAClB,KAAKE,aAAa;EAClB,KAAKD,SAAS;EAEd,MAAM,UAAU,IAAI;EAEpB,MAAM,cAAc,KAAKG,iBAAiB;EAC1C,KAAKC,oBACH,WAAW,MAAM,MAAM,CAAC,CAAC,CAAC,IAC1B,UAAS;GAAC,MAAM;GAAO;EAAI,IAC3B,WACF;EAEA,KAAKC,YAAY;EACjB,KAAKA,UACH,UACE,CACE,aACA,kBAAkB,OACd,WACA,WAAW,gBACT,KAAKC,WAAW,aAAa,IAC7B,OACR,GACA,EAEE,KAAK,SACP,CACF,CACF;EAEA,IAAI,YAAY,WAAW,GACzB,KAAKC,eAAe,KAAKJ,iBAAiB;EAG5C,IAAI,kBAAkB,QAAQ,EAAE,WAAW,gBACzC,cACG,WAAW;GACV,KAAKE,WAAU,SAAQ,CAAC,KAAK,IAAI,QAAQ,CAAC;EAC5C,CAAC,EACA,OAAO,UAAwB;GAC9B,KAAKA,WAAU,SAAQ,CAAC,K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IAAY,CAAC,EAC3C;CACF;CAEA,UAAU,KAAgB;EACxB,KAAKG,WAAW,GAAG;CACrB;AACF;AAEA,SAAS,yBAAyB,QAA4B;CAC5D,QAAQ,OAAO,IAAf;EACE,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,6BAA6B,OAAO,EAAiB;EAC7D;EACF,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,6BAA6B,OAAO,EAAiB;EAC7D;EACF,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,EAAC,KAAK,OAAO,GAAkB,IAAG;GACxC,OAAO;IACL,kBAAkB,OAAO,GAAwB;IACjD,QAAQ,yBACN,OAAO,GAAwB,MACjC;GACF;EACF;EACF,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,EAAC,KAAK,OAAO,GAAkB,IAAG;GACxC,SAAS,EAAC,KAAK,OAAO,GAAsB,IAAG;EACjD;CACJ;AACF;AAEA,SAAS,6BAA6B,MAAkB;CACtD,MAAM,gBAAoD,CAAC;CAC3D,KAAK,MAAM,gBAAgB,KAAK,eAAe;EAC7C,MAAM,eAAuB,CAAC;EAC9B,KAAK,MAAM,KAAK,WAAW,KAAK,cAAc,cAAc,CAAC,GAC3D,aAAa,KAAK,6BAA6B,CAAC,CAAC;EAEnD,cAAc,sBAAsB;CACtC;CACA,OAAO;EACL,KAAK,KAAK;EACV;CACF;AACF;AAEA,SAAS,YAAY,OAAc;CACjC,MAAM,OAAO,MAAM;CACnB,OAAO,SAAS,KAAA,KAAc,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW;AACvE;AAEA,SAAgB,uBACd,UACA,OACA;CACA,SAAS,iBAKP,QACA,OACA,QACA,WACA,qBACA,eACA,WACA;EACA,OAAO,IAAI,UACT,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,gBAAgB,CAAC,EACnB;CACF;CAIA,OAAO;AACT"}
1
+ {"version":3,"file":"solid-view.js","names":["#input","#format","#onDestroy","#retry","#updateTTL","#onTransactionCommit","#createEmptyRoot","#applyChangesToRoot","#setState","#makeError","#builderRoot","#transitionResultType","#held","#hasUncommittedChanges","#pendingResultType","#pendingChanges","#applyChanges","#applyChangeToRoot"],"sources":["../../../../zero-solid/src/solid-view.ts"],"sourcesContent":["import {produce, reconcile, type SetStoreFunction} from 'solid-js/store';\nimport {emptyArray} from '../../shared/src/sentinels.ts';\nimport {ChangeIndex} from '../../zql/src/ivm/change-index.ts';\nimport {ChangeType} from '../../zql/src/ivm/change-type.ts';\nimport {\n applyChange,\n idSymbol,\n skipYields,\n type ViewChange,\n} from './bindings.ts';\nimport {\n type AnyViewFactory,\n type Change,\n type Entry,\n type ErroredQuery,\n type Format,\n type Input,\n type Node,\n type Output,\n type Query,\n type QueryErrorDetails,\n type QueryResultDetails,\n type Schema,\n type Stream,\n type TTL,\n} from './zero.ts';\n\nexport type State = [Entry, QueryResultDetails];\n\nexport const COMPLETE: QueryResultDetails = Object.freeze({type: 'complete'});\nexport const UNKNOWN: QueryResultDetails = Object.freeze({type: 'unknown'});\nexport const CACHED: QueryResultDetails = Object.freeze({type: 'cached'});\n\n/**\n * SolidView bridges Zero's incremental view updates with Solid's reactive\n * store.\n *\n * The challenge: Zero pushes individual row changes (add/remove/edit) as they\n * arrive, but updating Solid's store on each push is expensive. We batch\n * changes until transaction commit, then apply them all at once.\n *\n * Two code paths optimize for different scenarios:\n *\n * 1. BULK INSERT (builderRoot path): When building from empty, we skip\n * Solid's reactive tracking entirely and build a plain JS object. This is\n * 5x faster for large initial loads. Uses reconcile() to diff the final\n * result into Solid.\n *\n * 2. INCREMENTAL UPDATE (#pendingChanges path): For existing views, we queue\n * changes and apply them in-place within a produce() draft. produce()\n * creates a mutable draft, applyChange mutates it directly, then produce()\n * handles diffing and reactivity.\n *\n *\n * push(change)\n * │\n * ▼\n * ┌─────────────────────────────────┐\n * │ builderRoot defined? │\n * │ (building from empty) │\n * └─────────────────────────────────┘\n * │yes │no\n * ▼ ▼\n * Build plain JS Queue in\n * object (fast) #pendingChanges\n * │ │\n * └───────┬───────────┘\n * ▼\n * onTransactionCommit()\n * │\n * ┌───────┴──────────┐\n * │ │\n * builderRoot produce(draft =>\n * → reconcile() applyChange(draft, ..., mutate: true))\n */\nexport class SolidView implements Output {\n readonly #input: Input;\n readonly #format: Format;\n readonly #onDestroy: () => void;\n readonly #retry: () => void;\n\n #setState: SetStoreFunction<State>;\n\n // Optimization: if the store is currently empty we build up\n // the view on a plain old JS object stored at #builderRoot, and return\n // that for the new state on transaction commit. This avoids building up\n // large views from scratch via solid produce. The proxy object used by\n // solid produce is slow and in this case we don't care about solid tracking\n // the fine grained changes (everything has changed, it's all new). For a\n // test case with a view with 3000 rows, each row having 2 children, this\n // optimization reduced #applyChanges time from 743ms to 133ms.\n #builderRoot: Entry | undefined;\n #pendingChanges: ViewChange[] = [];\n // A result type transition requested while row changes are waiting for the\n // next commit. It is applied with them, so a cached claim never reaches the\n // store before the rows it is about.\n #pendingResultType: ((prev: State) => State) | undefined;\n #held = false;\n readonly #updateTTL: (ttl: TTL) => void;\n\n constructor(\n input: Input,\n onTransactionCommit: (cb: () => void) => void,\n format: Format,\n onDestroy: () => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n setState: SetStoreFunction<State>,\n retry: () => void,\n ) {\n this.#input = input;\n onTransactionCommit(this.#onTransactionCommit);\n this.#format = format;\n this.#onDestroy = onDestroy;\n this.#updateTTL = updateTTL;\n this.#retry = retry;\n\n input.setOutput(this);\n\n const initialRoot = this.#createEmptyRoot();\n this.#applyChangesToRoot(\n skipYields(input.fetch({})),\n node => ({type: 'add', node}),\n initialRoot,\n );\n\n this.#setState = setState;\n this.#setState(\n reconcile(\n [\n initialRoot,\n queryComplete === true\n ? COMPLETE\n : 'error' in queryComplete\n ? this.#makeError(queryComplete)\n : UNKNOWN,\n ],\n {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n },\n ),\n );\n\n if (isEmptyRoot(initialRoot)) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n\n if (queryComplete !== true && !('error' in queryComplete)) {\n void queryComplete\n .then(() => {\n this.#setState(prev => [prev[0], COMPLETE]);\n })\n .catch((error: ErroredQuery) => {\n // Through the pending path: a deferred attach that fails is\n // published with the commit of its batch, not during it.\n this.#transitionResultType(prev => [prev[0], this.#makeError(error)]);\n });\n }\n }\n\n #makeError(error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry: this.#retry,\n refetch: this.#retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n }\n\n destroy(): void {\n this.#onDestroy();\n }\n\n /**\n * The store holds the server-confirmed result of this query from a\n * previous connection. Never downgrades 'complete'/'error'; freshness stays\n * a promise only the connection can keep, so nothing that waits on\n * 'complete' resolves here.\n */\n markCached(): void {\n this.#transitionResultType(prev =>\n prev[1].type === 'unknown' ? [prev[0], CACHED] : prev,\n );\n }\n\n /** The got key was deleted (eviction) before this connection confirmed it. */\n unmarkCached(): void {\n this.#transitionResultType(prev =>\n prev[1].type === 'cached' ? [prev[0], UNKNOWN] : prev,\n );\n }\n\n /**\n * Called before a deferred pipeline hydrates this view over several tasks\n * (see `ViewFactory`). Rows already only reach the store at commit; this\n * makes result type transitions wait for that commit too, including when\n * the hydration produced no rows.\n */\n holdData(): void {\n this.#held = true;\n }\n\n #transitionResultType(transition: (prev: State) => State): void {\n if (this.#held || this.#hasUncommittedChanges()) {\n // The last requested transition wins; each is a no-op unless the state\n // it expects is current, so the net effect at commit is correct.\n this.#pendingResultType = transition;\n } else {\n this.#setState(transition);\n }\n }\n\n #hasUncommittedChanges(): boolean {\n return (\n (this.#builderRoot !== undefined && !isEmptyRoot(this.#builderRoot)) ||\n this.#pendingChanges.length > 0\n );\n }\n\n #onTransactionCommit = () => {\n this.#held = false;\n const builderRoot = this.#builderRoot;\n if (builderRoot) {\n if (!isEmptyRoot(builderRoot)) {\n this.#setState(\n 0,\n reconcile(builderRoot, {\n // solidjs's types want a string, but a symbol works\n key: idSymbol as unknown as string,\n }),\n );\n this.#builderRoot = undefined;\n }\n } else {\n try {\n this.#applyChanges(this.#pendingChanges, c => c);\n } finally {\n this.#pendingChanges = [];\n }\n }\n const pendingResultType = this.#pendingResultType;\n if (pendingResultType) {\n this.#pendingResultType = undefined;\n this.#setState(pendingResultType);\n }\n };\n\n push(change: Change) {\n // Delay updating the solid store state until the transaction commit\n // (because each update of the solid store is quite expensive). If\n // this.#builderRoot is defined apply the changes to it (we are building\n // from an empty root), otherwise queue the changes to be applied\n // using produce at the end of the transaction but read the relationships\n // now as they are only valid to read when the push is received.\n if (this.#builderRoot) {\n this.#applyChangeToRoot(\n materializeRelationships(change),\n this.#builderRoot,\n );\n } else {\n this.#pendingChanges.push(materializeRelationships(change));\n }\n return emptyArray;\n }\n\n #applyChanges<T>(changes: Iterable<T>, mapper: (v: T) => ViewChange): void {\n this.#setState(\n produce((draftState: State) => {\n this.#applyChangesToRoot<T>(changes, mapper, draftState[0]);\n if (isEmptyRoot(draftState[0])) {\n this.#builderRoot = this.#createEmptyRoot();\n }\n }),\n );\n }\n\n #applyChangesToRoot<T>(\n changes: Iterable<T>,\n mapper: (v: T) => ViewChange,\n root: Entry,\n ) {\n for (const change of changes) {\n this.#applyChangeToRoot(mapper(change), root);\n }\n }\n\n #applyChangeToRoot(change: ViewChange, root: Entry) {\n applyChange(\n root,\n change,\n this.#input.getSchema(),\n '',\n this.#format,\n true /* withIDs */,\n true /* mutate */,\n );\n }\n\n #createEmptyRoot(): Entry {\n return {\n '': this.#format.singular ? undefined : [],\n };\n }\n\n updateTTL(ttl: TTL): void {\n this.#updateTTL(ttl);\n }\n}\n\nfunction materializeRelationships(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {\n type: 'add',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.REMOVE:\n return {\n type: 'remove',\n node: materializeNodeRelationships(change[ChangeIndex.NODE]),\n };\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: {row: change[ChangeIndex.NODE].row},\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: materializeRelationships(\n change[ChangeIndex.CHILD_DATA].change,\n ),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: {row: change[ChangeIndex.NODE].row},\n oldNode: {row: change[ChangeIndex.OLD_NODE].row},\n };\n }\n}\n\nfunction materializeNodeRelationships(node: Node): Node {\n const relationships: Record<string, () => Stream<Node>> = {};\n for (const relationship in node.relationships) {\n const materialized: Node[] = [];\n for (const n of skipYields(node.relationships[relationship]())) {\n materialized.push(materializeNodeRelationships(n));\n }\n relationships[relationship] = () => materialized;\n }\n return {\n row: node.row,\n relationships,\n };\n}\n\nfunction isEmptyRoot(entry: Entry) {\n const data = entry[''];\n return data === undefined || (Array.isArray(data) && data.length === 0);\n}\n\nexport function createSolidViewFactory(\n setState: SetStoreFunction<State>,\n retry?: () => void,\n) {\n function solidViewFactory<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n _query: Query<TTable, TSchema, TReturn>,\n input: Input,\n format: Format,\n onDestroy: () => void,\n onTransactionCommit: (cb: () => void) => void,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n return new SolidView(\n input,\n onTransactionCommit,\n format,\n onDestroy,\n queryComplete,\n updateTTL,\n setState,\n retry || (() => {}),\n );\n }\n\n solidViewFactory satisfies AnyViewFactory;\n\n return solidViewFactory;\n}\n"],"mappings":";;;;;;;AA6BA,IAAa,WAA+B,OAAO,OAAO,EAAC,MAAM,WAAU,CAAC;AAC5E,IAAa,UAA8B,OAAO,OAAO,EAAC,MAAM,UAAS,CAAC;AAC1E,IAAa,SAA6B,OAAO,OAAO,EAAC,MAAM,SAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4Cx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SAAS,iBAKP,QACA,OACA,QACA,WACA,qBACA,eACA,WACA;EACA,OAAO,IAAI,UACT,OACA,qBACA,QACA,WACA,eACA,WACA,UACA,gBAAgB,CAAC,EACnB;CACF;CAIA,OAAO;AACT"}
@@ -31,9 +31,11 @@ function useQuery(querySignal, options) {
31
31
  if (!query) return void 0;
32
32
  return asQueryInternals(query);
33
33
  });
34
- const hash = createMemo(() => qi()?.hash() + JSON.stringify(qi()?.format ?? null) + zero().clientID);
34
+ const hash = createMemo(() => {
35
+ const internals = qi();
36
+ return internals === void 0 ? void 0 : internals.hash() + zero().clientID;
37
+ });
35
38
  const ttl = createMemo(() => normalize(options)?.ttl ?? 3e5);
36
- const initialTTL = ttl();
37
39
  const view = createMemo(() => {
38
40
  const currentHash = hash();
39
41
  refetchKey();
@@ -46,7 +48,7 @@ function useQuery(querySignal, options) {
46
48
  setState([{ "": void 0 }, UNKNOWN]);
47
49
  return;
48
50
  }
49
- const v = zero().materialize(untrackedQuery, createSolidViewFactory(setState, refetch), { ttl: initialTTL });
51
+ const v = zero().materialize(untrackedQuery, createSolidViewFactory(setState, refetch), { ttl: untrack(ttl) });
50
52
  onCleanup(() => v.destroy());
51
53
  return v;
52
54
  });
@@ -1 +1 @@
1
- {"version":3,"file":"use-query.js","names":[],"sources":["../../../../zero-solid/src/use-query.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n on,\n onCleanup,\n untrack,\n type Accessor,\n} from 'solid-js';\nimport {createStore} from 'solid-js/store';\nimport {\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {createSolidViewFactory, UNKNOWN, type State} from './solid-view.ts';\nimport {useZero} from './use-zero.ts';\nimport {\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type DefaultContext,\n type DefaultSchema,\n type Falsy,\n type HumanReadable,\n type PullRow,\n type QueryOrQueryRequest,\n type QueryResultDetails,\n type ReadonlyJSONValue,\n type TTL,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn>>,\n Accessor<QueryResultDetails & {}>,\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn> | undefined>,\n Accessor<QueryResultDetails & {}>,\n];\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode UseQueryOptions} instead.\n */\nexport type CreateQueryOptions = {\n ttl?: TTL | undefined;\n};\n\nexport type UseQueryOptions = {\n ttl?: TTL | undefined;\n};\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode useQuery} instead.\n */\nexport function createQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: CreateQueryOptions | Accessor<CreateQueryOptions>,\n): QueryResult<TReturn> {\n return useQuery(querySignal, options);\n}\n\n// Overload 1: Query - returns QueryResult<TReturn>\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n const [state, setState] = createStore<State>([\n {\n '': undefined,\n },\n UNKNOWN,\n ]);\n const initialRefetchKey = 0;\n const [refetchKey, setRefetchKey] = createSignal(initialRefetchKey);\n\n const refetch = () => {\n setRefetchKey(k => k + 1);\n };\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // Handle possibly falsy queries\n const q = createMemo(() => {\n const query = querySignal();\n if (!query) return undefined;\n return addContextToQuery(query, zero().context);\n });\n\n const qi = createMemo(() => {\n const query = q();\n if (!query) return undefined;\n return asQueryInternals(query);\n });\n\n const hash = createMemo(\n () => qi()?.hash() + JSON.stringify(qi()?.format ?? null) + zero().clientID,\n );\n const ttl = createMemo(() => normalize(options)?.ttl ?? DEFAULT_TTL_MS);\n\n const initialTTL = ttl();\n\n const view = createMemo(() => {\n // Depend on hash instead of query to avoid recreating the view when the\n // query object changes but the hash is the same.\n const currentHash = hash();\n refetchKey();\n\n // If query is falsy, don't create a view and reset state to undefined\n if (currentHash === undefined) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const untrackedQuery = untrack(q);\n if (!untrackedQuery) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const v = zero().materialize(\n untrackedQuery,\n createSolidViewFactory(setState, refetch),\n {\n ttl: initialTTL,\n },\n );\n\n onCleanup(() => v.destroy());\n\n return v;\n });\n\n // Update TTL on existing view when it changes.\n createEffect(\n on(\n ttl,\n currentTTL => {\n view()?.updateTTL(currentTTL);\n },\n {defer: true},\n ),\n );\n\n return [() => state[0][''] as HumanReadable<TReturn>, () => state[1]];\n}\n\nfunction normalize<T>(options?: T | Accessor<T | undefined>): T | undefined {\n return typeof options === 'function' ? (options as Accessor<T>)() : options;\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,SAAgB,YAQd,aAGA,SACsB;CACtB,OAAO,SAAS,aAAa,OAAO;AACtC;AAkCA,SAAgB,SAQd,aAIA,SACkD;CAClD,MAAM,CAAC,OAAO,YAAY,YAAmB,CAC3C,EACE,IAAI,KAAA,EACN,GACA,OACF,CAAC;CAED,MAAM,CAAC,YAAY,iBAAiB,aAAa,CAAiB;CAElE,MAAM,gBAAgB;EACpB,eAAc,MAAK,IAAI,CAAC;CAC1B;CAEA,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,iBAAiB;EACzB,MAAM,QAAQ,YAAY;EAC1B,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,kBAAkB,OAAO,KAAK,EAAE,OAAO;CAChD,CAAC;CAED,MAAM,KAAK,iBAAiB;EAC1B,MAAM,QAAQ,EAAE;EAChB,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,iBAAiB,KAAK;CAC/B,CAAC;CAED,MAAM,OAAO,iBACL,GAAG,GAAG,KAAK,IAAI,KAAK,UAAU,GAAG,GAAG,UAAU,IAAI,IAAI,KAAK,EAAE,QACrE;CACA,MAAM,MAAM,iBAAiB,UAAU,OAAO,GAAG,OAAA,GAAqB;CAEtE,MAAM,aAAa,IAAI;CAEvB,MAAM,OAAO,iBAAiB;EAG5B,MAAM,cAAc,KAAK;EACzB,WAAW;EAGX,IAAI,gBAAgB,KAAA,GAAW;GAC7B,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,iBAAiB,QAAQ,CAAC;EAChC,IAAI,CAAC,gBAAgB;GACnB,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,IAAI,KAAK,EAAE,YACf,gBACA,uBAAuB,UAAU,OAAO,GACxC,EACE,KAAK,WACP,CACF;EAEA,gBAAgB,EAAE,QAAQ,CAAC;EAE3B,OAAO;CACT,CAAC;CAGD,aACE,GACE,MACA,eAAc;EACZ,KAAK,GAAG,UAAU,UAAU;CAC9B,GACA,EAAC,OAAO,KAAI,CACd,CACF;CAEA,OAAO,OAAO,MAAM,GAAG,WAAqC,MAAM,EAAE;AACtE;AAEA,SAAS,UAAa,SAAsD;CAC1E,OAAO,OAAO,YAAY,aAAc,QAAwB,IAAI;AACtE"}
1
+ {"version":3,"file":"use-query.js","names":[],"sources":["../../../../zero-solid/src/use-query.ts"],"sourcesContent":["import {\n createEffect,\n createMemo,\n createSignal,\n on,\n onCleanup,\n untrack,\n type Accessor,\n} from 'solid-js';\nimport {createStore} from 'solid-js/store';\nimport {\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {createSolidViewFactory, UNKNOWN, type State} from './solid-view.ts';\nimport {useZero} from './use-zero.ts';\nimport {\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type DefaultContext,\n type DefaultSchema,\n type Falsy,\n type HumanReadable,\n type PullRow,\n type QueryOrQueryRequest,\n type QueryResultDetails,\n type ReadonlyJSONValue,\n type TTL,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn>>,\n Accessor<QueryResultDetails & {}>,\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n Accessor<HumanReadable<TReturn> | undefined>,\n Accessor<QueryResultDetails & {}>,\n];\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode UseQueryOptions} instead.\n */\nexport type CreateQueryOptions = {\n ttl?: TTL | undefined;\n};\n\nexport type UseQueryOptions = {\n ttl?: TTL | undefined;\n};\n\n// Deprecated in 0.22\n/**\n * @deprecated Use {@linkcode useQuery} instead.\n */\nexport function createQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: CreateQueryOptions | Accessor<CreateQueryOptions>,\n): QueryResult<TReturn> {\n return useQuery(querySignal, options);\n}\n\n// Overload 1: Query - returns QueryResult<TReturn>\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n querySignal: Accessor<\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy\n >,\n options?: UseQueryOptions | Accessor<UseQueryOptions>,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n const [state, setState] = createStore<State>([\n {\n '': undefined,\n },\n UNKNOWN,\n ]);\n const initialRefetchKey = 0;\n const [refetchKey, setRefetchKey] = createSignal(initialRefetchKey);\n\n const refetch = () => {\n setRefetchKey(k => k + 1);\n };\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // Handle possibly falsy queries\n const q = createMemo(() => {\n const query = querySignal();\n if (!query) return undefined;\n return addContextToQuery(query, zero().context);\n });\n\n const qi = createMemo(() => {\n const query = q();\n if (!query) return undefined;\n return asQueryInternals(query);\n });\n\n // Undefined rather than the string `undefined` + the client id: this feeds\n // the guard below, and concatenating a missing hash produced a string that\n // was never equal to undefined, leaving that guard unreachable.\n const hash = createMemo(() => {\n const internals = qi();\n return internals === undefined\n ? undefined\n : internals.hash() + zero().clientID;\n });\n const ttl = createMemo(() => normalize(options)?.ttl ?? DEFAULT_TTL_MS);\n\n const view = createMemo(() => {\n // Depend on hash instead of query to avoid recreating the view when the\n // query object changes but the hash is the same.\n const currentHash = hash();\n refetchKey();\n\n // If query is falsy, don't create a view and reset state to undefined\n if (currentHash === undefined) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const untrackedQuery = untrack(q);\n if (!untrackedQuery) {\n setState([{'': undefined}, UNKNOWN]);\n return undefined;\n }\n\n const v = zero().materialize(\n untrackedQuery,\n createSolidViewFactory(setState, refetch),\n {\n // Untracked: a ttl change updates the live view through the effect\n // below, and depending on it here would tear the view down and build\n // a new one instead. Read at materialize time rather than once at\n // setup, so a view built later -- because the query changed -- gets\n // the ttl in effect by then rather than the one this hook started\n // with.\n ttl: untrack(ttl),\n },\n );\n\n onCleanup(() => v.destroy());\n\n return v;\n });\n\n // Update TTL on existing view when it changes.\n createEffect(\n on(\n ttl,\n currentTTL => {\n view()?.updateTTL(currentTTL);\n },\n {defer: true},\n ),\n );\n\n return [() => state[0][''] as HumanReadable<TReturn>, () => state[1]];\n}\n\nfunction normalize<T>(options?: T | Accessor<T | undefined>): T | undefined {\n return typeof options === 'function' ? (options as Accessor<T>)() : options;\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,SAAgB,YAQd,aAGA,SACsB;CACtB,OAAO,SAAS,aAAa,OAAO;AACtC;AAkCA,SAAgB,SAQd,aAIA,SACkD;CAClD,MAAM,CAAC,OAAO,YAAY,YAAmB,CAC3C,EACE,IAAI,KAAA,EACN,GACA,OACF,CAAC;CAED,MAAM,CAAC,YAAY,iBAAiB,aAAa,CAAiB;CAElE,MAAM,gBAAgB;EACpB,eAAc,MAAK,IAAI,CAAC;CAC1B;CAEA,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,iBAAiB;EACzB,MAAM,QAAQ,YAAY;EAC1B,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,kBAAkB,OAAO,KAAK,EAAE,OAAO;CAChD,CAAC;CAED,MAAM,KAAK,iBAAiB;EAC1B,MAAM,QAAQ,EAAE;EAChB,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO,iBAAiB,KAAK;CAC/B,CAAC;CAKD,MAAM,OAAO,iBAAiB;EAC5B,MAAM,YAAY,GAAG;EACrB,OAAO,cAAc,KAAA,IACjB,KAAA,IACA,UAAU,KAAK,IAAI,KAAK,EAAE;CAChC,CAAC;CACD,MAAM,MAAM,iBAAiB,UAAU,OAAO,GAAG,OAAA,GAAqB;CAEtE,MAAM,OAAO,iBAAiB;EAG5B,MAAM,cAAc,KAAK;EACzB,WAAW;EAGX,IAAI,gBAAgB,KAAA,GAAW;GAC7B,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,iBAAiB,QAAQ,CAAC;EAChC,IAAI,CAAC,gBAAgB;GACnB,SAAS,CAAC,EAAC,IAAI,KAAA,EAAS,GAAG,OAAO,CAAC;GACnC;EACF;EAEA,MAAM,IAAI,KAAK,EAAE,YACf,gBACA,uBAAuB,UAAU,OAAO,GACxC,EAOE,KAAK,QAAQ,GAAG,EAClB,CACF;EAEA,gBAAgB,EAAE,QAAQ,CAAC;EAE3B,OAAO;CACT,CAAC;CAGD,aACE,GACE,MACA,eAAc;EACZ,KAAK,GAAG,UAAU,UAAU;CAC9B,GACA,EAAC,OAAO,KAAI,CACd,CACF;CAEA,OAAO,OAAO,MAAM,GAAG,WAAqC,MAAM,EAAE;AACtE;AAEA,SAAS,UAAa,SAAsD;CAC1E,OAAO,OAAO,YAAY,aAAc,QAAwB,IAAI;AACtE"}
@@ -20,7 +20,12 @@ export interface DebugDelegate {
20
20
  }
21
21
  export declare class Debug implements DebugDelegate {
22
22
  #private;
23
- constructor();
23
+ /**
24
+ * @param collectRows Whether to keep the vended rows.
25
+ * @param maxRowsPerQuery Maximum number of rows kept per table/query. Rows
26
+ * past this are still counted but not kept.
27
+ */
28
+ constructor(collectRows: boolean, maxRowsPerQuery?: number);
24
29
  getVendedRowCounts(): RowCountsBySource;
25
30
  getVendedRows(): RowsBySource;
26
31
  getNVisitCounts(): RowCountsBySource;
@@ -1 +1 @@
1
- {"version":3,"file":"debug-delegate.d.ts","sourceRoot":"","sources":["../../../../../zql/src/builder/debug-delegate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EAEjB,YAAY,EACb,MAAM,oDAAoD,CAAC;AAC5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