@noy-db/hub 0.2.0-pre.3 → 0.2.0-pre.31

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 (384) hide show
  1. package/README.md +126 -0
  2. package/dist/adapter/index.d.ts +9 -0
  3. package/dist/adapter/index.js +14 -0
  4. package/dist/aggregate/index.d.ts +3 -2
  5. package/dist/aggregate/index.js +10 -8
  6. package/dist/aggregate/index.js.map +1 -1
  7. package/dist/attestation/index.d.ts +7 -5
  8. package/dist/attestation/index.js +7 -6
  9. package/dist/attestation/index.js.map +1 -1
  10. package/dist/blobs/index.d.ts +9 -7
  11. package/dist/blobs/index.js +12 -6
  12. package/dist/blobs/index.js.map +1 -1
  13. package/dist/bundle/index.d.ts +29 -18
  14. package/dist/bundle/index.js +53 -192
  15. package/dist/bundle/index.js.map +1 -1
  16. package/dist/{chunk-75QDHSE4.js → chunk-2QDWRK3B.js} +5 -5
  17. package/dist/{chunk-74JEQFMT.js → chunk-2UT7HJJR.js} +5 -5
  18. package/dist/chunk-2UT7HJJR.js.map +1 -0
  19. package/dist/{chunk-FCDO7UAO.js → chunk-2ZYIN3BL.js} +2 -2
  20. package/dist/{chunk-BFI3RS42.js → chunk-33EQCZXE.js} +2 -2
  21. package/dist/chunk-33EQCZXE.js.map +1 -0
  22. package/dist/{chunk-WRLHNG6H.js → chunk-4K4QKYK4.js} +4 -4
  23. package/dist/chunk-4K4QKYK4.js.map +1 -0
  24. package/dist/{chunk-HGZ7DC5H.js → chunk-4L6N56B4.js} +2 -2
  25. package/dist/chunk-4L6N56B4.js.map +1 -0
  26. package/dist/{chunk-YMYK7US4.js → chunk-4YD7VZH4.js} +2 -2
  27. package/dist/chunk-4YD7VZH4.js.map +1 -0
  28. package/dist/{chunk-ZUMGGHRB.js → chunk-5PTX7PKD.js} +4 -4
  29. package/dist/{chunk-QAU5HM6Q.js → chunk-6EKRQ7QF.js} +3 -3
  30. package/dist/{chunk-ZC2AAE6J.js → chunk-7GPQPLGO.js} +19 -4
  31. package/dist/chunk-7GPQPLGO.js.map +1 -0
  32. package/dist/{chunk-EPK6A3WJ.js → chunk-A3JMGXPG.js} +2 -2
  33. package/dist/chunk-A3JMGXPG.js.map +1 -0
  34. package/dist/{chunk-FXQYZNOW.js → chunk-A7DNZVAV.js} +1 -1
  35. package/dist/chunk-A7DNZVAV.js.map +1 -0
  36. package/dist/{chunk-UMLVJTYV.js → chunk-ADB7GPM3.js} +7 -4
  37. package/dist/chunk-ADB7GPM3.js.map +1 -0
  38. package/dist/{chunk-YL2DR3HY.js → chunk-ASIGWYRA.js} +2 -2
  39. package/dist/chunk-ASIGWYRA.js.map +1 -0
  40. package/dist/{chunk-2EYC3WDT.js → chunk-AWU4JF7C.js} +93 -93
  41. package/dist/chunk-AWU4JF7C.js.map +1 -0
  42. package/dist/chunk-BEZ2EV43.js +129 -0
  43. package/dist/chunk-BEZ2EV43.js.map +1 -0
  44. package/dist/{chunk-IS5HWQO7.js → chunk-CIZDUAHI.js} +30 -4
  45. package/dist/chunk-CIZDUAHI.js.map +1 -0
  46. package/dist/{chunk-4OQWR46B.js → chunk-CUPTCF4R.js} +5 -5
  47. package/dist/chunk-CUPTCF4R.js.map +1 -0
  48. package/dist/{chunk-5ZGZ6HIZ.js → chunk-DEE4CRYN.js} +30 -7
  49. package/dist/chunk-DEE4CRYN.js.map +1 -0
  50. package/dist/{chunk-UOF74WQY.js → chunk-E2MDPPOC.js} +37 -2
  51. package/dist/chunk-E2MDPPOC.js.map +1 -0
  52. package/dist/{chunk-SAVQ6E2O.js → chunk-FFKQ65YX.js} +10 -3
  53. package/dist/chunk-FFKQ65YX.js.map +1 -0
  54. package/dist/{chunk-2XLVPKXG.js → chunk-G7ALNCQH.js} +10 -2
  55. package/dist/chunk-G7ALNCQH.js.map +1 -0
  56. package/dist/chunk-GGXN73NM.js +252 -0
  57. package/dist/chunk-GGXN73NM.js.map +1 -0
  58. package/dist/{chunk-UVPGJXVO.js → chunk-JOJPBZSZ.js} +5 -5
  59. package/dist/{chunk-YDLAFP36.js → chunk-JZ5DS4DP.js} +346 -3
  60. package/dist/chunk-JZ5DS4DP.js.map +1 -0
  61. package/dist/{chunk-KMI2NBBF.js → chunk-K4JID2ZE.js} +44 -8
  62. package/dist/chunk-K4JID2ZE.js.map +1 -0
  63. package/dist/{aggregate/index.cjs → chunk-K6NVSHAH.js} +241 -210
  64. package/dist/chunk-K6NVSHAH.js.map +1 -0
  65. package/dist/chunk-KJ3K5VZM.js +524 -0
  66. package/dist/chunk-KJ3K5VZM.js.map +1 -0
  67. package/dist/chunk-L5HHBOMS.js +232 -0
  68. package/dist/chunk-L5HHBOMS.js.map +1 -0
  69. package/dist/{chunk-YK72A4IT.js → chunk-LBILABKZ.js} +4 -4
  70. package/dist/chunk-LXKBG52H.js +151 -0
  71. package/dist/chunk-LXKBG52H.js.map +1 -0
  72. package/dist/{chunk-NGSPBLLE.js → chunk-MPIZQGFA.js} +50 -20
  73. package/dist/chunk-MPIZQGFA.js.map +1 -0
  74. package/dist/{chunk-4X2S7PBF.js → chunk-MRJPSXPE.js} +84 -70
  75. package/dist/chunk-MRJPSXPE.js.map +1 -0
  76. package/dist/{chunk-6S3LLAQ5.js → chunk-MSMDDDDJ.js} +3 -3
  77. package/dist/{chunk-6S3LLAQ5.js.map → chunk-MSMDDDDJ.js.map} +1 -1
  78. package/dist/{chunk-GAUBWHAF.js → chunk-OCYFFBZS.js} +4 -4
  79. package/dist/{chunk-NCO2JGKK.js → chunk-PDVP3C2I.js} +1 -1
  80. package/dist/chunk-PDVP3C2I.js.map +1 -0
  81. package/dist/chunk-PZ5AY32C.js +10 -0
  82. package/dist/{chunk-P6256WTJ.js → chunk-QBLPY44S.js} +3 -3
  83. package/dist/chunk-QBLPY44S.js.map +1 -0
  84. package/dist/{query/index.cjs → chunk-QGBBQKDS.js} +706 -831
  85. package/dist/chunk-QGBBQKDS.js.map +1 -0
  86. package/dist/{chunk-FS7A4XNF.js → chunk-QWJCNXH2.js} +3 -3
  87. package/dist/chunk-QXWJQ7UU.js +380 -0
  88. package/dist/chunk-QXWJQ7UU.js.map +1 -0
  89. package/dist/{chunk-GDTCGIPX.js → chunk-RCB6GWTC.js} +27 -5
  90. package/dist/chunk-RCB6GWTC.js.map +1 -0
  91. package/dist/{chunk-K5PVGKE4.js → chunk-SAAJYSVV.js} +2 -2
  92. package/dist/{chunk-G7PAZ3TD.js → chunk-SHJ3BRTZ.js} +46 -10
  93. package/dist/chunk-SHJ3BRTZ.js.map +1 -0
  94. package/dist/chunk-SQXTKZL7.js +125 -0
  95. package/dist/chunk-SQXTKZL7.js.map +1 -0
  96. package/dist/chunk-STNPB3UM.js +9 -0
  97. package/dist/chunk-STNPB3UM.js.map +1 -0
  98. package/dist/{chunk-NSLTPGEN.js → chunk-TMUMMAWV.js} +12 -2
  99. package/dist/{chunk-NSLTPGEN.js.map → chunk-TMUMMAWV.js.map} +1 -1
  100. package/dist/{chunk-LS3JLEIB.js → chunk-TZGWI5AX.js} +4 -4
  101. package/dist/{chunk-GD3BGKAR.js → chunk-UBF5JEOJ.js} +44 -5
  102. package/dist/chunk-UBF5JEOJ.js.map +1 -0
  103. package/dist/{chunk-T6HQMVML.js → chunk-W5NVNJDX.js} +5250 -801
  104. package/dist/chunk-W5NVNJDX.js.map +1 -0
  105. package/dist/chunk-XAYDHD2O.js +123 -0
  106. package/dist/chunk-XAYDHD2O.js.map +1 -0
  107. package/dist/{chunk-LOL725S4.js → chunk-XYW2CSCI.js} +31 -3
  108. package/dist/chunk-XYW2CSCI.js.map +1 -0
  109. package/dist/{chunk-TLFUDXVV.js → chunk-ZCMOS4H2.js} +31 -10
  110. package/dist/chunk-ZCMOS4H2.js.map +1 -0
  111. package/dist/{chunk-FBMXWVGP.js → chunk-ZK66B5EY.js} +450 -30
  112. package/dist/chunk-ZK66B5EY.js.map +1 -0
  113. package/dist/{chunk-GVXBHCZ2.js → chunk-ZPJSQPQH.js} +66 -7
  114. package/dist/chunk-ZPJSQPQH.js.map +1 -0
  115. package/dist/consent/index.d.ts +8 -6
  116. package/dist/consent/index.js +4 -3
  117. package/dist/consent/index.js.map +1 -1
  118. package/dist/crdt/index.js +1 -0
  119. package/dist/crdt/index.js.map +1 -1
  120. package/dist/{crypto-H2Y3DDFW.js → crypto-OSIV2IIW.js} +8 -3
  121. package/dist/{ulid-CiM2OAeM.d.ts → decrypt-partition-CXS5KopB.d.ts} +37 -82
  122. package/dist/{delegation-QSC7G5QC.js → delegation-BQTRJATI.js} +6 -5
  123. package/dist/derivations/index.d.ts +11 -9
  124. package/dist/derivations/index.js +9 -6
  125. package/dist/{dev-unlock-Cf2B7Kih.d.ts → dev-unlock-CnHTTVea.d.ts} +1 -1
  126. package/dist/discriminant-BN9REW3o.d.ts +60 -0
  127. package/dist/errors-BAWO5Z5a.d.ts +1500 -0
  128. package/dist/executor-KYSKFJ2R.js +9 -0
  129. package/dist/executor-M7W3NEKR.js +9 -0
  130. package/dist/executor-VDTDGWO6.js +13 -0
  131. package/dist/{fanout-sidecar-NRBWSLRK.js → fanout-sidecar-AZALISHB.js} +3 -2
  132. package/dist/fanout-sidecar-AZALISHB.js.map +1 -0
  133. package/dist/forget/index.d.ts +1 -0
  134. package/dist/forget/index.js +15 -0
  135. package/dist/guards/index.d.ts +16 -8
  136. package/dist/guards/index.js +12 -5
  137. package/dist/{hash-gVn_uKhp.d.ts → hash-oc5paYl0.d.ts} +1 -1
  138. package/dist/history/index.d.ts +9 -7
  139. package/dist/history/index.js +10 -7
  140. package/dist/history/index.js.map +1 -1
  141. package/dist/i18n/index.d.ts +8 -6
  142. package/dist/i18n/index.js +116 -15
  143. package/dist/i18n/index.js.map +1 -1
  144. package/dist/index-BMmajblo.d.ts +362 -0
  145. package/dist/index-BmhGztUi.d.ts +93 -0
  146. package/dist/{types-D9eB0Rvh.d.ts → index-DHn9lEP0.d.ts} +4305 -1523
  147. package/dist/{index-BF1B2HB9.d.ts → index-Ddm8D3Oo.d.ts} +186 -1151
  148. package/dist/index.d.ts +342 -70
  149. package/dist/index.js +420 -112
  150. package/dist/index.js.map +1 -1
  151. package/dist/indexing/index.d.ts +3 -3
  152. package/dist/indexing/index.js +5 -4
  153. package/dist/indexing/index.js.map +1 -1
  154. package/dist/issue-DPHRF2TI.js +13 -0
  155. package/dist/kernel/index.d.ts +11 -0
  156. package/dist/kernel/index.js +50 -0
  157. package/dist/{lazy-builder-Rpd-V3jP.d.ts → lazy-builder-ChSqcF5t.d.ts} +2 -2
  158. package/dist/{ledger-WOEJUYTP.js → ledger-CI7GSMLB.js} +7 -6
  159. package/dist/materialized-views/index.d.ts +23 -20
  160. package/dist/materialized-views/index.js +9 -7
  161. package/dist/mime-magic-JeLKHRng.d.ts +103 -0
  162. package/dist/noydb-NAU2DTFP.js +40 -0
  163. package/dist/overlay-views/index.d.ts +32 -12
  164. package/dist/overlay-views/index.js +7 -6
  165. package/dist/periods/index.d.ts +8 -6
  166. package/dist/periods/index.js +7 -6
  167. package/dist/{predicate-Dnu81tsS.d.cts → predicate-BmhBSPCH.d.ts} +87 -5
  168. package/dist/{public-envelope-OHQ5UZFM.js → public-envelope-MFMBFJLZ.js} +5 -4
  169. package/dist/query/index.d.ts +4 -3
  170. package/dist/query/index.js +14 -6
  171. package/dist/read-only-facade-3OQRZ3VS.js +8 -0
  172. package/dist/registry-IX5WKK4F.js +8 -0
  173. package/dist/registry-LMHO5265.js +11 -0
  174. package/dist/registry-TXCKWH26.js +9 -0
  175. package/dist/registry-VFEDQSYV.js +9 -0
  176. package/dist/revoke-5PUOZPJJ.js +18 -0
  177. package/dist/revoke-5PUOZPJJ.js.map +1 -0
  178. package/dist/sealed-record/index.d.ts +123 -0
  179. package/dist/sealed-record/index.js +43 -0
  180. package/dist/sealed-record/index.js.map +1 -0
  181. package/dist/session/index.d.ts +9 -7
  182. package/dist/session/index.js +4 -3
  183. package/dist/session/index.js.map +1 -1
  184. package/dist/shadow/index.d.ts +8 -6
  185. package/dist/shadow/index.js +3 -2
  186. package/dist/shadow/index.js.map +1 -1
  187. package/dist/{signer-M4K5HBLD.js → signer-UB5TQOZ6.js} +6 -5
  188. package/dist/signer-UB5TQOZ6.js.map +1 -0
  189. package/dist/snapshots/index.d.ts +30 -0
  190. package/dist/snapshots/index.js +153 -0
  191. package/dist/snapshots/index.js.map +1 -0
  192. package/dist/{stale-PAGCS4K5.js → stale-J3TUF5C5.js} +3 -2
  193. package/dist/stale-J3TUF5C5.js.map +1 -0
  194. package/dist/store/index.d.ts +15 -6
  195. package/dist/store/index.js +3 -2
  196. package/dist/{strategy-DSTrsZ8t.d.ts → strategy-8QGs5KQE.d.ts} +475 -7
  197. package/dist/sync/index.d.ts +7 -5
  198. package/dist/sync/index.js +5 -4
  199. package/dist/sync/index.js.map +1 -1
  200. package/dist/team/index.d.ts +8 -6
  201. package/dist/team/index.js +9 -8
  202. package/dist/transition-guard-Dy3NioQr.d.ts +165 -0
  203. package/dist/tx/index.d.ts +26 -8
  204. package/dist/tx/index.js +10 -5
  205. package/dist/tx/index.js.map +1 -1
  206. package/dist/ulid-DRH25k3y.d.ts +66 -0
  207. package/dist/{ulid-COREQ2RQ.js → ulid-KEPZMD2N.js} +2 -1
  208. package/dist/ulid-KEPZMD2N.js.map +1 -0
  209. package/dist/util/index.d.ts +2 -0
  210. package/dist/util/index.js +6 -1
  211. package/dist/util/index.js.map +1 -1
  212. package/dist/{with-materialized-view-qtoJ3xKJ.d.ts → with-materialized-view-DIVeez0W.d.ts} +2 -2
  213. package/dist/{with-overlayed-view-DFaRfgMr.d.ts → with-overlayed-view-DVZrc5Hb.d.ts} +2 -2
  214. package/dist/with-rollup-CbU-O4wP.d.ts +47 -0
  215. package/dist/zod-HAJM7LMS.js +14763 -0
  216. package/dist/zod-HAJM7LMS.js.map +1 -0
  217. package/package.json +73 -191
  218. package/dist/aggregate/index.cjs.map +0 -1
  219. package/dist/aggregate/index.d.cts +0 -38
  220. package/dist/attestation/index.cjs +0 -305
  221. package/dist/attestation/index.cjs.map +0 -1
  222. package/dist/attestation/index.d.cts +0 -52
  223. package/dist/blobs/index.cjs +0 -1480
  224. package/dist/blobs/index.cjs.map +0 -1
  225. package/dist/blobs/index.d.cts +0 -46
  226. package/dist/bundle/index.cjs +0 -18561
  227. package/dist/bundle/index.cjs.map +0 -1
  228. package/dist/bundle/index.d.cts +0 -176
  229. package/dist/chunk-2EYC3WDT.js.map +0 -1
  230. package/dist/chunk-2XLVPKXG.js.map +0 -1
  231. package/dist/chunk-4OQWR46B.js.map +0 -1
  232. package/dist/chunk-4UBOTYP5.js +0 -1367
  233. package/dist/chunk-4UBOTYP5.js.map +0 -1
  234. package/dist/chunk-4X2S7PBF.js.map +0 -1
  235. package/dist/chunk-5YHWBPOT.js +0 -19
  236. package/dist/chunk-5YHWBPOT.js.map +0 -1
  237. package/dist/chunk-5ZGZ6HIZ.js.map +0 -1
  238. package/dist/chunk-74JEQFMT.js.map +0 -1
  239. package/dist/chunk-A6SWRXUQ.js +0 -118
  240. package/dist/chunk-A6SWRXUQ.js.map +0 -1
  241. package/dist/chunk-BFI3RS42.js.map +0 -1
  242. package/dist/chunk-EMEX37ZN.js +0 -51
  243. package/dist/chunk-EMEX37ZN.js.map +0 -1
  244. package/dist/chunk-EPK6A3WJ.js.map +0 -1
  245. package/dist/chunk-FBMXWVGP.js.map +0 -1
  246. package/dist/chunk-FXQYZNOW.js.map +0 -1
  247. package/dist/chunk-G7PAZ3TD.js.map +0 -1
  248. package/dist/chunk-GD3BGKAR.js.map +0 -1
  249. package/dist/chunk-GDTCGIPX.js.map +0 -1
  250. package/dist/chunk-GVXBHCZ2.js.map +0 -1
  251. package/dist/chunk-HGZ7DC5H.js.map +0 -1
  252. package/dist/chunk-IS5HWQO7.js.map +0 -1
  253. package/dist/chunk-KMI2NBBF.js.map +0 -1
  254. package/dist/chunk-KYKMKLJ6.js +0 -340
  255. package/dist/chunk-KYKMKLJ6.js.map +0 -1
  256. package/dist/chunk-LOL725S4.js.map +0 -1
  257. package/dist/chunk-MRIBLZL3.js +0 -86
  258. package/dist/chunk-MRIBLZL3.js.map +0 -1
  259. package/dist/chunk-NCO2JGKK.js.map +0 -1
  260. package/dist/chunk-NGSPBLLE.js.map +0 -1
  261. package/dist/chunk-P6256WTJ.js.map +0 -1
  262. package/dist/chunk-SAVQ6E2O.js.map +0 -1
  263. package/dist/chunk-T6HQMVML.js.map +0 -1
  264. package/dist/chunk-TLFUDXVV.js.map +0 -1
  265. package/dist/chunk-UMLVJTYV.js.map +0 -1
  266. package/dist/chunk-UOF74WQY.js.map +0 -1
  267. package/dist/chunk-WRLHNG6H.js.map +0 -1
  268. package/dist/chunk-YDLAFP36.js.map +0 -1
  269. package/dist/chunk-YL2DR3HY.js.map +0 -1
  270. package/dist/chunk-YMYK7US4.js.map +0 -1
  271. package/dist/chunk-ZC2AAE6J.js.map +0 -1
  272. package/dist/consent/index.cjs +0 -204
  273. package/dist/consent/index.cjs.map +0 -1
  274. package/dist/consent/index.d.cts +0 -25
  275. package/dist/crdt/index.cjs +0 -152
  276. package/dist/crdt/index.cjs.map +0 -1
  277. package/dist/crdt/index.d.cts +0 -30
  278. package/dist/derivations/index.cjs +0 -351
  279. package/dist/derivations/index.cjs.map +0 -1
  280. package/dist/derivations/index.d.cts +0 -72
  281. package/dist/dev-unlock-De3mjQWv.d.cts +0 -263
  282. package/dist/executor-BZKFZVRC.js +0 -8
  283. package/dist/executor-GFZFDQXV.js +0 -8
  284. package/dist/executor-KT2IOZVP.js +0 -11
  285. package/dist/fanout-sidecar-NRBWSLRK.js.map +0 -1
  286. package/dist/guards/index.cjs +0 -322
  287. package/dist/guards/index.cjs.map +0 -1
  288. package/dist/guards/index.d.cts +0 -31
  289. package/dist/hash-vBCB0-Ps.d.cts +0 -63
  290. package/dist/history/index.cjs +0 -1222
  291. package/dist/history/index.cjs.map +0 -1
  292. package/dist/history/index.d.cts +0 -63
  293. package/dist/i18n/index.cjs +0 -840
  294. package/dist/i18n/index.cjs.map +0 -1
  295. package/dist/i18n/index.d.cts +0 -39
  296. package/dist/index-DVkvrgpm.d.cts +0 -2290
  297. package/dist/index.cjs +0 -23590
  298. package/dist/index.cjs.map +0 -1
  299. package/dist/index.d.cts +0 -778
  300. package/dist/indexing/index.cjs +0 -738
  301. package/dist/indexing/index.cjs.map +0 -1
  302. package/dist/indexing/index.d.cts +0 -36
  303. package/dist/issue-BAJ7ZB4S.js +0 -12
  304. package/dist/lazy-builder-C-rPfWG0.d.cts +0 -304
  305. package/dist/materialized-views/index.cjs +0 -837
  306. package/dist/materialized-views/index.cjs.map +0 -1
  307. package/dist/materialized-views/index.d.cts +0 -184
  308. package/dist/mime-magic-CBBSOkjm.d.cts +0 -50
  309. package/dist/mime-magic-CBBSOkjm.d.ts +0 -50
  310. package/dist/noydb-XNQSKXGO.js +0 -34
  311. package/dist/overlay-views/index.cjs +0 -359
  312. package/dist/overlay-views/index.cjs.map +0 -1
  313. package/dist/overlay-views/index.d.cts +0 -82
  314. package/dist/periods/index.cjs +0 -1041
  315. package/dist/periods/index.cjs.map +0 -1
  316. package/dist/periods/index.d.cts +0 -22
  317. package/dist/predicate-Dnu81tsS.d.ts +0 -185
  318. package/dist/query/index.cjs.map +0 -1
  319. package/dist/query/index.d.cts +0 -3
  320. package/dist/read-only-facade-ITU6L7BL.js +0 -7
  321. package/dist/registry-2IEARCGT.js +0 -7
  322. package/dist/registry-CDHASH73.js +0 -10
  323. package/dist/registry-EMGLZGR6.js +0 -8
  324. package/dist/registry-NQALYR77.js +0 -8
  325. package/dist/revoke-7JOVLZFD.js +0 -17
  326. package/dist/session/index.cjs +0 -495
  327. package/dist/session/index.cjs.map +0 -1
  328. package/dist/session/index.d.cts +0 -46
  329. package/dist/shadow/index.cjs +0 -133
  330. package/dist/shadow/index.cjs.map +0 -1
  331. package/dist/shadow/index.d.cts +0 -17
  332. package/dist/store/index.cjs +0 -1083
  333. package/dist/store/index.cjs.map +0 -1
  334. package/dist/store/index.d.cts +0 -492
  335. package/dist/strategy-BSxFXGzb.d.cts +0 -110
  336. package/dist/strategy-DSTrsZ8t.d.cts +0 -601
  337. package/dist/sync/index.cjs +0 -1062
  338. package/dist/sync/index.cjs.map +0 -1
  339. package/dist/sync/index.d.cts +0 -43
  340. package/dist/team/index.cjs +0 -2798
  341. package/dist/team/index.cjs.map +0 -1
  342. package/dist/team/index.d.cts +0 -118
  343. package/dist/tx/index.cjs +0 -544
  344. package/dist/tx/index.cjs.map +0 -1
  345. package/dist/tx/index.d.cts +0 -21
  346. package/dist/types-CSLcfytP.d.cts +0 -12493
  347. package/dist/ulid-CG2YvAbg.d.cts +0 -603
  348. package/dist/util/index.cjs +0 -230
  349. package/dist/util/index.cjs.map +0 -1
  350. package/dist/util/index.d.cts +0 -77
  351. package/dist/with-derivation-Bzpj6UTv.d.ts +0 -13
  352. package/dist/with-derivation-DWajFh4K.d.cts +0 -13
  353. package/dist/with-guard-DF_Ul3DT.d.cts +0 -18
  354. package/dist/with-guard-DR7U-l4v.d.ts +0 -18
  355. package/dist/with-materialized-view-_piodoIz.d.cts +0 -27
  356. package/dist/with-overlayed-view-DwzCKxn2.d.cts +0 -13
  357. /package/dist/{crypto-H2Y3DDFW.js.map → adapter/index.js.map} +0 -0
  358. /package/dist/{chunk-75QDHSE4.js.map → chunk-2QDWRK3B.js.map} +0 -0
  359. /package/dist/{chunk-FCDO7UAO.js.map → chunk-2ZYIN3BL.js.map} +0 -0
  360. /package/dist/{chunk-ZUMGGHRB.js.map → chunk-5PTX7PKD.js.map} +0 -0
  361. /package/dist/{chunk-QAU5HM6Q.js.map → chunk-6EKRQ7QF.js.map} +0 -0
  362. /package/dist/{chunk-UVPGJXVO.js.map → chunk-JOJPBZSZ.js.map} +0 -0
  363. /package/dist/{chunk-YK72A4IT.js.map → chunk-LBILABKZ.js.map} +0 -0
  364. /package/dist/{chunk-GAUBWHAF.js.map → chunk-OCYFFBZS.js.map} +0 -0
  365. /package/dist/{delegation-QSC7G5QC.js.map → chunk-PZ5AY32C.js.map} +0 -0
  366. /package/dist/{chunk-FS7A4XNF.js.map → chunk-QWJCNXH2.js.map} +0 -0
  367. /package/dist/{chunk-K5PVGKE4.js.map → chunk-SAAJYSVV.js.map} +0 -0
  368. /package/dist/{chunk-LS3JLEIB.js.map → chunk-TZGWI5AX.js.map} +0 -0
  369. /package/dist/{executor-BZKFZVRC.js.map → crypto-OSIV2IIW.js.map} +0 -0
  370. /package/dist/{executor-GFZFDQXV.js.map → delegation-BQTRJATI.js.map} +0 -0
  371. /package/dist/{executor-KT2IOZVP.js.map → executor-KYSKFJ2R.js.map} +0 -0
  372. /package/dist/{issue-BAJ7ZB4S.js.map → executor-M7W3NEKR.js.map} +0 -0
  373. /package/dist/{ledger-WOEJUYTP.js.map → executor-VDTDGWO6.js.map} +0 -0
  374. /package/dist/{noydb-XNQSKXGO.js.map → forget/index.js.map} +0 -0
  375. /package/dist/{public-envelope-OHQ5UZFM.js.map → issue-DPHRF2TI.js.map} +0 -0
  376. /package/dist/{read-only-facade-ITU6L7BL.js.map → kernel/index.js.map} +0 -0
  377. /package/dist/{registry-2IEARCGT.js.map → ledger-CI7GSMLB.js.map} +0 -0
  378. /package/dist/{registry-CDHASH73.js.map → noydb-NAU2DTFP.js.map} +0 -0
  379. /package/dist/{registry-EMGLZGR6.js.map → public-envelope-MFMBFJLZ.js.map} +0 -0
  380. /package/dist/{registry-NQALYR77.js.map → read-only-facade-3OQRZ3VS.js.map} +0 -0
  381. /package/dist/{revoke-7JOVLZFD.js.map → registry-IX5WKK4F.js.map} +0 -0
  382. /package/dist/{signer-M4K5HBLD.js.map → registry-LMHO5265.js.map} +0 -0
  383. /package/dist/{stale-PAGCS4K5.js.map → registry-TXCKWH26.js.map} +0 -0
  384. /package/dist/{ulid-COREQ2RQ.js.map → registry-VFEDQSYV.js.map} +0 -0
@@ -1,2290 +0,0 @@
1
- import { C as CollectionIndexes, a as Clause, O as Operator } from './predicate-Dnu81tsS.cjs';
2
- import { A as AggregateStrategy, b as AggregateSpec, c as Aggregation, a as AggregateResult, g as GroupedQuery, h as GroupedQueryN } from './strategy-DSTrsZ8t.cjs';
3
-
4
- /**
5
- * All NOYDB error classes — a single import surface for `catch` blocks and
6
- * `instanceof` checks.
7
- *
8
- * ## Class hierarchy
9
- *
10
- * ```
11
- * Error
12
- * └─ NoydbError (code: string)
13
- * ├─ Crypto errors
14
- * │ ├─ DecryptionError — AES-GCM tag failure
15
- * │ ├─ TamperedError — ciphertext modified after write
16
- * │ └─ InvalidKeyError — wrong passphrase / corrupt keyring
17
- * ├─ Access errors
18
- * │ ├─ NoAccessError — no DEK for this collection
19
- * │ ├─ ReadOnlyError — ro permission, write attempted
20
- * │ ├─ PermissionDeniedError — role too low for operation
21
- * │ ├─ PrivilegeEscalationError — grant wider than grantor holds
22
- * │ └─ StoreCapabilityError — optional store method missing
23
- * ├─ Sync errors
24
- * │ ├─ ConflictError — optimistic-lock version mismatch
25
- * │ ├─ BundleVersionConflictError — bundle push rejected by remote
26
- * │ └─ NetworkError — push/pull network failure
27
- * ├─ Data errors
28
- * │ ├─ NotFoundError — get(id) on missing record
29
- * │ ├─ ValidationError — application-level guard failed
30
- * │ └─ SchemaValidationError — Standard Schema v1 rejection
31
- * ├─ Query errors
32
- * │ ├─ JoinTooLargeError — join row ceiling exceeded
33
- * │ ├─ DanglingReferenceError — strict ref() points at nothing
34
- * │ ├─ GroupCardinalityError — groupBy bucket cap exceeded
35
- * │ ├─ IndexRequiredError — lazy-mode query touches unindexed field
36
- * │ └─ IndexWriteFailureError — index side-car put/delete failed post-main
37
- * ├─ i18n / Dictionary errors
38
- * │ ├─ ReservedCollectionNameError
39
- * │ ├─ DictKeyMissingError
40
- * │ ├─ DictKeyInUseError
41
- * │ ├─ MissingTranslationError
42
- * │ ├─ LocaleNotSpecifiedError
43
- * │ └─ TranslatorNotConfiguredError
44
- * ├─ Backup errors
45
- * │ ├─ BackupLedgerError — hash-chain verification failed
46
- * │ └─ BackupCorruptedError — envelope hash mismatch in dump
47
- * ├─ Bundle errors
48
- * │ └─ BundleIntegrityError — .noydb body sha256 mismatch
49
- * └─ Session errors
50
- * ├─ SessionExpiredError
51
- * ├─ SessionNotFoundError
52
- * └─ SessionPolicyError
53
- * ```
54
- *
55
- * ## Catching all NOYDB errors
56
- *
57
- * ```ts
58
- * import { NoydbError, InvalidKeyError, ConflictError } from '@noy-db/hub'
59
- *
60
- * try {
61
- * await vault.unlock(passphrase)
62
- * } catch (e) {
63
- * if (e instanceof InvalidKeyError) { showBadPassphraseUI(); return }
64
- * if (e instanceof NoydbError) { logToSentry(e.code, e); return }
65
- * throw e // unexpected — re-throw
66
- * }
67
- * ```
68
- *
69
- * @module
70
- */
71
- /**
72
- * Base class for all NOYDB errors.
73
- *
74
- * Every error thrown by `@noy-db/hub` extends this class, so consumers can
75
- * catch all NOYDB errors in a single `catch (e) { if (e instanceof NoydbError) ... }`
76
- * block. The `code` field is a machine-readable string (e.g. `'DECRYPTION_FAILED'`)
77
- * suitable for `switch` statements and logging pipelines.
78
- */
79
- declare class NoydbError extends Error {
80
- /** Machine-readable error code. Stable across library versions. */
81
- readonly code: string;
82
- constructor(code: string, message: string);
83
- }
84
- /**
85
- * Thrown when AES-GCM decryption fails.
86
- *
87
- * The most common cause is a wrong passphrase or a corrupted ciphertext.
88
- * A `DecryptionError` at the wrong passphrase level is caught internally
89
- * and re-thrown as `InvalidKeyError` — so in practice this surfaces for
90
- * per-record corruption rather than authentication failures.
91
- */
92
- declare class DecryptionError extends NoydbError {
93
- constructor(message?: string);
94
- }
95
- /**
96
- * Thrown when GCM tag verification fails, indicating the ciphertext was
97
- * modified after encryption.
98
- *
99
- * AES-256-GCM is authenticated encryption — the tag over the ciphertext
100
- * is checked on every decrypt. If any byte was flipped (accidental
101
- * corruption or deliberate tampering), decryption throws this error.
102
- * Treat it as a security alert: the stored bytes are not what NOYDB wrote.
103
- */
104
- declare class TamperedError extends NoydbError {
105
- constructor(message?: string);
106
- }
107
- /**
108
- * Thrown when key unwrapping fails, typically because the passphrase is wrong
109
- * or the keyring file is corrupted.
110
- *
111
- * NOYDB uses AES-KW (RFC 3394) to wrap DEKs with the KEK. If AES-KW
112
- * unwrapping fails, it means either the KEK was derived from the wrong
113
- * passphrase (PBKDF2 with 600K iterations) or the keyring bytes are
114
- * corrupted. This is the error shown to the user on a failed unlock attempt.
115
- */
116
- declare class InvalidKeyError extends NoydbError {
117
- constructor(message?: string);
118
- }
119
- /**
120
- * Thrown when a keyring's wrapped-DEK set unwraps partially — at least
121
- * one DEK succeeds (proving the KEK is correct) but at least one fails.
122
- * The passphrase is right; the failed entries are corrupted.
123
- *
124
- * This is distinct from {@link InvalidKeyError} so that
125
- * `NoydbOptions.onInvalidKey: 'reset'` does NOT fire — resetting on
126
- * partial corruption would destroy the still-valid DEKs and the data
127
- * they protect, which is silent data loss in response to a feature
128
- * designed for stale-credential recovery.
129
- */
130
- declare class KeyringCorruptError extends NoydbError {
131
- readonly failedCollections: readonly string[];
132
- readonly intactCount: number;
133
- constructor(opts: {
134
- failedCollections: readonly string[];
135
- intactCount: number;
136
- message?: string;
137
- });
138
- }
139
- /**
140
- * Thrown when the authenticated user does not have a DEK for the requested
141
- * collection — i.e. the collection is not in their keyring at all.
142
- *
143
- * This is the "no key for this door" error. It is different from
144
- * `ReadOnlyError` (user has a key but it only grants ro) and from
145
- * `PermissionDeniedError` (user's role doesn't allow the operation).
146
- */
147
- declare class NoAccessError extends NoydbError {
148
- constructor(message?: string);
149
- }
150
- /**
151
- * Thrown when a user with read-only (`ro`) permission attempts a write
152
- * operation (`put` or `delete`) on a collection.
153
- *
154
- * The user has a DEK for the collection (they can decrypt and read), but
155
- * their keyring grants only `ro`. To fix: re-grant the user with `rw`
156
- * permission, or do not attempt writes as a viewer/client role.
157
- */
158
- declare class ReadOnlyError extends NoydbError {
159
- constructor(message?: string);
160
- }
161
- /**
162
- * Thrown when a write is attempted against a historical view produced
163
- * by `vault.at(timestamp)`. Time-machine views are read-only by
164
- * contract — mutating the past would require either the shadow-vault
165
- * mechanism or a ledger-history rewrite (which breaks
166
- * the tamper-evidence guarantee).
167
- *
168
- * Distinct from {@link ReadOnlyError} (keyring-level) and
169
- * {@link PermissionDeniedError} (role-level): this error is about the
170
- * *view* being historical, independent of the caller's permissions.
171
- */
172
- declare class ReadOnlyAtInstantError extends NoydbError {
173
- constructor(operation: string, timestamp: string);
174
- }
175
- /**
176
- * Thrown when a write is attempted against a shadow-vault frame
177
- * produced by `vault.frame()`. Frames are read-only by contract —
178
- * the use case is screen-sharing / demos / compliance review where
179
- * the operator wants to prevent accidental edits.
180
- *
181
- * Behavioural enforcement only — the underlying keyring still holds
182
- * write-capable DEKs. See {@link VaultFrame} for the full caveat.
183
- */
184
- declare class ReadOnlyFrameError extends NoydbError {
185
- constructor(operation: string);
186
- }
187
- /**
188
- * Thrown when the authenticated user's role does not permit the requested
189
- * operation — e.g. a `viewer` calling `grantAccess()`, or an `operator`
190
- * calling `rotateKeys()`.
191
- *
192
- * This is a role-level check (what the user's role allows), distinct from
193
- * `NoAccessError` (collection not in keyring) and `ReadOnlyError` (in
194
- * keyring, but write not allowed).
195
- */
196
- declare class PermissionDeniedError extends NoydbError {
197
- constructor(message?: string);
198
- }
199
- /**
200
- * Thrown when an `@noy-db/as-*` export is attempted without the
201
- * required capability bit on the invoking keyring.
202
- *
203
- * Two sub-cases discriminated by the `tier` field:
204
- *
205
- * - `tier: 'plaintext'` — a plaintext-tier export (`as-xlsx`,
206
- * `as-csv`, `as-blob`, `as-zip`, …) was attempted but the
207
- * keyring's `exportCapability.plaintext` does not include the
208
- * requested `format` (nor the `'*'` wildcard). Default for every
209
- * role is `plaintext: []` — the owner must positively grant.
210
- * - `tier: 'bundle'` — an encrypted `as-noydb` bundle export was
211
- * attempted but the keyring's `exportCapability.bundle` is
212
- * `false`. Default for `owner`/`admin` is `true`; for
213
- * `operator`/`viewer`/`client` it is `false`.
214
- *
215
- * Distinct from `PermissionDeniedError` (role-level check) and
216
- * `NoAccessError` (collection not readable). Surfaces separately so
217
- * UI layers can show a "request the export capability from your
218
- * admin" flow rather than a generic permission error.
219
- */
220
- declare class ExportCapabilityError extends NoydbError {
221
- readonly tier: 'plaintext' | 'bundle';
222
- readonly format?: string;
223
- readonly userId: string;
224
- constructor(opts: {
225
- tier: 'plaintext' | 'bundle';
226
- userId: string;
227
- format?: string;
228
- message?: string;
229
- });
230
- }
231
- /**
232
- * Thrown when a keyring file's `expires_at` cutoff has passed.
233
- * Surfaced by `loadKeyring` before any DEK unwrap is attempted —
234
- * past the cutoff the slot refuses to open even with the right
235
- * passphrase. Distinct from PBKDF2 / unwrap errors so consumer code
236
- * can show a precise "this bundle slot has expired" message instead
237
- * of the generic decryption-failure UX.
238
- *
239
- * Used predominantly on `BundleRecipient` slots produced by
240
- * `writeNoydbBundle({ recipients: [...] })` to time-box audit access.
241
- */
242
- declare class KeyringExpiredError extends NoydbError {
243
- readonly userId: string;
244
- readonly expiresAt: string;
245
- constructor(opts: {
246
- userId: string;
247
- expiresAt: string;
248
- });
249
- }
250
- /**
251
- * Thrown when an `@noy-db/as-*` import is attempted but the invoking
252
- * keyring lacks the required import-capability bit.
253
- *
254
- * - `tier: 'plaintext'` — a plaintext-tier import (`as-csv`, `as-json`,
255
- * `as-ndjson`, `as-zip`, …) was attempted but the keyring's
256
- * `importCapability.plaintext` does not include the requested
257
- * `format` (nor the `'*'` wildcard).
258
- * - `tier: 'bundle'` — a `.noydb` bundle import was attempted but the
259
- * keyring's `importCapability.bundle` is not `true`.
260
- *
261
- * Default for every role on every dimension is closed — owners and
262
- * admins must positively grant the capability. Distinct from
263
- * `PermissionDeniedError` and `NoAccessError` so UI layers can show a
264
- * specific "request the import capability" flow.
265
- */
266
- declare class ImportCapabilityError extends NoydbError {
267
- readonly tier: 'plaintext' | 'bundle';
268
- readonly format?: string;
269
- readonly userId: string;
270
- constructor(opts: {
271
- tier: 'plaintext' | 'bundle';
272
- userId: string;
273
- format?: string;
274
- message?: string;
275
- });
276
- }
277
- /**
278
- * Thrown when a grant would give the grantee a permission the grantor
279
- * does not themselves hold — the "admin cannot grant what admin cannot
280
- * do" rule from the admin-delegation work.
281
- *
282
- * Distinct from `PermissionDeniedError` so callers can tell the two
283
- * cases apart in logs and tests:
284
- *
285
- * - `PermissionDeniedError` — "you are not allowed to perform this
286
- * operation at all" (wrong role).
287
- * - `PrivilegeEscalationError` — "you are allowed to grant, but not
288
- * with these specific permissions" (widening attempt).
289
- *
290
- * Under the admin model the grantee of an admin-grants-admin call
291
- * inherits the caller's entire DEK set by construction, so this error
292
- * is structurally unreachable in typical flows. The check and error
293
- * class exist so that future per-collection admin scoping cannot
294
- * accidentally bypass the subset rule — the guard is already wired in.
295
- *
296
- * `offendingCollection` carries the first collection name that failed
297
- * the subset check, to make the violation actionable in error output.
298
- */
299
- /**
300
- * Thrown when a caller invokes an API that requires an optional
301
- * store capability the active store does not implement.
302
- *
303
- * Today the only call site is `Noydb.listAccessibleVaults()`,
304
- * which depends on the optional `NoydbStore.listVaults()`
305
- * method. The error message names the missing method and the calling
306
- * API so consumers know exactly which combination is unsupported,
307
- * and the `capability` field is machine-readable so library code can
308
- * pattern-match in catch blocks (e.g. fall back to a candidate-list
309
- * shape).
310
- *
311
- * The class lives in `errors.ts` rather than as a generic
312
- * `ValidationError` because the diagnostic shape is different: a
313
- * `ValidationError` says "the inputs you passed are wrong"; this
314
- * error says "the inputs are fine, but the store you wired up
315
- * doesn't support what you're asking for." Different fix, different
316
- * documentation.
317
- */
318
- declare class StoreCapabilityError extends NoydbError {
319
- /** The store method/capability that was missing. */
320
- readonly capability: string;
321
- constructor(capability: string, callerApi: string, storeName?: string);
322
- }
323
- declare class PrivilegeEscalationError extends NoydbError {
324
- readonly offendingCollection: string;
325
- constructor(offendingCollection: string, message?: string);
326
- }
327
- /**
328
- * Thrown by `Collection.put` / `.delete` when the target record's
329
- * envelope `_ts` falls within a closed accounting period.
330
- *
331
- * Distinct from `ReadOnlyError` (keyring-level), `ReadOnlyAtInstantError`
332
- * (historical view), and `ReadOnlyFrameError` (shadow vault): this
333
- * error is about the STORED RECORD being sealed by an operator call
334
- * to `vault.closePeriod()`, independent of caller permissions or
335
- * view type. The `periodName` and `endDate` fields name the sealing
336
- * period so audit UIs can surface a "this record is locked in
337
- * FY2026-Q1 (closed 2026-03-31)" message without parsing the error
338
- * string.
339
- *
340
- * To apply a correction after close, book a compensating entry in a
341
- * new period rather than unlocking the old one. Re-opening a closed
342
- * period is deliberately unsupported.
343
- */
344
- declare class PeriodClosedError extends NoydbError {
345
- readonly periodName: string;
346
- readonly endDate: string;
347
- readonly recordTs: string;
348
- constructor(periodName: string, endDate: string, recordTs: string);
349
- }
350
- /**
351
- * Thrown when a `put()` or `delete()` is rejected by a guard's `check`
352
- * function. The `reason` is the message the guard supplied — typically a
353
- * short business description (e.g. "invoice is issued"). The full
354
- * collection + id are surfaced so audit UIs can link back to the record.
355
- */
356
- declare class RecordLockedError extends NoydbError {
357
- readonly collection: string;
358
- readonly id: string;
359
- readonly reason: string;
360
- constructor(collection: string, id: string, reason: string);
361
- }
362
- /**
363
- * Thrown when a `put()` changes one or more fields that are frozen by a
364
- * `frozenFields` guard. The `fields` list contains the specific paths
365
- * that were detected as changed.
366
- */
367
- declare class FieldFrozenError extends NoydbError {
368
- readonly collection: string;
369
- readonly id: string;
370
- readonly fields: readonly string[];
371
- constructor(collection: string, id: string, fields: readonly string[]);
372
- }
373
- /**
374
- * Thrown by an amendment invariant when the proposed change-set violates
375
- * the declared business rule (e.g. disbursement total not preserved).
376
- * Triggers a full transaction rollback via the existing revert pass.
377
- */
378
- declare class InvariantError extends NoydbError {
379
- constructor(message: string);
380
- }
381
- /**
382
- * Thrown at `withTransactions({ amendment: true })` open if the caller's
383
- * role is not in the guard's allowed amendment roles. Fail-fast: thrown
384
- * before any writes are attempted.
385
- */
386
- declare class AmendmentForbiddenError extends NoydbError {
387
- readonly userId: string;
388
- readonly role: string;
389
- constructor(userId: string, role: string);
390
- }
391
- /**
392
- * Thrown by `listUsersWithEnvelopes` when the vault's user directory
393
- * has been disabled (via `db.setDirectoryEnabled(vault, false)`) and
394
- * the caller's role is neither `owner` nor `admin`. Owner/admin can
395
- * still enumerate users — the toggle is a UX privacy switch, not a
396
- * security boundary.
397
- *
398
- * Honest caveat: this is a UX flag, not a privacy guarantee. The
399
- * envelope ciphertext is still in the store, the keyring file is
400
- * still listed at `_keyring/*`, and anyone with direct store read
401
- * access can count keyrings without going through the hub. See
402
- * `docs/subsystems/user-envelope.md` → "Directory visibility".
403
- */
404
- declare class DirectoryDisabledError extends NoydbError {
405
- readonly vault: string;
406
- constructor(vault: string);
407
- }
408
- /**
409
- * Thrown when a user tries to act at a tier they are not cleared for.
410
- *
411
- * This is the umbrella error for tier write refusals:
412
- * - `put({ tier: N })` when the user's keyring lacks tier-N DEK.
413
- * - `elevate(id, N)` when the caller cannot reach tier N.
414
- *
415
- * Distinct from `TierAccessDeniedError` which covers *read* refusals on
416
- * the invisibility/ghost path.
417
- */
418
- declare class TierNotGrantedError extends NoydbError {
419
- readonly tier: number;
420
- readonly collection: string;
421
- constructor(collection: string, tier: number);
422
- }
423
- /**
424
- * Thrown when an elevated-handle operation runs after the elevation's
425
- * TTL expired. Reads continue at the original tier; only writes
426
- * through the scoped handle flip to throwing once expired.
427
- */
428
- declare class ElevationExpiredError extends NoydbError {
429
- readonly tier: number;
430
- readonly expiresAt: number;
431
- constructor(opts: {
432
- tier: number;
433
- expiresAt: number;
434
- });
435
- }
436
- /**
437
- * Thrown by `vault.elevate(...)` when an elevation is already active
438
- * on the vault. Adopters must `release()` the existing handle before
439
- * starting a new elevation.
440
- */
441
- declare class AlreadyElevatedError extends NoydbError {
442
- readonly activeTier: number;
443
- constructor(activeTier: number);
444
- }
445
- /**
446
- * Thrown when `demote()` is called by someone who is not the original
447
- * elevator and not an owner.
448
- */
449
- declare class TierDemoteDeniedError extends NoydbError {
450
- constructor(id: string, tier: number);
451
- }
452
- /**
453
- * Thrown when `db.delegate()` is called against a user that has no
454
- * keyring in the target vault — the delegation token cannot be
455
- * constructed without the target user's KEK wrap.
456
- */
457
- declare class DelegationTargetMissingError extends NoydbError {
458
- readonly toUser: string;
459
- constructor(toUser: string);
460
- }
461
- /**
462
- * Thrown when a `put()` detects an optimistic concurrency conflict.
463
- *
464
- * NOYDB uses version numbers (`_v`) for optimistic locking. If a `put()`
465
- * is called with `expectedVersion: N` but the stored record is at version
466
- * `M ≠ N`, the write is rejected and the caller must re-read, re-apply their
467
- * change, and retry. The `version` field carries the actual stored version
468
- * so callers can decide whether to retry or surface the conflict to the user.
469
- */
470
- declare class ConflictError extends NoydbError {
471
- /** The actual stored version at the time of conflict. */
472
- readonly version: number;
473
- constructor(version: number, message?: string);
474
- }
475
- /**
476
- * Thrown by `LedgerStore.append()` after exhausting its CAS retry
477
- * budget under multi-writer contention. Two browser tabs, a
478
- * web app + an offline mobile peer, or a server worker pool all
479
- * producing ledger entries against the same vault can race on the
480
- * "read head, write head+1" cycle; the optimistic-CAS retry loop
481
- * resolves the race for `casAtomic: true` stores, but pathological
482
- * contention (or a buggy peer) can still exhaust the budget. When
483
- * that happens, the chain is intact — the failed writer simply
484
- * couldn't claim a slot. Caller's choice whether to retry, queue,
485
- * or surface the failure to the user.
486
- */
487
- declare class LedgerContentionError extends NoydbError {
488
- readonly attempts: number;
489
- constructor(attempts: number);
490
- }
491
- /**
492
- * Thrown when a bundle push is rejected because the remote has been updated
493
- * since the local bundle was last pulled.
494
- *
495
- * Unlike `ConflictError` (per-record), this is a whole-bundle conflict —
496
- * the remote's bundle handle has changed. The caller must pull the new
497
- * bundle, merge, and re-push. `remoteVersion` is the handle of the newer
498
- * remote bundle for use in diagnostics.
499
- */
500
- declare class BundleVersionConflictError extends NoydbError {
501
- /** The bundle handle of the newer remote version that rejected the push. */
502
- readonly remoteVersion: string;
503
- constructor(remoteVersion: string, message?: string);
504
- }
505
- /**
506
- * Thrown when a sync operation (push or pull) fails due to a network error.
507
- *
508
- * NOYDB's offline-first design means network errors are expected during sync.
509
- * Callers should catch `NetworkError`, surface connectivity status in the UI,
510
- * and rely on the `SyncScheduler` to retry when connectivity is restored.
511
- */
512
- declare class NetworkError extends NoydbError {
513
- constructor(message?: string);
514
- }
515
- /**
516
- * Thrown when `collection.get(id)` is called with an ID that does not exist.
517
- *
518
- * NOYDB collections are memory-first, so this error is synchronous and cheap —
519
- * it does not make a network round-trip. Callers that expect the record to be
520
- * absent should use `collection.getOrNull(id)` instead.
521
- */
522
- declare class NotFoundError extends NoydbError {
523
- constructor(message?: string);
524
- }
525
- /**
526
- * Thrown when application-level validation fails before encryption.
527
- *
528
- * Distinct from `SchemaValidationError` (Standard Schema v1 validator)
529
- * and `MissingTranslationError` (i18nText). `ValidationError` is the
530
- * general-purpose validation base — use it for custom guards in `put()`
531
- * hooks or store middleware.
532
- */
533
- declare class ValidationError extends NoydbError {
534
- constructor(message?: string);
535
- }
536
- /**
537
- * Thrown when a Standard Schema v1 validator rejects a record on
538
- * `put()` (input validation) or on read (output validation). Carries
539
- * the raw issue list so callers can render field-level errors.
540
- *
541
- * `direction` distinguishes the two cases:
542
- * - `'input'`: the user passed bad data into `put()`. This is a
543
- * normal error case that application code should handle — typically
544
- * by showing validation messages in the UI.
545
- * - `'output'`: stored data does not match the current schema. This
546
- * indicates a schema drift (the schema was changed without
547
- * migrating the existing records) and should be treated as a bug
548
- * — the application should not swallow it silently.
549
- *
550
- * The `issues` type is deliberately `readonly unknown[]` on this class
551
- * so that `errors.ts` doesn't need to import from `schema.ts` (and
552
- * create a dependency cycle). Callers who know they're holding a
553
- * `SchemaValidationError` can cast to the more precise
554
- * `readonly StandardSchemaV1Issue[]` from `schema.ts`.
555
- */
556
- declare class SchemaValidationError extends NoydbError {
557
- readonly issues: readonly unknown[];
558
- readonly direction: 'input' | 'output';
559
- constructor(message: string, issues: readonly unknown[], direction: 'input' | 'output');
560
- }
561
- /** Base for schema-evolution strategy rejections (#245). */
562
- declare class SchemaUpdateError extends NoydbError {
563
- constructor(code: string, message: string);
564
- }
565
- /** A non-additive schema change was rejected by the `additiveOnly()` strategy. */
566
- declare class NonAdditiveSchemaChangeError extends SchemaUpdateError {
567
- constructor(message: string);
568
- }
569
- /** A schema change was rejected by the `lockSchema()` strategy. */
570
- declare class SchemaLockedError extends SchemaUpdateError {
571
- constructor(message: string);
572
- }
573
- /** Write attempted while a schema cutover fence is up (draining/migrating, or this collection has a pending cutover). */
574
- declare class SchemaFenceError extends SchemaUpdateError {
575
- constructor(message: string);
576
- }
577
- /** Write attempted by a client whose generation snapshot is behind the live fence — reload required. */
578
- declare class MigrationRequiredError extends SchemaUpdateError {
579
- constructor(message: string);
580
- }
581
- /** A coordinated cutover timed out waiting for active clients to quiesce. */
582
- declare class QuiesceTimeoutError extends SchemaUpdateError {
583
- constructor(message: string);
584
- }
585
- /**
586
- * Thrown when `.groupBy().aggregate()` produces more than the hard
587
- * cardinality cap (default 100_000 groups)..
588
- *
589
- * The cap exists because `.groupBy()` materializes one bucket per
590
- * distinct key value in memory, and runaway cardinality — a groupBy
591
- * on a high-uniqueness field like `id` or `createdAt` — is almost
592
- * always a query mistake rather than legitimate use. A hard error is
593
- * better than silent OOM: the consumer sees an actionable message
594
- * naming the field and the observed cardinality, with guidance to
595
- * either narrow the query with `.where()` or accept the ceiling
596
- * override.
597
- *
598
- * A separate one-shot warning fires at 10% of the cap (10_000
599
- * groups) so consumers get a heads-up before the hard error — same
600
- * pattern as `JoinTooLargeError` and the `.join()` row ceiling.
601
- *
602
- * **Not overridable in.** The 100k cap is a fixed constant so
603
- * the failure mode is consistent across the codebase; a
604
- * `{ maxGroups }` override can be added later without a break if a
605
- * real consumer asks.
606
- */
607
- declare class GroupCardinalityError extends NoydbError {
608
- /** The field being grouped on. */
609
- readonly field: string;
610
- /** Observed number of distinct groups at the moment the cap tripped. */
611
- readonly cardinality: number;
612
- /** The cap that was exceeded. */
613
- readonly maxGroups: number;
614
- constructor(field: string, cardinality: number, maxGroups: number);
615
- }
616
- /**
617
- * Thrown in lazy mode when a `.query()` / `.where()` / `.orderBy()` clause
618
- * references a field that does not have a declared index.
619
- *
620
- * Lazy-mode queries only work when every touched field is indexed.
621
- * This is deliberate — silent scan-fallback would hide the performance
622
- * cliff that lazy-mode indexes exist to prevent.
623
- *
624
- * Payload:
625
- * - `collection` — name of the collection queried
626
- * - `touchedFields` — every field referenced by the query (filter + order)
627
- * - `missingFields` — subset of `touchedFields` that have no declared index
628
- */
629
- declare class IndexRequiredError extends NoydbError {
630
- readonly collection: string;
631
- readonly touchedFields: readonly string[];
632
- readonly missingFields: readonly string[];
633
- constructor(args: {
634
- collection: string;
635
- touchedFields: readonly string[];
636
- missingFields: readonly string[];
637
- });
638
- }
639
- /**
640
- * Thrown (or surfaced via the `index:write-partial` event) when one or more
641
- * per-indexed-field side-car writes fail after the main record write has
642
- * already succeeded.
643
- *
644
- * Not thrown out of `.put()` / `.delete()` directly — those succeed when the
645
- * main record succeeds. Instead, `IndexWriteFailureError` instances are collected
646
- * into the session-scoped reconcile queue and emitted on the Collection
647
- * emitter as `index:write-partial`.
648
- *
649
- * Payload:
650
- * - `recordId` — the id of the main record whose side-car writes failed
651
- * - `field` — the indexed field whose side-car write failed
652
- * - `op` — `'put'` or `'delete'`, indicating which mutation was in flight
653
- * - `cause` — the underlying error from the store
654
- */
655
- declare class IndexWriteFailureError extends NoydbError {
656
- readonly recordId: string;
657
- readonly field: string;
658
- readonly op: 'put' | 'delete';
659
- readonly cause: unknown;
660
- constructor(args: {
661
- recordId: string;
662
- field: string;
663
- op: 'put' | 'delete';
664
- cause: unknown;
665
- });
666
- }
667
- /**
668
- * Thrown by `readNoydbBundle()` when the body bytes don't match
669
- * the integrity hash declared in the bundle header — i.e. someone
670
- * modified the bytes between write and read.
671
- *
672
- * Distinct from a generic `Error` (which would be thrown for
673
- * format violations like a missing magic prefix or malformed
674
- * header JSON) so consumers can pattern-match the corruption case
675
- * and handle it differently from a producer bug. A
676
- * `BundleIntegrityError` indicates "the bytes you got are not
677
- * what was written"; a plain `Error` from `parsePrefixAndHeader`
678
- * indicates "what was written wasn't a valid bundle in the first
679
- * place."
680
- *
681
- * Also thrown when decompression fails after the integrity hash
682
- * passed — that's a producer bug (the wrong algorithm byte was
683
- * written) but it surfaces with the same error class because the
684
- * end result is "the body cannot be turned back into a dump."
685
- */
686
- declare class BundleIntegrityError extends NoydbError {
687
- constructor(message: string);
688
- }
689
- /**
690
- * Thrown by `readNoydbBundle` (#197) when the bundle carries
691
- * sealed per-user passphrases but no supplied `SealingKeyProvider`
692
- * has a `.id` (= `pid`) matching the sealed entry's `pid`.
693
- *
694
- * Carries the failing pid + the user id so the recipient can
695
- * surface an actionable prompt:
696
- *
697
- * ```
698
- * BundleSealMismatchError: bundle carries sealed passphrase for user "alice"
699
- * under provider "macos-keychain:com.acme.app/alice@acme.example",
700
- * but no registered provider matches that pid.
701
- * ```
702
- *
703
- * Three resolution paths the message names (per foundation §11.9.4):
704
- *
705
- * 1. Configure a provider matching the pid and retry import.
706
- * 2. Pass `attemptUnsealAcrossProviders: true` to try each
707
- * registered provider regardless of pid.
708
- * 3. Inspect without unsealing — pass no `sealingProviders` to
709
- * receive the sealed entries unmodified for offline analysis.
710
- */
711
- declare class BundleSealMismatchError extends NoydbError {
712
- readonly userId: string;
713
- readonly pid: string;
714
- constructor(userId: string, pid: string);
715
- }
716
- /**
717
- * Thrown when `vault.collection()` is called with a name that is
718
- * reserved for NOYDB internal use (any name starting with `_dict_`).
719
- *
720
- * Dictionary collections are accessed exclusively via
721
- * `vault.dictionary(name)` — attempting to open one as a regular
722
- * collection would bypass the dictionary invariants (ACL, rename
723
- * tracking, reserved-name policy).
724
- */
725
- declare class ReservedCollectionNameError extends NoydbError {
726
- /** The rejected collection name. */
727
- readonly collectionName: string;
728
- constructor(collectionName: string);
729
- }
730
- /**
731
- * Thrown by `DictionaryHandle.get()` and `DictionaryHandle.delete()` when
732
- * the requested key does not exist in the dictionary.
733
- *
734
- * Distinct from `NotFoundError` (which is for data records) so callers
735
- * can distinguish "data record missing" from "dictionary key missing"
736
- * without inspecting error messages.
737
- */
738
- declare class DictKeyMissingError extends NoydbError {
739
- /** The dictionary name. */
740
- readonly dictionaryName: string;
741
- /** The key that was not found. */
742
- readonly key: string;
743
- constructor(dictionaryName: string, key: string);
744
- }
745
- /**
746
- * Thrown by `DictionaryHandle.delete()` in strict mode when the key to
747
- * be deleted is still referenced by one or more records.
748
- *
749
- * The caller must either rename the key first (the only sanctioned
750
- * mass-mutation path) or pass `{ mode: 'warn' }` to skip the check
751
- * (development only).
752
- */
753
- declare class DictKeyInUseError extends NoydbError {
754
- /** The dictionary name. */
755
- readonly dictionaryName: string;
756
- /** The key that is still referenced. */
757
- readonly key: string;
758
- /** Name of the first collection found to reference this key. */
759
- readonly usedBy: string;
760
- /** Number of records in `usedBy` that reference this key. */
761
- readonly count: number;
762
- constructor(dictionaryName: string, key: string, usedBy: string, count: number);
763
- }
764
- /**
765
- * Thrown by `Collection.put()` when an `i18nText` field is missing one
766
- * or more required translations.
767
- *
768
- * The `missing` array names each locale code that was absent from the
769
- * field value. The `field` property names the field so callers can
770
- * render a field-level error message without parsing the string.
771
- */
772
- declare class MissingTranslationError extends NoydbError {
773
- /** The field name whose translation(s) are missing. */
774
- readonly field: string;
775
- /** Locale codes that were required but absent. */
776
- readonly missing: readonly string[];
777
- constructor(field: string, missing: readonly string[], message?: string);
778
- }
779
- /**
780
- * Thrown when reading an `i18nText` field without specifying a locale —
781
- * either at the call site (`get(id, { locale })`) or on the vault
782
- * (`openVault(name, { locale })`).
783
- *
784
- * Also thrown when `resolveI18nText()` exhausts the fallback chain and
785
- * no translation is available for the requested locale.
786
- *
787
- * The `field` property names the field that triggered the error so the
788
- * caller can surface it in the UI.
789
- */
790
- declare class LocaleNotSpecifiedError extends NoydbError {
791
- /** The field name that required a locale. */
792
- readonly field: string;
793
- constructor(field: string, message?: string);
794
- }
795
- /**
796
- * Thrown when a collection has an `i18nText` field with
797
- * `autoTranslate: true` but no `plaintextTranslator` was configured
798
- * on `createNoydb()`.
799
- *
800
- * The error is raised at `put()` time (not at schema construction) so
801
- * the mis-configuration is surfaced by the first write rather than
802
- * silently at startup.
803
- */
804
- declare class TranslatorNotConfiguredError extends NoydbError {
805
- /** The field that requested auto-translation. */
806
- readonly field: string;
807
- /** The collection the put was targeting. */
808
- readonly collection: string;
809
- constructor(field: string, collection: string);
810
- }
811
- /**
812
- * Thrown when `Vault.load()` finds that a backup's hash chain
813
- * doesn't verify, or that its embedded `ledgerHead.hash` doesn't
814
- * match the chain head reconstructed from the loaded entries.
815
- *
816
- * Distinct from `BackupCorruptedError` so callers can choose to
817
- * recover from one but not the other (e.g., a corrupted JSON file is
818
- * unrecoverable; a chain mismatch might mean the backup is from an
819
- * incompatible noy-db version).
820
- */
821
- declare class BackupLedgerError extends NoydbError {
822
- /** First-broken-entry index, if known. */
823
- readonly divergedAt?: number;
824
- constructor(message: string, divergedAt?: number);
825
- }
826
- /**
827
- * Thrown when `Vault.load()` finds that the backup's data
828
- * collection content doesn't match the ledger's recorded
829
- * `payloadHash`es. This is the "envelope was tampered with after
830
- * dump" detection — the chain itself can be intact, but if any
831
- * encrypted record bytes were swapped, this check catches it.
832
- */
833
- declare class BackupCorruptedError extends NoydbError {
834
- /** The (collection, id) pair whose envelope failed the hash check. */
835
- readonly collection: string;
836
- readonly id: string;
837
- constructor(collection: string, id: string, message: string);
838
- }
839
- /**
840
- * Thrown by partition-extraction primitives (#198 epic) when the
841
- * transitive-closure walk fails — e.g. the FK graph is deeper than
842
- * `maxDepth`, signalling a runaway or unexpectedly cyclic graph.
843
- */
844
- declare class PartitionExtractionError extends NoydbError {
845
- constructor(message: string);
846
- }
847
- /**
848
- * Thrown by `adoptPartition` (#207) when the transfer seal can't be
849
- * opened — a wrong/short transfer key (AES-GCM auth-tag failure) or a
850
- * malformed sealed payload.
851
- */
852
- declare class TransferSealError extends NoydbError {
853
- constructor(message: string);
854
- }
855
- /**
856
- * Thrown when an adoption-lifecycle precondition fails — re-adopting a
857
- * partition already consumed in this store (#207), or owner-creation on a
858
- * vault that isn't in the adopted-unowned state (#208).
859
- */
860
- declare class AdoptionStateError extends NoydbError {
861
- constructor(message: string);
862
- }
863
- /** Document-attestation failures: undeclared field-schema, non-owner issue, missing field, signer failure. */
864
- declare class AttestationError extends NoydbError {
865
- constructor(message: string);
866
- }
867
- /**
868
- * Thrown by `resolveSession()` when the session token's `expiresAt`
869
- * timestamp is in the past. The session key is also removed from the
870
- * in-memory store when this is thrown, so retrying with the same sessionId
871
- * will produce `SessionNotFoundError`.
872
- *
873
- * Separate from `SessionNotFoundError` so callers can distinguish between
874
- * "session is gone" (key store cleared, tab reloaded) and "session is
875
- * still in the store but has exceeded its lifetime" (idle timeout, absolute
876
- * timeout, policy-driven expiry). The remediation differs: expired sessions
877
- * should prompt a fresh unlock; not-found sessions may indicate a bug or a
878
- * cross-tab scenario where the session was never established.
879
- */
880
- declare class SessionExpiredError extends NoydbError {
881
- readonly sessionId: string;
882
- constructor(sessionId: string);
883
- }
884
- /**
885
- * Thrown by `resolveSession()` when the session key cannot be found in
886
- * the module-level store. This happens when:
887
- * - The session was explicitly revoked via `revokeSession()`.
888
- * - The JS context was reloaded (tab navigation, page refresh, worker restart).
889
- * - `Noydb.close()` was called (which calls `revokeAllSessions()`).
890
- * - The sessionId is wrong or was generated by a different JS context.
891
- *
892
- * The session token (if the caller holds it) is permanently useless after
893
- * this error — the key is gone and cannot be recovered.
894
- */
895
- declare class SessionNotFoundError extends NoydbError {
896
- readonly sessionId: string;
897
- constructor(sessionId: string);
898
- }
899
- /**
900
- * Thrown when a session policy blocks an operation — for example,
901
- * `requireReAuthFor: ['export']` is set and the caller attempts to
902
- * call `exportStream()` without re-authenticating for this session.
903
- *
904
- * The `operation` field names the specific operation that was blocked
905
- * (e.g. `'export'`, `'grant'`, `'rotate'`) so the caller can surface
906
- * a targeted prompt ("Please re-enter your passphrase to export data").
907
- */
908
- declare class SessionPolicyError extends NoydbError {
909
- readonly operation: string;
910
- constructor(operation: string, message?: string);
911
- }
912
- /**
913
- * Thrown when a `.join()` would exceed its configured row ceiling on
914
- * either side. The ceiling defaults to 50,000 per side and can be
915
- * overridden via the `{ maxRows }` option on `.join()`.
916
- *
917
- * Carries both row counts so the error message can show which side
918
- * tripped the limit (e.g. "left had 60,000 rows, right had 1,200,
919
- * max was 50,000"). The `side` field is machine-readable so test
920
- * code and devtools can match on it without regex-parsing the
921
- * message.
922
- *
923
- * The row ceiling exists because joins are bounded in-memory
924
- * operations over materialized record sets. Consumers whose
925
- * collections genuinely exceed the ceiling should track
926
- * (streaming joins over `scan()`) or filter the left side further
927
- * with `where()` / `limit()` before joining.
928
- */
929
- declare class JoinTooLargeError extends NoydbError {
930
- readonly leftRows: number;
931
- readonly rightRows: number;
932
- readonly maxRows: number;
933
- readonly side: 'left' | 'right';
934
- constructor(opts: {
935
- leftRows: number;
936
- rightRows: number;
937
- maxRows: number;
938
- side: 'left' | 'right';
939
- message: string;
940
- });
941
- }
942
- /**
943
- * Thrown by `.join()` in strict `ref()` mode when a left-side record
944
- * points at a right-side id that does not exist in the target
945
- * collection.
946
- *
947
- * Distinct from `RefIntegrityError` so test code can pattern-match
948
- * on the *read-time* dangling case without catching *write-time*
949
- * integrity violations. Both indicate "ref points at nothing" but
950
- * happen at different lifecycle phases and deserve different
951
- * remediation in documentation: a RefIntegrityError on `put()`
952
- * means the input is invalid; a DanglingReferenceError on `.join()`
953
- * means stored data has drifted and `vault.checkIntegrity()`
954
- * is the right tool to find the full set of orphans.
955
- */
956
- declare class DanglingReferenceError extends NoydbError {
957
- readonly field: string;
958
- readonly target: string;
959
- readonly refId: string;
960
- constructor(opts: {
961
- field: string;
962
- target: string;
963
- refId: string;
964
- message: string;
965
- });
966
- }
967
- /**
968
- * Thrown by {@link sanitizeFilename} when an input filename cannot be
969
- * made safe — NUL byte, empty after normalization, missing
970
- * `opaqueId` for the opaque profile, `..` segment, or a `maxBytes`
971
- * cap too small to hold a single code point.
972
- */
973
- declare class FilenameSanitizationError extends NoydbError {
974
- constructor(message: string);
975
- }
976
- /**
977
- * Thrown when a write target resolves OUTSIDE the requested
978
- * directory after sanitization — the canonical Zip-Slip class. The
979
- * sanitizer's job is to strip path-traversal segments; this error
980
- * is the defense-in-depth fallback at the FS write site.
981
- */
982
- declare class PathEscapeError extends NoydbError {
983
- readonly attempted: string;
984
- readonly targetDir: string;
985
- constructor(opts: {
986
- attempted: string;
987
- targetDir: string;
988
- });
989
- }
990
- /**
991
- * Thrown at vault open if the derivation graph contains a cycle.
992
- * `path` is the offending chain (e.g. `['a', 'b', 'c', 'a']`).
993
- */
994
- declare class DerivationCycleError extends NoydbError {
995
- readonly path: readonly string[];
996
- constructor(path: readonly string[]);
997
- }
998
- /**
999
- * Thrown when a cascade of source → output → source → … exceeds the
1000
- * configured `maxDepth` (default 5).
1001
- */
1002
- declare class DerivationDepthError extends NoydbError {
1003
- readonly limit: number;
1004
- readonly attempted: number;
1005
- constructor(limit: number, attempted: number);
1006
- }
1007
- /**
1008
- * Thrown at registration if a `withDerivation` strategy references an
1009
- * output `collection` that isn't otherwise declared (no schema, no use
1010
- * elsewhere). Surfacing this early catches typos in collection names.
1011
- */
1012
- declare class DerivationOutputUnknownError extends NoydbError {
1013
- readonly collection: string;
1014
- constructor(collection: string);
1015
- }
1016
- /**
1017
- * Thrown when the user's `derive` function returns a value that doesn't
1018
- * match the declared output spec (e.g. wrong shape, wrong key set).
1019
- */
1020
- declare class DerivationOutputShapeError extends NoydbError {
1021
- readonly outputKey: string;
1022
- constructor(outputKey: string, detail: string);
1023
- }
1024
- /**
1025
- * Thrown by array-shape derivations (#200) when the `derive` function
1026
- * returns more rows than the output's `maxFanout` cap. The cap exists
1027
- * to keep dispatch cost bounded — without it a single source-row
1028
- * update could fan out to thousands of derived rows, dominating the
1029
- * write path.
1030
- *
1031
- * Defaults to `maxFanout: 64`. Raise on the output spec for
1032
- * carry-forward expansion cases (e.g. monthly rows across multi-year
1033
- * contracts).
1034
- */
1035
- declare class DerivationCapExceededError extends NoydbError {
1036
- readonly outputKey: string;
1037
- readonly returned: number;
1038
- readonly maxFanout: number;
1039
- constructor(outputKey: string, returned: number, maxFanout: number);
1040
- }
1041
- /**
1042
- * Thrown at vault open if the materialized-view graph contains a
1043
- * cycle. `path` is the offending chain (e.g. `['a-mv', 'b-mv', 'a-mv']`).
1044
- * Detected by the same shared DFS that catches `DerivationCycleError`;
1045
- * surfaces with a distinct error type so consumers can disambiguate.
1046
- */
1047
- declare class MaterializedViewCycleError extends NoydbError {
1048
- readonly path: readonly string[];
1049
- constructor(path: readonly string[]);
1050
- }
1051
- /**
1052
- * Thrown at MV registration if the query references a source
1053
- * collection that isn't declared on the vault. Surfacing this early
1054
- * catches typos in collection names.
1055
- */
1056
- declare class MaterializedViewSourceUnknownError extends NoydbError {
1057
- readonly mvName: string;
1058
- readonly collection: string;
1059
- constructor(mvName: string, collection: string);
1060
- }
1061
- /**
1062
- * Thrown by the MV executor when a refresh produces more rows than
1063
- * the configured ceiling. Default ceiling is 100k rows; override
1064
- * per-MV via `maxRows`. Mirrors `JoinTooLargeError` /
1065
- * `GroupCardinalityError` from the query DSL — the explosion is
1066
- * detected BEFORE writes hit the store, so the source-write
1067
- * transaction can roll back cleanly via strict-mode.
1068
- */
1069
- declare class MaterializedViewTooLargeError extends NoydbError {
1070
- readonly mvName: string;
1071
- readonly expected: number;
1072
- readonly limit: number;
1073
- constructor(mvName: string, expected: number, limit: number);
1074
- }
1075
- /**
1076
- * Thrown by `withMaterializedView()` at registration time when the
1077
- * strategy is structurally malformed. Distinct from
1078
- * `MaterializedViewSourceUnknownError` (the source list is well-formed
1079
- * but names a collection the vault doesn't know) and
1080
- * `MaterializedViewCycleError` (the source graph has a cycle): this
1081
- * error fires before either check, at the moment the spec is being
1082
- * normalized.
1083
- *
1084
- * Today the trigger cases are all about the `query` / `unionSources`
1085
- * dichotomy introduced by #165:
1086
- * - both `query` and `unionSources` were set (mutually exclusive),
1087
- * - neither `query` nor `unionSources` was set,
1088
- * - `unionSources` has fewer than 2 arms,
1089
- * - two arms in `unionSources` reference the same `collection`.
1090
- *
1091
- * The error message is prefixed with `[noy-db] withMaterializedView:`
1092
- * so it's grep-friendly in logs and looks consistent with the existing
1093
- * `ValidationError` messages from the same factory.
1094
- */
1095
- declare class MaterializedViewConfigError extends NoydbError {
1096
- constructor(message: string);
1097
- }
1098
- /**
1099
- * Thrown at vault open when a `withOverlayedView` declaration uses
1100
- * another virtual-overlay name as its `base`. Multi-overlay stacking
1101
- * is a v2 non-goal — the shallow expansion in
1102
- * `QueryDependencyAnalyzer` would truncate at the inner overlay
1103
- * name, leaving downstream MVs silently stale.
1104
- */
1105
- declare class OverlayBaseIsVirtualError extends NoydbError {
1106
- readonly overlayName: string;
1107
- readonly base: string;
1108
- constructor(overlayName: string, base: string);
1109
- }
1110
- /**
1111
- * Thrown at vault open when a `withOverlayedView`'s `overlay`
1112
- * references an unknown collection or an MV-owned collection. The
1113
- * overlay collection is user-writable; MV-owned collections aren't.
1114
- */
1115
- declare class OverlayCollectionUnavailableError extends NoydbError {
1116
- readonly overlayName: string;
1117
- readonly overlay: string;
1118
- constructor(overlayName: string, overlay: string);
1119
- }
1120
- /**
1121
- * Thrown at vault open when a `withOverlayedView`'s virtual `name`
1122
- * collides with an MV output or a concrete source collection.
1123
- */
1124
- declare class OverlayNameCollisionError extends NoydbError {
1125
- readonly overlayName: string;
1126
- constructor(overlayName: string);
1127
- }
1128
- /**
1129
- * Thrown by the virtual overlay's `put(id, record)` when the
1130
- * consumer-supplied `id` doesn't match `rowKey(record)`. Catches
1131
- * fat-finger separator typos that would otherwise silently produce
1132
- * orphaned overlay rows. Direct writes to the underlying overlay
1133
- * collection (bypass the virtual layer) skip this validation.
1134
- */
1135
- declare class OverlayIdMismatchError extends NoydbError {
1136
- readonly actual: string;
1137
- readonly expected: string;
1138
- constructor(actual: string, expected: string);
1139
- }
1140
-
1141
- /**
1142
- * Foreign-key references — the soft-FK mechanism.
1143
- *
1144
- * A collection declares its references as metadata at construction
1145
- * time:
1146
- *
1147
- * ```ts
1148
- * import { ref } from '@noy-db/hub'
1149
- *
1150
- * const invoices = company.collection<Invoice>('invoices', {
1151
- * refs: {
1152
- * clientId: ref('clients'), // default: strict
1153
- * categoryId: ref('categories', 'warn'),
1154
- * parentId: ref('invoices', 'cascade'), // self-reference OK
1155
- * },
1156
- * })
1157
- * ```
1158
- *
1159
- * Three modes:
1160
- *
1161
- * - **strict** — the default. `put()` rejects records whose
1162
- * reference target doesn't exist, and `delete()` of the target
1163
- * rejects if any strict-referencing records still exist.
1164
- * Matches SQL's default FK semantics.
1165
- *
1166
- * - **warn** — both operations succeed unconditionally. Broken
1167
- * references surface only through
1168
- * `vault.checkIntegrity()`, which walks every collection
1169
- * and reports orphans. Use when you want soft validation for
1170
- * imports from messy sources.
1171
- *
1172
- * - **cascade** — `put()` is same as warn. `delete()` of the
1173
- * target deletes every referencing record. Cycles are detected
1174
- * and broken via an in-progress set, so mutual cascades
1175
- * terminate instead of recursing forever.
1176
- *
1177
- * Cross-vault refs are explicitly rejected: if the target
1178
- * name contains a `/`, `ref()` throws `RefScopeError`. Cross-
1179
- * vault refs need an auth story (multi-keyring reads) that
1180
- * doesn't ship — tracked for.
1181
- */
1182
-
1183
- /** The three enforcement modes. Default for new refs is `'strict'`. */
1184
- type RefMode = 'strict' | 'warn' | 'cascade';
1185
- /**
1186
- * Descriptor returned by `ref()`. Collections accept a
1187
- * `Record<string, RefDescriptor>` in their options. The key is the
1188
- * field name on the record (top-level only — dotted paths are out of
1189
- * scope), the value describes which target collection the
1190
- * field references and under what mode.
1191
- *
1192
- * The descriptor carries only plain data so it can be serialized,
1193
- * passed around, and introspected without any class machinery.
1194
- */
1195
- interface RefDescriptor {
1196
- readonly target: string;
1197
- readonly mode: RefMode;
1198
- }
1199
- /**
1200
- * Thrown when a strict reference is violated — either `put()` with a
1201
- * missing target id, or `delete()` of a target that still has
1202
- * strict-referencing records.
1203
- *
1204
- * Carries structured detail so UI code (and a potential future
1205
- * devtools panel) can render "client X cannot be deleted because
1206
- * invoices 1, 2, and 3 reference it" instead of a bare error string.
1207
- */
1208
- declare class RefIntegrityError extends NoydbError {
1209
- readonly collection: string;
1210
- readonly id: string;
1211
- readonly field: string;
1212
- readonly refTo: string;
1213
- readonly refId: string | null;
1214
- constructor(opts: {
1215
- collection: string;
1216
- id: string;
1217
- field: string;
1218
- refTo: string;
1219
- refId: string | null;
1220
- message: string;
1221
- });
1222
- }
1223
- /**
1224
- * Thrown when `ref()` is called with a target name that looks like
1225
- * a cross-vault reference (contains a `/`). Separate error
1226
- * class because the fix is different: RefIntegrityError means "data
1227
- * is wrong"; RefScopeError means "the ref declaration is wrong".
1228
- */
1229
- declare class RefScopeError extends NoydbError {
1230
- constructor(target: string);
1231
- }
1232
- /**
1233
- * Helper constructor. Thin wrapper around the object literal so user
1234
- * code reads like `ref('clients')` instead of `{ target: 'clients',
1235
- * mode: 'strict' }` — this is the only ergonomics reason it exists.
1236
- *
1237
- * Validates the target name eagerly so a misconfigured ref declaration
1238
- * fails at collection construction time, not at the first put.
1239
- */
1240
- declare function ref(target: string, mode?: RefMode): RefDescriptor;
1241
- /**
1242
- * Per-vault registry of reference declarations.
1243
- *
1244
- * The registry is populated by `Collection` constructors (which pass
1245
- * their `refs` option through the Vault) and consulted by the
1246
- * Vault on every `put` / `delete` and by `checkIntegrity`. A
1247
- * single instance lives on the Vault for its lifetime; there's
1248
- * no global state.
1249
- *
1250
- * The data structure is two parallel maps:
1251
- *
1252
- * - `outbound`: `collection → { field → RefDescriptor }` — what
1253
- * refs does `collection` declare? Used on put to check
1254
- * strict-target-exists and on checkIntegrity to walk each
1255
- * collection's outbound refs.
1256
- *
1257
- * - `inbound`: `target → Array<{ collection, field, mode }>` —
1258
- * which collections reference `target`? Used on delete to find
1259
- * the records that might be affected by cascade / strict.
1260
- *
1261
- * The two views are kept in sync by `register()` and never mutated
1262
- * otherwise — refs can't be unregistered at runtime in.
1263
- */
1264
- declare class RefRegistry {
1265
- private readonly outbound;
1266
- private readonly inbound;
1267
- /**
1268
- * Register the refs declared by a single collection. Idempotent in
1269
- * the happy path — calling twice with the same data is a no-op.
1270
- * Calling twice with DIFFERENT data throws, because silent
1271
- * overrides would be confusing ("I changed the ref and it doesn't
1272
- * update" vs "I declared the same collection twice with different
1273
- * refs and the second call won").
1274
- */
1275
- register(collection: string, refs: Record<string, RefDescriptor>): void;
1276
- /** Get the outbound refs declared by a collection (or `{}` if none). */
1277
- getOutbound(collection: string): Record<string, RefDescriptor>;
1278
- /** Get the inbound refs that target a given collection (or `[]`). */
1279
- getInbound(target: string): ReadonlyArray<{
1280
- collection: string;
1281
- field: string;
1282
- mode: RefMode;
1283
- }>;
1284
- /**
1285
- * Iterate every (collection → refs) pair that has at least one
1286
- * declared reference. Used by `checkIntegrity` to walk the full
1287
- * universe of outbound refs without needing to track collection
1288
- * names elsewhere.
1289
- */
1290
- entries(): Array<[string, Record<string, RefDescriptor>]>;
1291
- /** Clear the registry. Test-only escape hatch; never called from production code. */
1292
- clear(): void;
1293
- }
1294
- /**
1295
- * Shape of a single violation reported by `vault.checkIntegrity()`.
1296
- *
1297
- * `refId` is the value we saw in the referencing field — it's the
1298
- * ID we expected to find in `refTo`, but didn't. Left as `unknown`
1299
- * because records are loosely typed at the integrity-check layer.
1300
- */
1301
- interface RefViolation {
1302
- readonly collection: string;
1303
- readonly id: string;
1304
- readonly field: string;
1305
- readonly refTo: string;
1306
- readonly refId: unknown;
1307
- readonly mode: RefMode;
1308
- }
1309
-
1310
- /**
1311
- * Query DSL `.join()` — eager, single-FK, intra-vault joins.
1312
- *
1313
- * resolves a ref()-declared foreign key into an attached
1314
- * right-side record under an alias, using one of two planner paths
1315
- * selected automatically:
1316
- *
1317
- * - **nested-loop** — right-side source exposes `lookupById`, so
1318
- * each left row costs O(1). This is the common path for joins
1319
- * against a Collection, which backs `lookupById` with a Map
1320
- * lookup.
1321
- * - **hash** — right-side has only `snapshot()`. Build a
1322
- * `Map<id, record>` once, probe per left row. Same asymptotic
1323
- * cost for our collections, but the path exists as a fallback
1324
- * for custom QuerySource implementations and as an explicit
1325
- * test-only override via `{ strategy: 'hash' }`.
1326
- *
1327
- * Scope:
1328
- *
1329
- * - Equi-joins on declared `ref()` fields only. Joins on
1330
- * undeclared fields throw at plan time with an actionable error
1331
- * naming the field and collection.
1332
- * - Same-vault only. Cross-vault correlation goes
1333
- * through `queryAcross`; this is an architectural
1334
- * invariant, not a limitation we plan to lift.
1335
- * - Hard row ceiling via `JoinTooLargeError` — default 50k per
1336
- * side, override via `{ maxRows }`. Warns at 80% of the ceiling
1337
- * on the existing warn channel.
1338
- * - Three ref-mode behaviors on dangling refs:
1339
- * strict → `DanglingReferenceError`,
1340
- * warn → attach `null` with a one-shot warning,
1341
- * cascade → attach `null` silently (cascade is a delete-time
1342
- * mode; any dangling refs still present at read time are
1343
- * mid-flight cascades or orphans from earlier, not a DSL error).
1344
- *
1345
- * Partition-awareness seam:
1346
- *
1347
- * Every `JoinLeg` carries a `partitionScope` field that is always
1348
- * `'all'` in. The executor never reads this field.
1349
- * partition-aware joins will start populating it from `where()`
1350
- * predicates on the partition key without changing the planner's
1351
- * external shape — this is the whole reason it exists now.
1352
- *
1353
- * Joins stay OUT of the ledger: reads don't touch `_ledger/`,
1354
- * including joined reads.
1355
- */
1356
-
1357
- /** Planner strategy for a single join leg. Auto-selected unless overridden. */
1358
- type JoinStrategy = 'hash' | 'nested';
1359
- /** Default per-side row ceiling before `.join()` throws `JoinTooLargeError`. */
1360
- declare const DEFAULT_JOIN_MAX_ROWS = 50000;
1361
- /**
1362
- * Internal representation of a single join leg in the query plan.
1363
- *
1364
- * This is the primary place where constraint #1 is honored:
1365
- * every leg carries a `partitionScope` field that is always `'all'`
1366
- * in and is never read by the executor. partition-aware
1367
- * joins will start populating it from `where()` predicates on the
1368
- * partition key without changing the planner's external shape.
1369
- */
1370
- interface JoinLeg {
1371
- /** Field on the left-side record holding the foreign key value. */
1372
- readonly field: string;
1373
- /** Alias key under which the joined right-side record attaches. */
1374
- readonly as: string;
1375
- /** Target collection name, resolved from the `ref()` declaration. */
1376
- readonly target: string;
1377
- /** Ref mode controlling behavior on dangling refs at read time. */
1378
- readonly mode: RefMode;
1379
- /** Manual planner strategy override. `undefined` → auto-select. */
1380
- readonly strategy: JoinStrategy | undefined;
1381
- /** Per-side row ceiling override. `undefined` → DEFAULT_JOIN_MAX_ROWS. */
1382
- readonly maxRows: number | undefined;
1383
- /**
1384
- * Partition scope for future partition-aware joins. Always `'all'`
1385
- * today — the executor never reads this field. Future versions will
1386
- * populate it from `where()` predicates without breaking the
1387
- * planner's external shape. Do not remove even though it looks
1388
- * unused today — that's the whole point of having it.
1389
- */
1390
- readonly partitionScope: 'all' | readonly string[];
1391
- /**
1392
- * When `true`, this is a dictionary join. The executor
1393
- * resolves the left-field value against the dict snapshot and
1394
- * attaches `{ ...labels, key }` rather than a right-side record.
1395
- * `target` holds the dictionary name (not a collection name).
1396
- */
1397
- readonly isDictJoin?: true;
1398
- }
1399
- /**
1400
- * Minimal shape of a joinable right-side record source.
1401
- *
1402
- * Collections implement this structurally via their `QuerySource`;
1403
- * sources without `lookupById` force the hash-join fallback. Kept as
1404
- * a thin interface so tests can wire up plain-object sources without
1405
- * pulling in the full Collection class.
1406
- *
1407
- * The optional `subscribe` is used by `Query.live()` to merge
1408
- * right-side change streams into the live re-run trigger. Sources
1409
- * that omit `subscribe` still work for live joins — they just
1410
- * don't drive re-fires when their right side mutates. Collection
1411
- * implements `subscribe` by hooking into the existing per-
1412
- * vault event emitter.
1413
- */
1414
- interface JoinableSource {
1415
- snapshot(): readonly unknown[];
1416
- lookupById?(id: string): unknown;
1417
- /**
1418
- * Subscribe to mutations on this source. The callback fires
1419
- * AFTER the underlying record set has been updated. Returns an
1420
- * unsubscribe function. Optional — sources without this method
1421
- * cannot trigger live-join re-fires from their side.
1422
- */
1423
- subscribe?(cb: () => void): () => void;
1424
- }
1425
- /**
1426
- * Join resolution context attached to a `Query` when it's constructed
1427
- * from a `Collection`. Holds everything the `.join()` method needs to
1428
- * translate a field name into a target collection + ref mode, and
1429
- * everything the executor needs to read the right side.
1430
- *
1431
- * Kept as a structural interface so `Vault` can implement it
1432
- * without `Query` needing to import `Vault` (circular-import
1433
- * avoid). The Collection wires this up in its `query()` method using
1434
- * the `joinResolver` back-reference the Vault passes in.
1435
- */
1436
- interface JoinContext {
1437
- /** Name of the left-side (owning) collection. */
1438
- readonly leftCollection: string;
1439
- /** Look up a `RefDescriptor` by field name on the left collection. */
1440
- resolveRef(field: string): RefDescriptor | null;
1441
- /** Resolve a right-side source by target collection name. */
1442
- resolveSource(collectionName: string): JoinableSource | null;
1443
- /**
1444
- * Resolve a dictKey join source. Returns a `JoinableSource`
1445
- * whose snapshot exposes `{ key, ...labels }` records, keyed by the
1446
- * stable dictionary key. `null` when the field is not a dictKey.
1447
- *
1448
- * The source is built from the compartment's in-memory dictionary
1449
- * snapshot — same data as `DictionaryHandle.list()`, O(1) per lookup.
1450
- */
1451
- resolveDictSource?(field: string): JoinableSource | null;
1452
- }
1453
- /**
1454
- * Apply every join leg in the plan against a base set of left-side
1455
- * rows. Called by the query executor after `where` / `orderBy` /
1456
- * `offset` / `limit` have narrowed the left set.
1457
- *
1458
- * Each leg attaches a `leg.as` field to every row. Returns a new
1459
- * array of plain objects — the original left rows are not mutated
1460
- * (structural sharing is fine for the inner fields, but the
1461
- * top-level object is a fresh clone so consumers can further mutate
1462
- * safely).
1463
- *
1464
- * **Ordering:** joins run AFTER orderBy / limit / offset in v1.
1465
- * This keeps the planner simple and means queries like "top 10
1466
- * invoices with client" sort and paginate the left side first, then
1467
- * join. Sorting *by* a joined field is out of scope for — users
1468
- * can post-sort the result array in userland or wait for
1469
- * (multi-FK chaining) which can be layered on top.
1470
- *
1471
- * **Multi-FK chaining:** each leg's `maxRows` is enforced
1472
- * against the current left-row count independently. Because
1473
- * joins are equi-joins on the target's primary key (one-to-one or
1474
- * one-to-null), the left row count is constant across legs — no
1475
- * cartesian blowup. The per-leg left-side check is still necessary
1476
- * so that a later leg with a tighter ceiling correctly fires on a
1477
- * query like `.join('a', { maxRows: 100_000 }).join('b', { maxRows: 50 })`,
1478
- * which should throw on the second leg if the left set exceeds 50.
1479
- */
1480
- declare function applyJoins(rows: readonly unknown[], joins: readonly JoinLeg[], context: JoinContext): unknown[];
1481
- /**
1482
- * Test-only: reset the join warning deduplication state between
1483
- * tests. Production code never calls this — the dedup state is
1484
- * intentionally process-scoped so a noisy query doesn't spam the
1485
- * console once per component render.
1486
- */
1487
- declare function resetJoinWarnings(): void;
1488
-
1489
- /**
1490
- * Reactive query primitive — `query.live()`.
1491
- *
1492
- * produces a `LiveQuery<T>` that re-runs the query and
1493
- * updates its `value` whenever any source feeding it (the left
1494
- * collection AND every right-side collection a join leg points at)
1495
- * mutates.
1496
- *
1497
- * Framework-agnostic by design. The Vue layer wraps a `LiveQuery`
1498
- * in a Vue `Ref<T[]>` by subscribing once and copying `value` into
1499
- * the ref on every notification. React/Solid/Svelte adapters do the
1500
- * same with their own primitives. Core never depends on a UI
1501
- * framework.
1502
- *
1503
- * **Error semantics.** A `.live()` query may throw at re-run time —
1504
- * a strict-mode `DanglingReferenceError` is the most common case
1505
- * (a right-side record was deleted out-of-band, leaving a left
1506
- * row's FK pointing at nothing). When the re-run throws, the
1507
- * `LiveQuery` catches the error and stores it in the `error`
1508
- * field; it does NOT propagate the throw out of the source's
1509
- * change handler, because doing so would tear down whatever
1510
- * upstream emitter is dispatching. Listeners check `error` after
1511
- * each notification and render an error state in the UI.
1512
- *
1513
- * **Dedup of right-side subscriptions.** A multi-FK chain that
1514
- * joins the same target twice (e.g.
1515
- * `.join('billingClientId').join('shippingClientId')`, both
1516
- * pointing at `clients`) only subscribes to that target once. We
1517
- * dedup by target collection name, on the assumption that
1518
- * `resolveSource(name)` returns a single subscribable source per
1519
- * vault + name. Vault's `resolveSource` reads from
1520
- * `collectionCache` so this assumption holds.
1521
- *
1522
- * **What .live() does NOT do in v1:**
1523
- * - No granular delta updates — the whole query re-runs on every
1524
- * change. Granular delta tracking is a v2 optimization once
1525
- * the API is stable.
1526
- * - No batching of bursty changes — one event in, one re-run
1527
- * out. Batching with microtask coalescing is a v2 enhancement.
1528
- * - No async notifications — every notification is synchronous
1529
- * within the source's change handler.
1530
- * - No re-planning under live mutations — the planner picks once
1531
- * at subscription time and reuses the same plan for every
1532
- * re-run.
1533
- */
1534
- /**
1535
- * The reactive primitive returned by `Query.live()`.
1536
- *
1537
- * Listeners can read the current `value` snapshot at any time and
1538
- * subscribe to changes via `.subscribe(cb)`. The `error` field
1539
- * carries the most recent re-run error, if any — read it after
1540
- * each notification to render error state.
1541
- *
1542
- * Always call `stop()` when the live query is no longer needed.
1543
- * Without it, the upstream change-stream subscriptions stay live
1544
- * forever and the query keeps re-running on every mutation.
1545
- */
1546
- interface LiveQuery<T> {
1547
- /**
1548
- * Current snapshot of the query result. Updated in place on
1549
- * every upstream change. The reference returned is the same
1550
- * `readonly T[]` array — consumers that want change detection by
1551
- * reference should copy: `const arr = [...live.value]`.
1552
- */
1553
- readonly value: readonly T[];
1554
- /**
1555
- * Most recent re-run error, or `null` on success. Set when the
1556
- * executor throws (e.g. `DanglingReferenceError` in strict mode
1557
- * after a right-side delete). Cleared on the next successful
1558
- * re-run.
1559
- */
1560
- readonly error: Error | null;
1561
- /**
1562
- * Register a notification callback. Fires AFTER `value` and
1563
- * `error` have been updated for a given upstream change.
1564
- * Returns an unsubscribe function.
1565
- *
1566
- * The first call to `subscribe` does NOT fire the callback
1567
- * immediately — call sites that want the initial value should
1568
- * read `live.value` directly before subscribing.
1569
- */
1570
- subscribe(cb: () => void): () => void;
1571
- /**
1572
- * Tear down every upstream subscription and clear the listener
1573
- * set. Idempotent — calling twice is safe. After `stop()`, the
1574
- * query no longer re-runs and `subscribe()` becomes a no-op
1575
- * (the returned unsubscribe is still callable and is also a
1576
- * no-op).
1577
- */
1578
- stop(): void;
1579
- }
1580
- /**
1581
- * Internal subscription handle for an upstream source — left or
1582
- * right side. The contract is just `subscribe(cb): unsubscribe`,
1583
- * matching the existing `QuerySource.subscribe` and the new
1584
- * `JoinableSource.subscribe` (added in ).
1585
- */
1586
- interface LiveUpstream {
1587
- subscribe(cb: () => void): () => void;
1588
- }
1589
- /**
1590
- * Build a LiveQuery from a `recompute` callback (typically the
1591
- * Query's bound `toArray`) and a list of upstream sources to
1592
- * subscribe to.
1593
- *
1594
- * The recompute fires once synchronously to populate the initial
1595
- * value, then re-fires every time any upstream notifies. Errors
1596
- * thrown by recompute are caught and stored in `error` instead of
1597
- * propagating — see the file docstring for the rationale.
1598
- */
1599
- declare function buildLiveQuery<T>(recompute: () => T[], upstreams: readonly LiveUpstream[]): LiveQuery<T>;
1600
-
1601
- /**
1602
- * Chainable, immutable query builder.
1603
- *
1604
- * Each builder operation returns a NEW Query — the underlying plan is never
1605
- * mutated. This makes plans safe to share, cache, and serialize.
1606
- */
1607
-
1608
- interface OrderBy {
1609
- readonly field: string;
1610
- readonly direction: 'asc' | 'desc';
1611
- }
1612
- /**
1613
- * A complete query plan: zero-or-more clauses, optional ordering, pagination,
1614
- * and optional joins.
1615
- *
1616
- * Plans are JSON-serializable as long as no FilterClause is present and no
1617
- * join leg carries a manual `strategy` override (JoinLeg itself is plain
1618
- * data, so it serializes cleanly).
1619
- *
1620
- * Plans are intentionally NOT parametric on T — see `predicate.ts` FilterClause
1621
- * for the variance reasoning. The public `Query<T>` API attaches the type tag.
1622
- */
1623
- interface QueryPlan {
1624
- readonly clauses: readonly Clause[];
1625
- readonly orderBy: readonly OrderBy[];
1626
- readonly limit: number | undefined;
1627
- readonly offset: number;
1628
- /**
1629
- * Zero-or-more join legs to apply after where/orderBy/limit/offset.
1630
- * Each leg attaches a resolved right-side record (or null) under its
1631
- * alias. See `query/join.ts` for the full semantics.
1632
- */
1633
- readonly joins: readonly JoinLeg[];
1634
- }
1635
- /**
1636
- * Source of records that a query executes against.
1637
- *
1638
- * The interface is non-parametric to keep variance friendly: callers cast
1639
- * their typed source (e.g. `QuerySource<Invoice>`) into this opaque shape.
1640
- *
1641
- * `getIndexes` and `lookupById` are optional fast-path hooks. When both are
1642
- * present and a where clause matches an indexed field, the executor uses
1643
- * the index to skip a linear scan. Sources without these methods (or with
1644
- * `getIndexes` returning `null`) always fall back to a linear scan.
1645
- */
1646
- interface QuerySource<T> {
1647
- /** Snapshot of all current records. The query never mutates this array. */
1648
- snapshot(): readonly T[];
1649
- /** Subscribe to mutations; returns an unsubscribe function. */
1650
- subscribe?(cb: () => void): () => void;
1651
- /** Index store for the indexed-fast-path. Optional. */
1652
- getIndexes?(): CollectionIndexes | null;
1653
- /** O(1) record lookup by id, used to materialize index hits. */
1654
- lookupById?(id: string): T | undefined;
1655
- }
1656
- /**
1657
- * The chainable builder. All methods return a new Query — the original
1658
- * remains unchanged. Terminal methods (`toArray`, `first`, `count`,
1659
- * `subscribe`) execute the plan against the source.
1660
- *
1661
- * Type parameter T flows through the public API for ergonomics, but the
1662
- * internal storage uses `unknown` so Collection<T> stays covariant.
1663
- *
1664
- * The optional `joinContext` is attached when the Query is constructed
1665
- * via `Collection.query()` (Collection passes in a context built from
1666
- * the Vault's join resolver). A Query constructed via `new Query`
1667
- * directly — e.g. from tests with a plain-object source — has no
1668
- * joinContext, and calling `.join()` on it throws with an actionable
1669
- * error. See `query/join.ts` for the full design.
1670
- */
1671
- /**
1672
- * Declared deterministic predicate (#153). Carries the consumer's
1673
- * stable `hash` (for function-body identity), the function itself,
1674
- * and is keyed by name when registered on a `Query<T>` via
1675
- * `_withPredicates()`.
1676
- */
1677
- interface DeclaredPredicate {
1678
- hash: string;
1679
- fn: (record: unknown, ctx?: unknown) => boolean;
1680
- }
1681
- declare class Query<T> {
1682
- private readonly source;
1683
- private readonly plan;
1684
- private readonly joinContext;
1685
- private readonly aggregateStrategy;
1686
- private readonly predicates;
1687
- constructor(source: QuerySource<T>, plan?: QueryPlan, joinContext?: JoinContext, aggregateStrategy?: AggregateStrategy, predicates?: ReadonlyMap<string, DeclaredPredicate>);
1688
- /**
1689
- * @internal — accessor for the materialized-view dependency
1690
- * analyzer. Not part of the public API; consumers should use the
1691
- * builder methods, not inspect the plan directly.
1692
- */
1693
- _plan(): QueryPlan;
1694
- /**
1695
- * @internal — accessor for the materialized-view dependency
1696
- * analyzer. Returns the join resolution context (or `undefined` for
1697
- * queries constructed without a Collection backing).
1698
- */
1699
- _joinContext(): JoinContext | undefined;
1700
- /**
1701
- * @internal — clone this Query with a declared-predicate map
1702
- * attached. Used by the materialized-view registry to enable
1703
- * `.wherePredicate(name, ctx?)` for the MV's query callback (#153).
1704
- * Consumers don't call this directly.
1705
- */
1706
- _withPredicates(predicates: ReadonlyMap<string, DeclaredPredicate>): Query<T>;
1707
- /**
1708
- * Filter by a registered deterministic predicate (#153). Requires
1709
- * the Query to have been augmented with a predicates map (typically
1710
- * via the materialized-view registry — bare Queries constructed
1711
- * outside an MV throw on `.wherePredicate()`).
1712
- *
1713
- * `ctx` is an optional opaque value passed verbatim to the predicate
1714
- * function. Both `predicateHash` (from the registration) and a
1715
- * canonical-JSON hash of `ctx` fold into the MV's `queryHash`, so
1716
- * either changing forces refresh on next visit.
1717
- */
1718
- wherePredicate(name: string, ctx?: unknown): Query<T>;
1719
- /** Add a field comparison. Multiple where() calls are AND-combined. */
1720
- where(field: string, op: Operator, value: unknown): Query<T>;
1721
- /**
1722
- * Logical OR group. Pass a callback that builds a sub-query.
1723
- * Each clause inside the callback is OR-combined; the group itself
1724
- * joins the parent plan with AND.
1725
- */
1726
- or(builder: (q: Query<T>) => Query<T>): Query<T>;
1727
- /**
1728
- * Logical AND group. Same shape as `or()` but every clause inside the group
1729
- * must match. Useful for explicit grouping inside a larger OR.
1730
- */
1731
- and(builder: (q: Query<T>) => Query<T>): Query<T>;
1732
- /** Escape hatch: add an arbitrary predicate function. Not serializable. */
1733
- filter(fn: (record: T) => boolean): Query<T>;
1734
- /** Sort by a field. Subsequent calls are tie-breakers. */
1735
- orderBy(field: string, direction?: 'asc' | 'desc'): Query<T>;
1736
- /** Cap the result size. */
1737
- limit(n: number): Query<T>;
1738
- /** Skip the first N matching records (after ordering). */
1739
- offset(n: number): Query<T>;
1740
- /**
1741
- * Resolve a `ref()`-declared foreign key and attach the right-side
1742
- * record under `opts.as`. — eager, single-FK, intra-
1743
- * vault joins.
1744
- *
1745
- * ```ts
1746
- * const rows = invoices.query()
1747
- * .where('status', '==', 'open')
1748
- * .join('clientId', { as: 'client' })
1749
- * .toArray()
1750
- * // → [{ id, amount, client: { id, name, ... } }, ...]
1751
- * ```
1752
- *
1753
- * Preconditions:
1754
- * - The Query must have a `joinContext` (constructed via
1755
- * `Collection.query()`, not `new Query`).
1756
- * - `field` must have a matching `refs: { [field]: ref('<target>') }`
1757
- * declaration on the left collection.
1758
- * - The target collection must be reachable via the vault
1759
- * (either currently open or openable on demand).
1760
- *
1761
- * Strategy:
1762
- * - Nested-loop against `lookupById` when the target source
1763
- * provides it (the common path for Collection targets).
1764
- * - Hash join otherwise, or when `{ strategy: 'hash' }` is
1765
- * explicitly passed for test purposes.
1766
- *
1767
- * Ref-mode semantics on dangling refs (left record has a non-null
1768
- * FK value pointing at a right-side id that doesn't exist):
1769
- * - `strict` → throws `DanglingReferenceError` with the full
1770
- * field / target / refId context.
1771
- * - `warn` → attaches `null` and emits a one-shot warning per
1772
- * unique dangling pair.
1773
- * - `cascade` → attaches `null` silently. Cascade is a
1774
- * delete-time mode; dangling refs visible at read time are
1775
- * either mid-flight cascades or pre-existing orphans, not a
1776
- * DSL-level error.
1777
- *
1778
- * A left-side record whose FK field is `null` / `undefined` is NOT
1779
- * a dangling ref — it's "no reference at all", always allowed
1780
- * regardless of mode.
1781
- *
1782
- * The return type widens `T` with `Record<As, R | null>`. The `R`
1783
- * parameter is optional — supply it explicitly for type-checked
1784
- * access to the joined fields:
1785
- *
1786
- * ```ts
1787
- * invoices.query().join<'client', Client>('clientId', { as: 'client' })
1788
- * // ^^^^^^^^^^^^^^^^^^^ alias literal + right-side type
1789
- * ```
1790
- *
1791
- * Without the generic, the joined field is typed as `unknown`, which
1792
- * still works but requires a cast to access its properties.
1793
- *
1794
- * Joins stay intra-vault by construction — cross-vault
1795
- * correlation goes through `Noydb.queryAcross`, not
1796
- * `.join()`.
1797
- */
1798
- join<As extends string, R = unknown>(field: string, opts: {
1799
- as: As;
1800
- strategy?: JoinStrategy;
1801
- maxRows?: number;
1802
- }): Query<T & Record<As, R | null>>;
1803
- /**
1804
- * Execute the plan and return the matching records. When the plan
1805
- * carries any join legs, they are applied after `where` / `orderBy`
1806
- * / `limit` / `offset` narrow the left set. See the `.join()` doc
1807
- * for the ordering rationale.
1808
- */
1809
- toArray(): T[];
1810
- /** Return the first matching record, or null. Joins are applied. */
1811
- first(): T | null;
1812
- /**
1813
- * Return the number of matching records (after where/filter,
1814
- * before limit). **Joins are NOT applied** — count() reports the
1815
- * left-side cardinality, because joins in are projection-only
1816
- * (they attach an aliased field; they never filter). Running joins
1817
- * here just to discard the aliases would be wasteful, and in strict
1818
- * mode it could throw `DanglingReferenceError` for a call whose
1819
- * intent is purely to count.
1820
- */
1821
- count(): number;
1822
- /**
1823
- * Reduce the matching records through a named set of reducers.
1824
- * the aggregation terminal.
1825
- *
1826
- * ```ts
1827
- * const { total, n, avgAmount } = invoices.query()
1828
- * .where('status', '==', 'open')
1829
- * .aggregate({
1830
- * total: sum('amount'),
1831
- * n: count(),
1832
- * avgAmount: avg('amount'),
1833
- * })
1834
- * .run()
1835
- * ```
1836
- *
1837
- * Returns an `Aggregation<R>` wrapper with two terminals:
1838
- * - `.run(): R` — synchronous one-shot reduction
1839
- * - `.live(): LiveAggregation<R>` — reactive primitive that
1840
- * re-runs the reduction whenever the source notifies of a
1841
- * change. Always call `live.stop()` when finished.
1842
- *
1843
- * The reducer spec is bound here once and reused by both
1844
- * terminals — this is why `.aggregate()` returns a wrapper instead
1845
- * of being a direct terminal. Consumers who only need the static
1846
- * value read `.run()`; consumers wiring a reactive UI read
1847
- * `.live()`.
1848
- *
1849
- * Joins are intentionally NOT applied to aggregations in —
1850
- * the same logic as `.count()`. Joins in are projection-only
1851
- * (they attach an aliased field and never filter), so running
1852
- * them just to throw the aliases away would be wasteful. If you
1853
- * need a reducer that reads a joined field, open an issue —
1854
- * aggregations-across-joins is explicitly out of scope for v1.
1855
- *
1856
- * Every reducer factory accepts an optional `{ seed }` parameter
1857
- * that is plumbed through the protocol but unused by the
1858
- * executor — that's constraint #2. When partition-aware
1859
- * aggregation lands, the seed will carry running state across
1860
- * partition boundaries without an API break.
1861
- */
1862
- aggregate<Spec extends AggregateSpec>(spec: Spec): Aggregation<AggregateResult<Spec>>;
1863
- /**
1864
- * Partition matching records into buckets keyed by a field, then
1865
- * terminate with `.aggregate(spec)` to compute per-bucket
1866
- * reducers..
1867
- *
1868
- * ```ts
1869
- * const byClient = invoices.query()
1870
- * .where('status', '==', 'open')
1871
- * .groupBy('clientId')
1872
- * .aggregate({ total: sum('amount'), n: count() })
1873
- * .run()
1874
- * // → [ { clientId: 'c1', total: 5250, n: 3 }, … ]
1875
- * ```
1876
- *
1877
- * Result rows carry the group key value under the grouping field
1878
- * name plus every reducer output from the spec. Buckets are
1879
- * emitted in first-seen order — consumers who want a specific
1880
- * ordering should `.sort()` downstream.
1881
- *
1882
- * **Cardinality caps:** a one-shot warning fires at 10_000
1883
- * distinct groups; `GroupCardinalityError` throws at 100_000.
1884
- * Grouping on a high-uniqueness field like `id` or `createdAt` is
1885
- * almost always a query mistake — the error message names the
1886
- * field and observed cardinality and suggests narrowing with
1887
- * `.where()` first.
1888
- *
1889
- * **Null / undefined keys:** records with a missing or explicitly
1890
- * `null` group field get their own buckets. `Map`-based
1891
- * partitioning distinguishes `undefined` from `null`, so the two
1892
- * cases do NOT merge. Consumers who want them merged should
1893
- * coalesce upstream with `.filter()`.
1894
- *
1895
- * **Joins are not applied** — same rationale as `.count()` and
1896
- * `.aggregate()`. Joined fields in are projection-only, so
1897
- * running a join inside a grouping pipeline would be wasteful and
1898
- * could trigger `DanglingReferenceError` in strict mode for a
1899
- * call whose intent is purely to bucket-and-reduce. Grouping by
1900
- * a joined field is explicitly out of scope for — file an
1901
- * issue if a real consumer needs it.
1902
- *
1903
- * **Filter clauses (`.filter(fn)`):** grouped queries still
1904
- * support filter clauses in the underlying plan — they run in
1905
- * the same candidate/filter pipeline that `.aggregate()` uses.
1906
- * The performance caveat is the same: filter clauses cost O(N)
1907
- * per record and can't be index-accelerated.
1908
- */
1909
- groupBy<F extends string>(field: F): GroupedQuery<T, F>;
1910
- groupBy<F extends readonly [string, string, ...string[]]>(...fields: F): GroupedQueryN<T, F>;
1911
- /**
1912
- * Re-run the query whenever the source notifies of changes.
1913
- * Returns an unsubscribe function. The callback receives the latest result.
1914
- * Throws if the source does not support subscriptions.
1915
- *
1916
- * **For joined queries, prefer `.live()`** — `subscribe()`
1917
- * only re-fires on LEFT-side changes, so joined data can be
1918
- * stale if the right side mutates between emissions. `.live()`
1919
- * merges change streams from every join target.
1920
- */
1921
- subscribe(cb: (result: T[]) => void): () => void;
1922
- /**
1923
- * Reactive terminal — returns a `LiveQuery<T>` that re-runs the
1924
- * query and updates its `value` whenever any source feeding it
1925
- * mutates..
1926
- *
1927
- * For non-joined queries, `.live()` is a convenience over the
1928
- * existing `.subscribe()` callback shape: a hand-rolled reactive
1929
- * primitive with `value` / `error` fields and a `subscribe(cb)`
1930
- * notification channel. Frame-agnostic — Vue / React / Solid
1931
- * adapters wrap it in their own primitive.
1932
- *
1933
- * For joined queries, `.live()` additionally subscribes to every
1934
- * join target's change stream. Mutations on a right-side
1935
- * collection (insert / update / delete of a client referenced by
1936
- * an invoice) re-fire the live query and re-evaluate every
1937
- * dependent left row. Right-side targets are deduped by
1938
- * collection name, so a chain that joins the same target twice
1939
- * (e.g. billing client + shipping client → both 'clients') only
1940
- * subscribes once.
1941
- *
1942
- * **Ref-mode behavior on right-side disappearance** — matches the
1943
- * eager `.toArray()` contract from :
1944
- * - `strict` → re-run throws `DanglingReferenceError`. The
1945
- * LiveQuery catches the throw, stores it in `live.error`, and
1946
- * notifies listeners (the throw does NOT propagate out of
1947
- * the source's change handler — that would tear down the
1948
- * emitter). Consumers check `live.error` after each
1949
- * notification and render an error state in the UI.
1950
- * - `warn` → joined value flips to `null`; the existing
1951
- * warn-channel deduplication keeps repeated re-runs from
1952
- * spamming the console.
1953
- * - `cascade` → no special handling needed; the cascade-
1954
- * delete mechanism propagates the right-side delete into the
1955
- * left collection on the next tick, and the live query
1956
- * naturally re-fires with the orphaned left rows gone.
1957
- *
1958
- * Always call `live.stop()` when finished — it tears down every
1959
- * upstream subscription. The Vue layer's `onUnmounted` hook
1960
- * should call `stop()` automatically; raw consumers must do it
1961
- * themselves.
1962
- *
1963
- * **Limitations:**
1964
- * - No granular delta updates — the whole query re-runs on
1965
- * every change.
1966
- * - No microtask batching — bursty changes produce one re-run
1967
- * per change.
1968
- * - No re-planning under live mutations — the planner picks
1969
- * once at subscription time and reuses the same plan.
1970
- * - Streaming live joins are deferred.
1971
- */
1972
- live(): LiveQuery<T>;
1973
- /**
1974
- * Return the plan as a JSON-friendly object. FilterClause entries are
1975
- * stripped (their `fn` cannot be serialized) and replaced with
1976
- * { type: 'filter', fn: '[function]' } so devtools can still see them.
1977
- */
1978
- toPlan(): unknown;
1979
- }
1980
- /**
1981
- * Execute a plan against a snapshot of records.
1982
- * Pure function — same input, same output, no side effects.
1983
- *
1984
- * Records are typed as `unknown` because plans are non-parametric; callers
1985
- * cast the return type at the API surface (see `Query.toArray()`).
1986
- */
1987
- declare function executePlan(records: readonly unknown[], plan: QueryPlan): unknown[];
1988
-
1989
- /**
1990
- * Streaming scan builder with filter + aggregate support.
1991
- *
1992
- * `Collection.scan()` now returns a `ScanBuilder<T>` that
1993
- * implements `AsyncIterable<T>` (for existing `for await … of`
1994
- * consumers) AND exposes chainable `.where()` / `.filter()` clauses
1995
- * plus a `.aggregate(spec)` async terminal that reduces the scan
1996
- * stream through the same reducer protocol as `Query.aggregate()`
1997
- *.
1998
- *
1999
- * **Memory model:** O(reducers), not O(records). The aggregate
2000
- * terminal initializes one state per reducer, iterates through the
2001
- * scan one record at a time via `for await`, applies every reducer's
2002
- * `step` per record, and never collects the stream into an array.
2003
- * This is what makes `scan().aggregate()` suitable for collections
2004
- * that don't fit in memory — the bound is a code-level invariant
2005
- * visible in the function body, not a runtime assertion.
2006
- *
2007
- * **Paginated iteration:** the builder holds a `pageProvider`
2008
- * closure that maps `(cursor, limit) → Promise<page>`, plumbed by
2009
- * `Collection.scan()` to `collection.listPage(...)`. The page
2010
- * iterator walks cursors forward until exhaustion, same as the
2011
- * previous async-generator `scan()` did.
2012
- *
2013
- * **Backward compatibility:** existing `for await (const rec of
2014
- * collection.scan()) { … }` code continues to work because
2015
- * `ScanBuilder` implements `[Symbol.asyncIterator]`. The previous
2016
- * signature returned an `AsyncIterableIterator<T>` (which has both
2017
- * `[Symbol.asyncIterator]` and `.next()`). We verified at grep time
2018
- * that no call sites use `.next()` on the scan result directly, so
2019
- * the narrowed interface is safe.
2020
- *
2021
- * **Immutability:** each `.where()` / `.filter()` call returns a
2022
- * fresh builder sharing the same page provider and page size. This
2023
- * lets a base scan be reused for multiple parallel aggregations:
2024
- *
2025
- * ```ts
2026
- * const scan = invoices.scan()
2027
- * const [open, paid] = await Promise.all([
2028
- * scan.where('status', '==', 'open').aggregate({ n: count() }),
2029
- * scan.where('status', '==', 'paid').aggregate({ n: count() }),
2030
- * ])
2031
- * ```
2032
- *
2033
- * Note that each aggregation pays a full scan — there's no shared
2034
- * iteration across the two. Multi-way aggregation in a single pass
2035
- * is out of scope; consumers who need it should build a compound spec
2036
- * and run a single `.aggregate({ openN, paidN })` at the DSL level.
2037
- *
2038
- * **Out of scope for (tracked separately):**
2039
- * - `scan().aggregate().live()` — unbounded scan + change-stream
2040
- * reconciliation is a design problem, not just a code one
2041
- * - `scan().groupBy().aggregate()` — high-cardinality grouping on
2042
- * huge collections would re-introduce the O(groups) memory
2043
- * problem that aggregate fixes
2044
- * - Parallel scan across pages — race-safe page cursor contracts
2045
- * are not in the adapter API yet
2046
- * - `scan().join(...)` — tracked under (streaming join)
2047
- */
2048
-
2049
- /**
2050
- * Page provider — the Collection-shaped hook the builder calls to
2051
- * walk cursors forward. Kept as a structural interface so tests can
2052
- * wire up a synthetic provider without pulling in the full
2053
- * Collection class. Collection's `listPage` matches this shape
2054
- * exactly.
2055
- */
2056
- interface ScanPageProvider<T> {
2057
- listPage(opts: {
2058
- cursor?: string;
2059
- limit?: number;
2060
- }): Promise<{
2061
- items: T[];
2062
- nextCursor: string | null;
2063
- }>;
2064
- }
2065
- /**
2066
- * Chainable streaming scan. Implements `AsyncIterable<T>` for
2067
- * drop-in use with `for await … of`; adds `.where()` / `.filter()`
2068
- * chainable clauses and a `.aggregate(spec)` async terminal.
2069
- *
2070
- * The builder is immutable per operation — each chained call
2071
- * returns a fresh `ScanBuilder` sharing the same page provider and
2072
- * page size. The original builder is never mutated, so it's safe
2073
- * to reuse across multiple parallel consumers.
2074
- */
2075
- declare class ScanBuilder<T> implements AsyncIterable<T> {
2076
- private readonly pageProvider;
2077
- private readonly pageSize;
2078
- private readonly clauses;
2079
- /**
2080
- * Zero-or-more join legs to apply per record as the stream flows.
2081
- * Each leg attaches the resolved right-side record (or null) under
2082
- * its alias. — streaming joins.
2083
- *
2084
- * Joins are evaluated AFTER clauses, so a `where()` filtered-out
2085
- * record never triggers a right-side lookup. This is the same
2086
- * ordering as `Query.toArray()` (clauses first, joins after) and
2087
- * keeps the streaming path from doing wasted work.
2088
- */
2089
- private readonly joins;
2090
- /**
2091
- * Join resolution context. Required for `.join()` to translate a
2092
- * field name into a target collection + ref mode and to resolve
2093
- * the right-side `JoinableSource`. Optional because tests
2094
- * construct ScanBuilder directly with synthetic page providers
2095
- * that don't know about ref() — calling `.join()` without a
2096
- * context throws with an actionable error.
2097
- */
2098
- private readonly joinContext;
2099
- constructor(pageProvider: ScanPageProvider<T>, pageSize?: number, clauses?: readonly Clause[], joins?: readonly JoinLeg[], joinContext?: JoinContext);
2100
- /**
2101
- * Add a field comparison. Runs per record as the scan stream
2102
- * flows through, so non-matching records are dropped before they
2103
- * reach `.aggregate()` or the iteration consumer. Multiple
2104
- * `.where()` calls are AND-combined — same semantics as
2105
- * `Query.where()`.
2106
- *
2107
- * Clauses cannot use the secondary-index fast path here because
2108
- * the scan sources records from the adapter's paginator, not from
2109
- * the in-memory cache where indexes live. Index-accelerated scans
2110
- * are a future optimization — the current implementation
2111
- * evaluates clauses per record in O(1) per clause.
2112
- */
2113
- where(field: string, op: Operator, value: unknown): ScanBuilder<T>;
2114
- /**
2115
- * Escape hatch: add an arbitrary predicate function. Same
2116
- * non-serializable caveat as `Query.filter()` — filter clauses
2117
- * don't round-trip through `toPlan()`. Prefer `.where()` when
2118
- * possible.
2119
- */
2120
- filter(fn: (record: T) => boolean): ScanBuilder<T>;
2121
- /**
2122
- * Resolve a `ref()`-declared foreign key per record as the scan
2123
- * stream flows, attaching the right-side record (or null) under
2124
- * `opts.as`. — streaming joins over `scan()`.
2125
- *
2126
- * ```ts
2127
- * for await (const inv of invoices.scan().join('clientId', { as: 'client' })) {
2128
- * await processInvoice(inv) // inv.client is attached
2129
- * }
2130
- *
2131
- * // Or terminate with .aggregate() for streaming joined aggregation
2132
- * const { total } = await invoices.scan()
2133
- * .where('status', '==', 'open')
2134
- * .join('clientId', { as: 'client' })
2135
- * .aggregate({ total: sum('amount') })
2136
- * ```
2137
- *
2138
- * **The key difference from eager `.join()`:** the LEFT
2139
- * side streams page-by-page from the adapter and is never
2140
- * materialized. Memory ceiling on the left is O(pageSize), not
2141
- * O(rowCount). This is what makes streaming joins suitable for
2142
- * collections that exceed the eager join's 50_000-row ceiling.
2143
- *
2144
- * **Right-side strategy** is auto-selected per leg:
2145
- * - **Indexed** — right source exposes `lookupById`, so each
2146
- * left row costs O(1). This is the common path for
2147
- * Collection right sides, which back `lookupById` with a Map
2148
- * lookup over the in-memory cache. The right collection must
2149
- * be in eager mode (the same constraint as eager join's
2150
- * `querySourceForJoin` from ).
2151
- * - **Hash** — right source has only `snapshot()`. Build a
2152
- * `Map<id, record>` once at iteration start, probe per left
2153
- * row. Same correctness, same per-row cost as the indexed
2154
- * path; the difference is the upfront cost of materializing
2155
- * the right side once.
2156
- *
2157
- * Both strategies hold the right side in memory for the duration
2158
- * of the iteration. The "streaming" property applies to the LEFT
2159
- * side only — true left-and-right streaming joins (where neither
2160
- * side fits in memory) require a sort-merge join planner that's
2161
- * out of scope for.
2162
- *
2163
- * **Ref-mode semantics** match eager `.join()` exactly:
2164
- * - `strict` → throws `DanglingReferenceError` mid-stream
2165
- * when a left record points at a non-existent right id.
2166
- * The throw aborts the async iterator — consumers should
2167
- * wrap the `for await` in try/catch if they want to recover.
2168
- * - `warn` → attaches `null` and emits a one-shot warning
2169
- * per unique dangling pair (deduped via the same warn
2170
- * channel as eager join).
2171
- * - `cascade` → attaches `null` silently. A delete-time mode;
2172
- * dangling refs at read time are mid-flight or pre-existing
2173
- * orphans, not a DSL error.
2174
- *
2175
- * Left records with null/undefined FK values attach `null`
2176
- * regardless of mode — same "no reference at all" policy as
2177
- * eager join and write-time `enforceRefsOnPut`.
2178
- *
2179
- * **Multi-FK chaining** is supported via repeated `.join()`
2180
- * calls: each leg resolves an independent ref. Each leg
2181
- * independently picks its right-side strategy and applies its
2182
- * own ref mode.
2183
- *
2184
- * **Joins are NOT applied** to a `.aggregate()` terminal that
2185
- * doesn't reference joined fields — wait, that's not quite
2186
- * right. The streaming path actually DOES apply joins before
2187
- * `.aggregate()` because the join attaches a field that the
2188
- * spec might reference. Unlike `Query.aggregate()` (which skips
2189
- * joins entirely as a projection-only short-circuit), the
2190
- * streaming aggregation can't know whether the spec touches a
2191
- * joined field, so it always applies joins. Consumers who want
2192
- * unjoined streaming aggregation should leave `.join()` off the
2193
- * chain — the chain is composable for a reason.
2194
- *
2195
- * constraint #1 — every JoinLeg carries `partitionScope:
2196
- * 'all'` plumbed through but never read by. Same seam as
2197
- * eager join.
2198
- */
2199
- join<As extends string, R = unknown>(field: string, opts: {
2200
- as: As;
2201
- }): ScanBuilder<T & Record<As, R | null>>;
2202
- /**
2203
- * Iterate the scan as an async iterable. Walks the page
2204
- * provider's cursors forward until exhaustion, applying every
2205
- * clause per record — only matching records are yielded.
2206
- *
2207
- * Backward-compatible with the previous async-generator `scan()`
2208
- * return type for `for await … of` consumers.
2209
- */
2210
- [Symbol.asyncIterator](): AsyncIterator<T>;
2211
- /**
2212
- * Per-leg right-side resolution state. Built once at iteration
2213
- * start and reused for every left record. Two strategies:
2214
- *
2215
- * - `lookupById`: present when the right source exposes the
2216
- * hook directly (typical Collection right side). Per-row
2217
- * cost is O(1).
2218
- * - `hashByPrimaryKey`: built from `snapshot()` when no
2219
- * lookupById. Per-row cost is O(1) after the upfront O(N)
2220
- * materialization. Same as eager join's hash strategy.
2221
- *
2222
- * `warnedKeys` is the per-leg dedup set for ref-mode 'warn'. We
2223
- * key on `field→target:refId` so the same dangling pair only
2224
- * warns once per iteration. The dedup is per-iteration, not
2225
- * per-process — a long-running scan that re-iterates would warn
2226
- * again, which is the desired behavior (the data may have
2227
- * changed between iterations).
2228
- */
2229
- private buildJoinResolvers;
2230
- /**
2231
- * Resolve a single join leg for one left record and return the
2232
- * left record with the joined field attached under
2233
- * `leg.as`. Pure function over `(left, resolver)`; never
2234
- * mutates the input.
2235
- *
2236
- * Ref-mode dispatch matches eager `applyJoins` from :
2237
- * - null/undefined FK → attach null silently (always allowed)
2238
- * - dangling FK + strict → throw `DanglingReferenceError`
2239
- * - dangling FK + warn → attach null, warn-once per pair
2240
- * - dangling FK + cascade → attach null silently
2241
- */
2242
- private applyOneJoinStreaming;
2243
- /**
2244
- * Reduce the scan stream through a named set of reducers and
2245
- * return the final aggregated shape.
2246
- *
2247
- * Memory is O(reducers): one mutable state slot per spec key.
2248
- * Records flow through the pipeline one at a time via
2249
- * `for await` and are discarded after their `step()` is applied
2250
- * — never collected into an array. This is the distinguishing
2251
- * property from `Query.aggregate()`, which materializes the full
2252
- * match set first.
2253
- *
2254
- * Reuses the same reducer protocol as `Query.aggregate()`,
2255
- * so `count()`, `sum(field)`, `avg(field)`, `min(field)`,
2256
- * `max(field)` all work unchanged. The `{ seed }` parameter
2257
- * plumbing from constraint #2 is honored transparently — the
2258
- * factories ignore it in and the scan executor never
2259
- * touches the per-reducer state construction.
2260
- *
2261
- * **Returns a Promise**, unlike `Query.aggregate().run()` which
2262
- * is synchronous. The scan is inherently async because it walks
2263
- * adapter pages, so the terminal has to be too. Consumers
2264
- * destructure with await:
2265
- *
2266
- * ```ts
2267
- * const { total, n } = await invoices.scan()
2268
- * .where('year', '==', 2025)
2269
- * .aggregate({ total: sum('amount'), n: count() })
2270
- * ```
2271
- *
2272
- * **No `.live()` in.** `scan().aggregate().live()` would
2273
- * require reconciling an unbounded streaming iteration with a
2274
- * change-stream subscription — a design problem, not just a code
2275
- * one. Consumers with huge collections and live needs should
2276
- * narrow with `.where()` enough to fit in the 50k `query()`
2277
- * limit and use `query().aggregate().live()` instead.
2278
- */
2279
- aggregate<Spec extends AggregateSpec>(spec: Spec): Promise<AggregateResult<Spec>>;
2280
- /**
2281
- * Evaluate the clause list against a single record. Linear in
2282
- * the clause count; short-circuits on first false. Clauses on a
2283
- * scan are always re-evaluated per record — no index-accelerated
2284
- * path, because the stream sources records from the adapter
2285
- * paginator, not from the in-memory cache where indexes live.
2286
- */
2287
- private recordMatches;
2288
- }
2289
-
2290
- export { type JoinLeg as $, AmendmentForbiddenError as A, BackupCorruptedError as B, ConflictError as C, DictKeyInUseError as D, DecryptionError as E, FieldFrozenError as F, DelegationTargetMissingError as G, DirectoryDisabledError as H, InvariantError as I, ElevationExpiredError as J, ExportCapabilityError as K, LocaleNotSpecifiedError as L, MissingTranslationError as M, NoydbError as N, OverlayBaseIsVirtualError as O, PartitionExtractionError as P, Query as Q, ReservedCollectionNameError as R, SessionExpiredError as S, TranslatorNotConfiguredError as T, FilenameSanitizationError as U, GroupCardinalityError as V, ImportCapabilityError as W, IndexRequiredError as X, IndexWriteFailureError as Y, InvalidKeyError as Z, type JoinContext as _, DictKeyMissingError as a, type JoinStrategy as a0, JoinTooLargeError as a1, type JoinableSource as a2, KeyringCorruptError as a3, KeyringExpiredError as a4, LedgerContentionError as a5, type LiveQuery as a6, type LiveUpstream as a7, MigrationRequiredError as a8, NetworkError as a9, StoreCapabilityError as aA, TamperedError as aB, TierDemoteDeniedError as aC, TierNotGrantedError as aD, ValidationError as aE, applyJoins as aF, buildLiveQuery as aG, executePlan as aH, ref as aI, resetJoinWarnings as aJ, NoAccessError as aa, NonAdditiveSchemaChangeError as ab, NotFoundError as ac, type OrderBy as ad, PathEscapeError as ae, PeriodClosedError as af, PermissionDeniedError as ag, PrivilegeEscalationError as ah, type QueryPlan as ai, type QuerySource as aj, QuiesceTimeoutError as ak, ReadOnlyAtInstantError as al, ReadOnlyError as am, ReadOnlyFrameError as an, type RefDescriptor as ao, RefIntegrityError as ap, type RefMode as aq, RefRegistry as ar, RefScopeError as as, type RefViolation as at, ScanBuilder as au, type ScanPageProvider as av, SchemaFenceError as aw, SchemaLockedError as ax, SchemaUpdateError as ay, SchemaValidationError as az, SessionNotFoundError as b, SessionPolicyError as c, RecordLockedError as d, DerivationCapExceededError as e, DerivationCycleError as f, DerivationDepthError as g, DerivationOutputShapeError as h, DerivationOutputUnknownError as i, OverlayCollectionUnavailableError as j, OverlayIdMismatchError as k, OverlayNameCollisionError as l, AttestationError as m, AdoptionStateError as n, BackupLedgerError as o, BundleIntegrityError as p, BundleSealMismatchError as q, BundleVersionConflictError as r, TransferSealError as s, MaterializedViewConfigError as t, MaterializedViewCycleError as u, MaterializedViewSourceUnknownError as v, MaterializedViewTooLargeError as w, AlreadyElevatedError as x, DEFAULT_JOIN_MAX_ROWS as y, DanglingReferenceError as z };