@noy-db/hub 0.3.0 → 0.4.0-pre.1

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 (375) hide show
  1. package/dist/aggregate/index.js +4 -4
  2. package/dist/api-IQFZJSQO.js +20 -0
  3. package/dist/as/index.js +11 -11
  4. package/dist/attestation/index.js +18 -18
  5. package/dist/{backup-BJ57IKAO.js → backup-LU2DTZTI.js} +11 -11
  6. package/dist/blobs/index.js +12 -12
  7. package/dist/broker/index.js +12 -12
  8. package/dist/bundle/index.js +26 -74
  9. package/dist/bundle/index.js.map +1 -1
  10. package/dist/by/index.js +2 -2
  11. package/dist/cargo/index.js +41 -22
  12. package/dist/chunk-2IALOXZS.js +24 -0
  13. package/dist/chunk-2IALOXZS.js.map +1 -0
  14. package/dist/{chunk-EVVGJDRQ.js → chunk-2MUZ3LY6.js} +3 -3
  15. package/dist/{chunk-NWSGI5C7.js → chunk-2P7EGNKF.js} +3 -3
  16. package/dist/{chunk-ZAJAVEXY.js → chunk-2PCAVW2I.js} +2 -2
  17. package/dist/{chunk-HTJQYHZP.js → chunk-3ELCWU56.js} +2 -2
  18. package/dist/{chunk-X7QBD67R.js → chunk-3PF6CRDT.js} +136 -114
  19. package/dist/chunk-3PF6CRDT.js.map +1 -0
  20. package/dist/{chunk-J2ZX2XUV.js → chunk-3SV2EPMN.js} +5 -5
  21. package/dist/{chunk-FUG4SFN3.js → chunk-3U3FBR7O.js} +2 -2
  22. package/dist/{chunk-VFUPHI2Z.js → chunk-4BRCIYFG.js} +6 -6
  23. package/dist/{chunk-SNZ6URZZ.js → chunk-5OI6BR4H.js} +7 -7
  24. package/dist/{chunk-B3HJYUOF.js → chunk-5WZXVULX.js} +2 -2
  25. package/dist/{chunk-LASZKVMO.js → chunk-6B4DYGWO.js} +3 -3
  26. package/dist/{chunk-ZJ2AK4V7.js → chunk-6HPG2YNX.js} +2 -2
  27. package/dist/{chunk-5M5DVGV7.js → chunk-6HY2X62D.js} +2 -2
  28. package/dist/{chunk-QRB7NAOJ.js → chunk-6NQMXTYC.js} +2 -2
  29. package/dist/{chunk-RIX4V2TB.js → chunk-6XE5TMPR.js} +3 -3
  30. package/dist/{chunk-BDVFPG6Y.js → chunk-7CI6CP7Z.js} +5 -5
  31. package/dist/{chunk-VLFCJYTL.js → chunk-7O3AYBC7.js} +63 -10
  32. package/dist/chunk-7O3AYBC7.js.map +1 -0
  33. package/dist/{chunk-454JXE57.js → chunk-A5BDDEXK.js} +10 -170
  34. package/dist/chunk-A5BDDEXK.js.map +1 -0
  35. package/dist/{chunk-FHS2HQSH.js → chunk-A7JJLVGH.js} +11 -8
  36. package/dist/chunk-A7JJLVGH.js.map +1 -0
  37. package/dist/{chunk-FM3G3NOY.js → chunk-BGK233EA.js} +83 -6
  38. package/dist/chunk-BGK233EA.js.map +1 -0
  39. package/dist/{chunk-OSDB5WW3.js → chunk-BMQWTQZ4.js} +11 -11
  40. package/dist/{chunk-W22IKJE2.js → chunk-BOKIKJJB.js} +2 -2
  41. package/dist/{chunk-CRI4OUV4.js → chunk-CBSY2N76.js} +2 -2
  42. package/dist/{chunk-2NVOWNI3.js → chunk-CCOP5XDW.js} +4 -4
  43. package/dist/{chunk-CDUQTA3Z.js → chunk-DDATL6PU.js} +7 -7
  44. package/dist/{chunk-RCVJZMFE.js → chunk-DDHM2TLX.js} +4 -4
  45. package/dist/{chunk-PN2XMATY.js → chunk-DRWBEDYO.js} +2 -2
  46. package/dist/{chunk-XDYREZWE.js → chunk-DVUZMT2W.js} +12 -8
  47. package/dist/{chunk-XDYREZWE.js.map → chunk-DVUZMT2W.js.map} +1 -1
  48. package/dist/{chunk-T2FFWNPK.js → chunk-EGCRBCNA.js} +3 -3
  49. package/dist/{chunk-VZRODIM3.js → chunk-F6T6L2UK.js} +4 -4
  50. package/dist/chunk-FH52K7EG.js +50 -0
  51. package/dist/chunk-FH52K7EG.js.map +1 -0
  52. package/dist/{chunk-EXK7QRWF.js → chunk-G6EQYAL6.js} +5 -5
  53. package/dist/{chunk-F64IRYG3.js → chunk-GQNGCEP5.js} +2 -2
  54. package/dist/{chunk-6JTIAGHD.js → chunk-GULTLPFB.js} +3 -3
  55. package/dist/chunk-GULTLPFB.js.map +1 -0
  56. package/dist/{chunk-ZUODRVHY.js → chunk-GVZQ4NAM.js} +2 -2
  57. package/dist/{chunk-3B5VVCNY.js → chunk-GWKAVKHI.js} +2 -2
  58. package/dist/{chunk-SLFHQTTW.js → chunk-GYYCX5K6.js} +5 -5
  59. package/dist/{chunk-CIE2BASH.js → chunk-HOONYZY2.js} +2 -2
  60. package/dist/{chunk-EYZ6IQ6X.js → chunk-HPUWOVR7.js} +5 -5
  61. package/dist/{chunk-IL6POWCW.js → chunk-IM3QVF53.js} +6 -6
  62. package/dist/{chunk-NJ4EOKMB.js → chunk-IRQY7IR5.js} +4 -4
  63. package/dist/{chunk-3QCRBHCY.js → chunk-ISMV2QVG.js} +2 -2
  64. package/dist/{chunk-HB3RFQSC.js → chunk-IY23KFNZ.js} +3 -3
  65. package/dist/chunk-J6Q7UVQE.js +248 -0
  66. package/dist/chunk-J6Q7UVQE.js.map +1 -0
  67. package/dist/{chunk-6CRIV7DE.js → chunk-JBBSYJHP.js} +2 -2
  68. package/dist/{chunk-MEFJPTZ4.js → chunk-JRBNCUNT.js} +3 -3
  69. package/dist/{chunk-4VNQOLML.js → chunk-JVBO4SZL.js} +2 -2
  70. package/dist/{chunk-I6GALP6E.js → chunk-JZWWLLVY.js} +6 -6
  71. package/dist/{chunk-RYCTDFUX.js → chunk-KUIB4B5Q.js} +2 -2
  72. package/dist/{chunk-HDQIIUPH.js → chunk-KUPKLSX5.js} +3 -3
  73. package/dist/{chunk-5O3XF4DV.js → chunk-KWVJAOIN.js} +4 -4
  74. package/dist/{chunk-3LQ2YKO4.js → chunk-LB6OH6K2.js} +2 -2
  75. package/dist/{chunk-AUSTCW2X.js → chunk-LOF2W3JU.js} +8 -8
  76. package/dist/{chunk-JNAI2HN2.js → chunk-LSASLXGC.js} +1 -1
  77. package/dist/chunk-LSASLXGC.js.map +1 -0
  78. package/dist/{chunk-K5IMOGHB.js → chunk-M75ZZHSR.js} +2 -2
  79. package/dist/{chunk-GTGPO5KW.js → chunk-MQ6WOPSY.js} +5 -5
  80. package/dist/{chunk-4CTHCN4J.js → chunk-MTQPRQHB.js} +4 -4
  81. package/dist/{chunk-UNFPPVNI.js → chunk-N55W7KUL.js} +2 -2
  82. package/dist/{chunk-JKJOGPZN.js → chunk-N6WF5PKC.js} +2 -2
  83. package/dist/{chunk-6T2SCQRU.js → chunk-O7WJ47EF.js} +4 -4
  84. package/dist/{chunk-JIF24JPM.js → chunk-OF75ACKS.js} +9 -9
  85. package/dist/{chunk-GKEWXIV5.js → chunk-ONTBCHCP.js} +2 -2
  86. package/dist/{chunk-4JBYV75E.js → chunk-PK6QCH2C.js} +5 -5
  87. package/dist/{chunk-6QTNZJBS.js → chunk-PT37L5DV.js} +3 -3
  88. package/dist/{chunk-EVX47VBM.js → chunk-QDPZWTN2.js} +2 -2
  89. package/dist/chunk-RA5VTXXG.js +173 -0
  90. package/dist/chunk-RA5VTXXG.js.map +1 -0
  91. package/dist/{chunk-QLWMEXCT.js → chunk-RDXW3OBQ.js} +2 -2
  92. package/dist/{chunk-Q5VNKNE5.js → chunk-RM2XV574.js} +3 -3
  93. package/dist/{chunk-ERJ7FU55.js → chunk-RND5ZPNP.js} +3 -3
  94. package/dist/{chunk-JZUV47FZ.js → chunk-RTEK4C4I.js} +2 -2
  95. package/dist/{chunk-KSKBRKGJ.js → chunk-S3BFKGET.js} +84 -6
  96. package/dist/chunk-S3BFKGET.js.map +1 -0
  97. package/dist/{chunk-5YOLBEQ6.js → chunk-S6Q37VGE.js} +2 -2
  98. package/dist/{chunk-HDMEGAQE.js → chunk-SMGEYW6G.js} +127 -8
  99. package/dist/chunk-SMGEYW6G.js.map +1 -0
  100. package/dist/{chunk-E5ZQT5KX.js → chunk-SMIRGMS7.js} +2 -2
  101. package/dist/chunk-T36RFODW.js +180 -0
  102. package/dist/chunk-T36RFODW.js.map +1 -0
  103. package/dist/{chunk-EQO2UVP4.js → chunk-T6GU5PPZ.js} +6 -6
  104. package/dist/{chunk-LXEXBTKL.js → chunk-TAGR72IR.js} +4 -4
  105. package/dist/{chunk-YFXZEAYK.js → chunk-TOPYT5U5.js} +6 -6
  106. package/dist/{chunk-MV43JSJF.js → chunk-UBNCR3YK.js} +4 -4
  107. package/dist/{chunk-ZICD77GM.js → chunk-UC2ETWF3.js} +2 -2
  108. package/dist/{chunk-XWZVFISC.js → chunk-UFEVO57O.js} +6 -6
  109. package/dist/{chunk-NR5LT5RY.js → chunk-UNCOC7QH.js} +7 -7
  110. package/dist/{chunk-R4ROFEYC.js → chunk-VAIS3SOM.js} +2 -2
  111. package/dist/{chunk-VN3DBQAU.js → chunk-VCBHAE4R.js} +2 -2
  112. package/dist/{chunk-M4CV6BRT.js → chunk-VEALDPHW.js} +2 -2
  113. package/dist/{chunk-BIOUI4HL.js → chunk-W2OG6JOL.js} +1 -1
  114. package/dist/{chunk-BIOUI4HL.js.map → chunk-W2OG6JOL.js.map} +1 -1
  115. package/dist/{chunk-7DSTRQIJ.js → chunk-WEYZTLXN.js} +2 -2
  116. package/dist/{chunk-CAF6WOK7.js → chunk-WNGGJWF7.js} +2 -2
  117. package/dist/{chunk-IU6SNYX6.js → chunk-YJV2UZ7H.js} +5 -5
  118. package/dist/{chunk-RZ5SVOYR.js → chunk-YTGDPCPW.js} +2 -2
  119. package/dist/{chunk-DLG74CNB.js → chunk-ZEQWCBCM.js} +7 -19
  120. package/dist/chunk-ZEQWCBCM.js.map +1 -0
  121. package/dist/classified/index.js +5 -5
  122. package/dist/{classified-marker-CZKA6ITE.js → classified-marker-WQVIJAW2.js} +3 -3
  123. package/dist/collection-facade-MJXSC3Q6.js +44 -0
  124. package/dist/{computed-ZIQTYTDI.js → computed-DSMPXG2Y.js} +3 -3
  125. package/dist/consent/index.js +9 -9
  126. package/dist/{public-envelope-B4KNWVUA.js → cover-B5SJDHR3.js} +25 -5
  127. package/dist/{dead-filter-ESOBZZP5.js → dead-filter-2A7IAJ3D.js} +2 -2
  128. package/dist/delegation-A5A75KQO.js +25 -0
  129. package/dist/derivations/index.js +12 -12
  130. package/dist/derive-HJSMH7RA.js +21 -0
  131. package/dist/{enclave-AP3I5W7O.js → enclave-7MW6ZGXW.js} +11 -9
  132. package/dist/executor-AXE4XMLT.js +26 -0
  133. package/dist/executor-KGNLJD6M.js +9 -0
  134. package/dist/executor-XGIS6CR7.js +9 -0
  135. package/dist/export-accessible-VVBJM3MM.js +23 -0
  136. package/dist/extract-partition-LGGBTQET.js +38 -0
  137. package/dist/{fanout-sidecar-A765THMX.js → fanout-sidecar-WDYQ77VB.js} +9 -9
  138. package/dist/find-YS6XWB46.js +11 -0
  139. package/dist/forget/index.js +9 -9
  140. package/dist/guards/index.js +6 -6
  141. package/dist/history/index.js +12 -12
  142. package/dist/i18n/index.js +14 -14
  143. package/dist/index.d.ts +6 -3
  144. package/dist/index.js +140 -117
  145. package/dist/index.js.map +1 -1
  146. package/dist/indexing/index.js +2 -2
  147. package/dist/issue-LSR5PS6H.js +19 -0
  148. package/dist/kernel/enclave/index.d.ts +1 -1
  149. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +8 -0
  150. package/dist/kernel/errors.d.ts +10 -5
  151. package/dist/kernel/noydb.d.ts +21 -11
  152. package/dist/kernel/types.d.ts +53 -6
  153. package/dist/kernel/vault.d.ts +10 -6
  154. package/dist/{ledger-GFBKVPV4.js → ledger-33BC4TR7.js} +11 -11
  155. package/dist/liberate-GBSAYLPJ.js +24 -0
  156. package/dist/{link-set-Z7Q2ASFX.js → link-set-QK22TDEX.js} +11 -11
  157. package/dist/materialized-views/index.js +19 -18
  158. package/dist/noydb-MTUBMWFE.js +70 -0
  159. package/dist/on/index.js +9 -9
  160. package/dist/overlay-views/index.js +4 -4
  161. package/dist/periods/index.js +19 -17
  162. package/dist/pod/index.js +13 -11
  163. package/dist/{policy-Z3RUAIY2.js → policy-NAHB2TUT.js} +5 -5
  164. package/dist/portability/index.js +8 -8
  165. package/dist/{post-register-JTH76BLY.js → post-register-JVTMJ6OW.js} +6 -6
  166. package/dist/query/index.js +10 -8
  167. package/dist/register-X462DNDM.js +23 -0
  168. package/dist/registry-3XMCT7MQ.js +18 -0
  169. package/dist/registry-KHD2I3M2.js +19 -0
  170. package/dist/registry-NPOWJHC4.js +9 -0
  171. package/dist/request-withdrawal-U7K3JTMY.js +31 -0
  172. package/dist/{reveal-DIBHLUZX.js → reveal-LGBOM2BO.js} +6 -6
  173. package/dist/revoke-OCWDSWRQ.js +24 -0
  174. package/dist/satellites/index.js +1 -1
  175. package/dist/sealed-record/index.js +12 -12
  176. package/dist/{seed-Q6M2IZFL.js → seed-PWK45HDF.js} +11 -11
  177. package/dist/session/index.js +9 -9
  178. package/dist/shadow/index.js +2 -2
  179. package/dist/share-link/index.d.ts +19 -0
  180. package/dist/share-link/index.js +201 -0
  181. package/dist/share-link/index.js.map +1 -0
  182. package/dist/share-link/share-link.d.ts +123 -0
  183. package/dist/signer-3YFBLZRN.js +25 -0
  184. package/dist/snapshots/index.js +10 -10
  185. package/dist/{stale-OSQ7J3AA.js → stale-FJED42DM.js} +10 -10
  186. package/dist/storage-W3GURVFU.js +23 -0
  187. package/dist/{store-coordination-provider-64OEZFGS.js → store-coordination-provider-APODTV4W.js} +3 -3
  188. package/dist/sync/index.js +10 -9
  189. package/dist/sync/index.js.map +1 -1
  190. package/dist/team/index.js +16 -15
  191. package/dist/tiers/index.js +10 -10
  192. package/dist/to/index.js +1 -1
  193. package/dist/tx/index.js +3 -3
  194. package/dist/util/index.js +1 -1
  195. package/dist/{verify-ZASTRNPR.js → verify-26Y5GNMK.js} +5 -5
  196. package/dist/via/i18n/policy.d.ts +1 -1
  197. package/dist/{walk-SVNDIZ62.js → walk-XS3PKM6I.js} +11 -11
  198. package/dist/with/index.js +11 -11
  199. package/dist/with-audit/periods/periods.d.ts +1 -16
  200. package/dist/with-audit/periods/window.d.ts +16 -0
  201. package/dist/with-cargo/index.d.ts +6 -0
  202. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +15 -0
  203. package/dist/with-formula/materialized-views/index.d.ts +1 -1
  204. package/dist/with-formula/materialized-views/registry.d.ts +29 -0
  205. package/dist/with-formula/materialized-views/types.d.ts +81 -0
  206. package/dist/with-formula/materialized-views/with-materialized-view.d.ts +9 -5
  207. package/dist/with-party/directory/cover/custom.d.ts +34 -0
  208. package/dist/with-party/directory/cover/index.d.ts +19 -0
  209. package/dist/with-party/directory/cover/schema.d.ts +39 -0
  210. package/dist/with-party/directory/cover/storage.d.ts +71 -0
  211. package/dist/with-party/directory/cover/types.d.ts +149 -0
  212. package/dist/with-party/team/noydb-facade.d.ts +1 -1
  213. package/dist/with-party/team/sync-period-scope.d.ts +78 -0
  214. package/dist/with-party/team/sync.d.ts +13 -0
  215. package/dist/with-pod/bundle.d.ts +9 -7
  216. package/dist/with-pod/format.d.ts +8 -4
  217. package/dist/with-pod/index.d.ts +2 -1
  218. package/dist/withdraw-accessible-Y3B2535F.js +28 -0
  219. package/package.json +7 -3
  220. package/dist/api-ZGS6LCOF.js +0 -20
  221. package/dist/chunk-454JXE57.js.map +0 -1
  222. package/dist/chunk-4NXKCLLQ.js +0 -97
  223. package/dist/chunk-4NXKCLLQ.js.map +0 -1
  224. package/dist/chunk-6JTIAGHD.js.map +0 -1
  225. package/dist/chunk-DLG74CNB.js.map +0 -1
  226. package/dist/chunk-FHS2HQSH.js.map +0 -1
  227. package/dist/chunk-FM3G3NOY.js.map +0 -1
  228. package/dist/chunk-HDMEGAQE.js.map +0 -1
  229. package/dist/chunk-JNAI2HN2.js.map +0 -1
  230. package/dist/chunk-KSKBRKGJ.js.map +0 -1
  231. package/dist/chunk-VLFCJYTL.js.map +0 -1
  232. package/dist/chunk-WXSYDNBT.js +0 -39
  233. package/dist/chunk-WXSYDNBT.js.map +0 -1
  234. package/dist/chunk-X3YYQWOQ.js +0 -155
  235. package/dist/chunk-X3YYQWOQ.js.map +0 -1
  236. package/dist/chunk-X7QBD67R.js.map +0 -1
  237. package/dist/collection-facade-TLWIPI76.js +0 -44
  238. package/dist/delegation-W7ZV2322.js +0 -25
  239. package/dist/derive-H2BJTLUI.js +0 -21
  240. package/dist/executor-KGWTNEQD.js +0 -9
  241. package/dist/executor-OVEXR6RT.js +0 -9
  242. package/dist/executor-UNEH5ZYH.js +0 -25
  243. package/dist/export-accessible-PCMXSUZS.js +0 -23
  244. package/dist/extract-partition-SWHFSYJO.js +0 -38
  245. package/dist/find-N6345CNT.js +0 -11
  246. package/dist/issue-5OKB6I2R.js +0 -19
  247. package/dist/liberate-3VDOT4KO.js +0 -24
  248. package/dist/noydb-ZCJOYBDI.js +0 -68
  249. package/dist/register-VAHONCID.js +0 -23
  250. package/dist/registry-7MLVD3VO.js +0 -19
  251. package/dist/registry-EPKPD5SM.js +0 -18
  252. package/dist/registry-P5T7PS2U.js +0 -9
  253. package/dist/request-withdrawal-TI3A5WPS.js +0 -31
  254. package/dist/revoke-FDRD6GRW.js +0 -24
  255. package/dist/signer-MUWEIUI6.js +0 -25
  256. package/dist/storage-MVFCGEQE.js +0 -23
  257. package/dist/with-party/directory/public-envelope/index.d.ts +0 -12
  258. package/dist/with-party/directory/public-envelope/schema.d.ts +0 -24
  259. package/dist/with-party/directory/public-envelope/storage.d.ts +0 -59
  260. package/dist/with-party/directory/public-envelope/types.d.ts +0 -80
  261. package/dist/withdraw-accessible-WZIEVWSR.js +0 -28
  262. /package/dist/{api-ZGS6LCOF.js.map → api-IQFZJSQO.js.map} +0 -0
  263. /package/dist/{backup-BJ57IKAO.js.map → backup-LU2DTZTI.js.map} +0 -0
  264. /package/dist/{chunk-EVVGJDRQ.js.map → chunk-2MUZ3LY6.js.map} +0 -0
  265. /package/dist/{chunk-NWSGI5C7.js.map → chunk-2P7EGNKF.js.map} +0 -0
  266. /package/dist/{chunk-ZAJAVEXY.js.map → chunk-2PCAVW2I.js.map} +0 -0
  267. /package/dist/{chunk-HTJQYHZP.js.map → chunk-3ELCWU56.js.map} +0 -0
  268. /package/dist/{chunk-J2ZX2XUV.js.map → chunk-3SV2EPMN.js.map} +0 -0
  269. /package/dist/{chunk-FUG4SFN3.js.map → chunk-3U3FBR7O.js.map} +0 -0
  270. /package/dist/{chunk-VFUPHI2Z.js.map → chunk-4BRCIYFG.js.map} +0 -0
  271. /package/dist/{chunk-SNZ6URZZ.js.map → chunk-5OI6BR4H.js.map} +0 -0
  272. /package/dist/{chunk-B3HJYUOF.js.map → chunk-5WZXVULX.js.map} +0 -0
  273. /package/dist/{chunk-LASZKVMO.js.map → chunk-6B4DYGWO.js.map} +0 -0
  274. /package/dist/{chunk-ZJ2AK4V7.js.map → chunk-6HPG2YNX.js.map} +0 -0
  275. /package/dist/{chunk-5M5DVGV7.js.map → chunk-6HY2X62D.js.map} +0 -0
  276. /package/dist/{chunk-QRB7NAOJ.js.map → chunk-6NQMXTYC.js.map} +0 -0
  277. /package/dist/{chunk-RIX4V2TB.js.map → chunk-6XE5TMPR.js.map} +0 -0
  278. /package/dist/{chunk-BDVFPG6Y.js.map → chunk-7CI6CP7Z.js.map} +0 -0
  279. /package/dist/{chunk-OSDB5WW3.js.map → chunk-BMQWTQZ4.js.map} +0 -0
  280. /package/dist/{chunk-W22IKJE2.js.map → chunk-BOKIKJJB.js.map} +0 -0
  281. /package/dist/{chunk-CRI4OUV4.js.map → chunk-CBSY2N76.js.map} +0 -0
  282. /package/dist/{chunk-2NVOWNI3.js.map → chunk-CCOP5XDW.js.map} +0 -0
  283. /package/dist/{chunk-CDUQTA3Z.js.map → chunk-DDATL6PU.js.map} +0 -0
  284. /package/dist/{chunk-RCVJZMFE.js.map → chunk-DDHM2TLX.js.map} +0 -0
  285. /package/dist/{chunk-PN2XMATY.js.map → chunk-DRWBEDYO.js.map} +0 -0
  286. /package/dist/{chunk-T2FFWNPK.js.map → chunk-EGCRBCNA.js.map} +0 -0
  287. /package/dist/{chunk-VZRODIM3.js.map → chunk-F6T6L2UK.js.map} +0 -0
  288. /package/dist/{chunk-EXK7QRWF.js.map → chunk-G6EQYAL6.js.map} +0 -0
  289. /package/dist/{chunk-F64IRYG3.js.map → chunk-GQNGCEP5.js.map} +0 -0
  290. /package/dist/{chunk-ZUODRVHY.js.map → chunk-GVZQ4NAM.js.map} +0 -0
  291. /package/dist/{chunk-3B5VVCNY.js.map → chunk-GWKAVKHI.js.map} +0 -0
  292. /package/dist/{chunk-SLFHQTTW.js.map → chunk-GYYCX5K6.js.map} +0 -0
  293. /package/dist/{chunk-CIE2BASH.js.map → chunk-HOONYZY2.js.map} +0 -0
  294. /package/dist/{chunk-EYZ6IQ6X.js.map → chunk-HPUWOVR7.js.map} +0 -0
  295. /package/dist/{chunk-IL6POWCW.js.map → chunk-IM3QVF53.js.map} +0 -0
  296. /package/dist/{chunk-NJ4EOKMB.js.map → chunk-IRQY7IR5.js.map} +0 -0
  297. /package/dist/{chunk-3QCRBHCY.js.map → chunk-ISMV2QVG.js.map} +0 -0
  298. /package/dist/{chunk-HB3RFQSC.js.map → chunk-IY23KFNZ.js.map} +0 -0
  299. /package/dist/{chunk-6CRIV7DE.js.map → chunk-JBBSYJHP.js.map} +0 -0
  300. /package/dist/{chunk-MEFJPTZ4.js.map → chunk-JRBNCUNT.js.map} +0 -0
  301. /package/dist/{chunk-4VNQOLML.js.map → chunk-JVBO4SZL.js.map} +0 -0
  302. /package/dist/{chunk-I6GALP6E.js.map → chunk-JZWWLLVY.js.map} +0 -0
  303. /package/dist/{chunk-RYCTDFUX.js.map → chunk-KUIB4B5Q.js.map} +0 -0
  304. /package/dist/{chunk-HDQIIUPH.js.map → chunk-KUPKLSX5.js.map} +0 -0
  305. /package/dist/{chunk-5O3XF4DV.js.map → chunk-KWVJAOIN.js.map} +0 -0
  306. /package/dist/{chunk-3LQ2YKO4.js.map → chunk-LB6OH6K2.js.map} +0 -0
  307. /package/dist/{chunk-AUSTCW2X.js.map → chunk-LOF2W3JU.js.map} +0 -0
  308. /package/dist/{chunk-K5IMOGHB.js.map → chunk-M75ZZHSR.js.map} +0 -0
  309. /package/dist/{chunk-GTGPO5KW.js.map → chunk-MQ6WOPSY.js.map} +0 -0
  310. /package/dist/{chunk-4CTHCN4J.js.map → chunk-MTQPRQHB.js.map} +0 -0
  311. /package/dist/{chunk-UNFPPVNI.js.map → chunk-N55W7KUL.js.map} +0 -0
  312. /package/dist/{chunk-JKJOGPZN.js.map → chunk-N6WF5PKC.js.map} +0 -0
  313. /package/dist/{chunk-6T2SCQRU.js.map → chunk-O7WJ47EF.js.map} +0 -0
  314. /package/dist/{chunk-JIF24JPM.js.map → chunk-OF75ACKS.js.map} +0 -0
  315. /package/dist/{chunk-GKEWXIV5.js.map → chunk-ONTBCHCP.js.map} +0 -0
  316. /package/dist/{chunk-4JBYV75E.js.map → chunk-PK6QCH2C.js.map} +0 -0
  317. /package/dist/{chunk-6QTNZJBS.js.map → chunk-PT37L5DV.js.map} +0 -0
  318. /package/dist/{chunk-EVX47VBM.js.map → chunk-QDPZWTN2.js.map} +0 -0
  319. /package/dist/{chunk-QLWMEXCT.js.map → chunk-RDXW3OBQ.js.map} +0 -0
  320. /package/dist/{chunk-Q5VNKNE5.js.map → chunk-RM2XV574.js.map} +0 -0
  321. /package/dist/{chunk-ERJ7FU55.js.map → chunk-RND5ZPNP.js.map} +0 -0
  322. /package/dist/{chunk-JZUV47FZ.js.map → chunk-RTEK4C4I.js.map} +0 -0
  323. /package/dist/{chunk-5YOLBEQ6.js.map → chunk-S6Q37VGE.js.map} +0 -0
  324. /package/dist/{chunk-E5ZQT5KX.js.map → chunk-SMIRGMS7.js.map} +0 -0
  325. /package/dist/{chunk-EQO2UVP4.js.map → chunk-T6GU5PPZ.js.map} +0 -0
  326. /package/dist/{chunk-LXEXBTKL.js.map → chunk-TAGR72IR.js.map} +0 -0
  327. /package/dist/{chunk-YFXZEAYK.js.map → chunk-TOPYT5U5.js.map} +0 -0
  328. /package/dist/{chunk-MV43JSJF.js.map → chunk-UBNCR3YK.js.map} +0 -0
  329. /package/dist/{chunk-ZICD77GM.js.map → chunk-UC2ETWF3.js.map} +0 -0
  330. /package/dist/{chunk-XWZVFISC.js.map → chunk-UFEVO57O.js.map} +0 -0
  331. /package/dist/{chunk-NR5LT5RY.js.map → chunk-UNCOC7QH.js.map} +0 -0
  332. /package/dist/{chunk-R4ROFEYC.js.map → chunk-VAIS3SOM.js.map} +0 -0
  333. /package/dist/{chunk-VN3DBQAU.js.map → chunk-VCBHAE4R.js.map} +0 -0
  334. /package/dist/{chunk-M4CV6BRT.js.map → chunk-VEALDPHW.js.map} +0 -0
  335. /package/dist/{chunk-7DSTRQIJ.js.map → chunk-WEYZTLXN.js.map} +0 -0
  336. /package/dist/{chunk-CAF6WOK7.js.map → chunk-WNGGJWF7.js.map} +0 -0
  337. /package/dist/{chunk-IU6SNYX6.js.map → chunk-YJV2UZ7H.js.map} +0 -0
  338. /package/dist/{chunk-RZ5SVOYR.js.map → chunk-YTGDPCPW.js.map} +0 -0
  339. /package/dist/{classified-marker-CZKA6ITE.js.map → classified-marker-WQVIJAW2.js.map} +0 -0
  340. /package/dist/{collection-facade-TLWIPI76.js.map → collection-facade-MJXSC3Q6.js.map} +0 -0
  341. /package/dist/{computed-ZIQTYTDI.js.map → computed-DSMPXG2Y.js.map} +0 -0
  342. /package/dist/{delegation-W7ZV2322.js.map → cover-B5SJDHR3.js.map} +0 -0
  343. /package/dist/{dead-filter-ESOBZZP5.js.map → dead-filter-2A7IAJ3D.js.map} +0 -0
  344. /package/dist/{derive-H2BJTLUI.js.map → delegation-A5A75KQO.js.map} +0 -0
  345. /package/dist/{enclave-AP3I5W7O.js.map → derive-HJSMH7RA.js.map} +0 -0
  346. /package/dist/{executor-KGWTNEQD.js.map → enclave-7MW6ZGXW.js.map} +0 -0
  347. /package/dist/{executor-OVEXR6RT.js.map → executor-AXE4XMLT.js.map} +0 -0
  348. /package/dist/{executor-UNEH5ZYH.js.map → executor-KGNLJD6M.js.map} +0 -0
  349. /package/dist/{export-accessible-PCMXSUZS.js.map → executor-XGIS6CR7.js.map} +0 -0
  350. /package/dist/{extract-partition-SWHFSYJO.js.map → export-accessible-VVBJM3MM.js.map} +0 -0
  351. /package/dist/{find-N6345CNT.js.map → extract-partition-LGGBTQET.js.map} +0 -0
  352. /package/dist/{fanout-sidecar-A765THMX.js.map → fanout-sidecar-WDYQ77VB.js.map} +0 -0
  353. /package/dist/{issue-5OKB6I2R.js.map → find-YS6XWB46.js.map} +0 -0
  354. /package/dist/{ledger-GFBKVPV4.js.map → issue-LSR5PS6H.js.map} +0 -0
  355. /package/dist/{liberate-3VDOT4KO.js.map → ledger-33BC4TR7.js.map} +0 -0
  356. /package/dist/{link-set-Z7Q2ASFX.js.map → liberate-GBSAYLPJ.js.map} +0 -0
  357. /package/dist/{noydb-ZCJOYBDI.js.map → link-set-QK22TDEX.js.map} +0 -0
  358. /package/dist/{policy-Z3RUAIY2.js.map → noydb-MTUBMWFE.js.map} +0 -0
  359. /package/dist/{public-envelope-B4KNWVUA.js.map → policy-NAHB2TUT.js.map} +0 -0
  360. /package/dist/{post-register-JTH76BLY.js.map → post-register-JVTMJ6OW.js.map} +0 -0
  361. /package/dist/{register-VAHONCID.js.map → register-X462DNDM.js.map} +0 -0
  362. /package/dist/{registry-7MLVD3VO.js.map → registry-3XMCT7MQ.js.map} +0 -0
  363. /package/dist/{registry-EPKPD5SM.js.map → registry-KHD2I3M2.js.map} +0 -0
  364. /package/dist/{registry-P5T7PS2U.js.map → registry-NPOWJHC4.js.map} +0 -0
  365. /package/dist/{request-withdrawal-TI3A5WPS.js.map → request-withdrawal-U7K3JTMY.js.map} +0 -0
  366. /package/dist/{reveal-DIBHLUZX.js.map → reveal-LGBOM2BO.js.map} +0 -0
  367. /package/dist/{revoke-FDRD6GRW.js.map → revoke-OCWDSWRQ.js.map} +0 -0
  368. /package/dist/{seed-Q6M2IZFL.js.map → seed-PWK45HDF.js.map} +0 -0
  369. /package/dist/{signer-MUWEIUI6.js.map → signer-3YFBLZRN.js.map} +0 -0
  370. /package/dist/{stale-OSQ7J3AA.js.map → stale-FJED42DM.js.map} +0 -0
  371. /package/dist/{storage-MVFCGEQE.js.map → storage-W3GURVFU.js.map} +0 -0
  372. /package/dist/{store-coordination-provider-64OEZFGS.js.map → store-coordination-provider-APODTV4W.js.map} +0 -0
  373. /package/dist/{verify-ZASTRNPR.js.map → verify-26Y5GNMK.js.map} +0 -0
  374. /package/dist/{walk-SVNDIZ62.js.map → walk-XS3PKM6I.js.map} +0 -0
  375. /package/dist/{withdraw-accessible-WZIEVWSR.js.map → withdraw-accessible-Y3B2535F.js.map} +0 -0
@@ -1,23 +1,34 @@
1
1
  import {
2
2
  SyncScheduler
3
3
  } from "./chunk-VQNJ7UZL.js";
4
+ import {
5
+ PERIODS_COLLECTION,
6
+ PERIOD_ARCHIVES_COLLECTION,
7
+ PERIOD_FREEZES_COLLECTION,
8
+ PERIOD_TARGET_PURGES_COLLECTION,
9
+ periodExclusiveUpperBound
10
+ } from "./chunk-2IALOXZS.js";
11
+ import {
12
+ envelopeBodySize
13
+ } from "./chunk-DVUZMT2W.js";
4
14
  import {
5
15
  isDeleteMarker,
6
16
  isTombstoneShape
7
- } from "./chunk-7DSTRQIJ.js";
17
+ } from "./chunk-WEYZTLXN.js";
8
18
  import {
9
19
  bufferToBase64,
10
20
  decrypt,
11
21
  derivePresenceKey,
12
22
  encrypt,
13
23
  generateIV
14
- } from "./chunk-CIE2BASH.js";
24
+ } from "./chunk-HOONYZY2.js";
15
25
  import {
16
26
  NOYDB_SYNC_VERSION
17
- } from "./chunk-JNAI2HN2.js";
27
+ } from "./chunk-LSASLXGC.js";
18
28
  import {
19
- ConflictError
20
- } from "./chunk-BIOUI4HL.js";
29
+ ConflictError,
30
+ ValidationError
31
+ } from "./chunk-W2OG6JOL.js";
21
32
 
22
33
  // src/with-party/team/presence.ts
23
34
  var PresenceHandle = class {
@@ -226,6 +237,51 @@ var PresenceHandle = class {
226
237
  }
227
238
  };
228
239
 
240
+ // src/with-party/team/sync-period-scope.ts
241
+ var PERIOD_SUMMARY_COLLECTIONS = [
242
+ PERIODS_COLLECTION,
243
+ PERIOD_FREEZES_COLLECTION,
244
+ PERIOD_ARCHIVES_COLLECTION,
245
+ PERIOD_TARGET_PURGES_COLLECTION
246
+ ];
247
+ var SHAPE_MSG = "pull: `periods` must be an array of closed-period names, or `{ current: true }`.";
248
+ function validatePeriodsOption(periods) {
249
+ if (Array.isArray(periods)) {
250
+ for (const p of periods) {
251
+ if (typeof p !== "string" || p.length === 0) throw new ValidationError(SHAPE_MSG);
252
+ }
253
+ return;
254
+ }
255
+ if (typeof periods === "object" && periods !== null && periods.current === true && Object.keys(periods).length === 1) {
256
+ return;
257
+ }
258
+ throw new ValidationError(SHAPE_MSG);
259
+ }
260
+ function buildPeriodScope(option, records) {
261
+ const closed = records.filter((r) => r.kind === "closed").map((r) => ({ name: r.name, bound: periodExclusiveUpperBound(r.endDate) })).sort((a, b) => a.bound.localeCompare(b.bound));
262
+ let windows;
263
+ if (Array.isArray(option)) {
264
+ windows = option.map((name) => {
265
+ const idx = closed.findIndex((c) => c.name === name);
266
+ if (idx < 0) {
267
+ const other = records.find((r) => r.name === name);
268
+ throw new ValidationError(
269
+ other ? `pull: period "${name}" is "${other.kind}" \u2014 only closed periods have a backfill window; use \`{ current: true }\` for the open period.` : `pull: no closed period named "${name}" in this vault's _periods index.`
270
+ );
271
+ }
272
+ return { lower: idx > 0 ? closed[idx - 1].bound : null, upper: closed[idx].bound };
273
+ });
274
+ } else {
275
+ windows = [{ lower: closed.length > 0 ? closed[closed.length - 1].bound : null, upper: null }];
276
+ }
277
+ return (envelope) => {
278
+ if (isTombstoneShape(envelope) || isDeleteMarker(envelope)) return true;
279
+ return windows.some(
280
+ (w) => (w.lower === null || envelope._ts >= w.lower) && (w.upper === null || envelope._ts < w.upper)
281
+ );
282
+ };
283
+ }
284
+
229
285
  // src/with-party/team/sync.ts
230
286
  var SyncEngine = class {
231
287
  local;
@@ -288,6 +344,20 @@ var SyncEngine = class {
288
344
  setReservedDictExpander(expander) {
289
345
  this.reservedDictExpander = expander;
290
346
  }
347
+ /** #807: vault-injected source of decrypted period records — resolves the `_ts` windows a
348
+ * `pull({ periods })` scopes to. Re-read AFTER the summaries phase, so a fresh device's
349
+ * freshly pulled `_periods` index is what the windows are computed from. `undefined` on a
350
+ * standalone engine that was never vault-attached (period-scoped pull then throws). */
351
+ periodPullSource;
352
+ /** Wire the period-window source (#807). Same injection pattern as `setReservedLookupSource`. */
353
+ setPeriodPullSource(source) {
354
+ this.periodPullSource = source;
355
+ }
356
+ /** #807: KPI accumulator `applyRemote` feeds during a period-scoped `pull()` — pointed at the
357
+ * active phase's counters (summaries → records) and cleared before pull returns. Approximate
358
+ * by design: a push interleaved mid-pull on the same engine would attribute its converge
359
+ * applies to the open phase; the counters are a download-budget KPI, not an audit source. */
360
+ pullByteSink = null;
291
361
  constructor(opts) {
292
362
  this.local = opts.local;
293
363
  this.remote = opts.remote;
@@ -490,11 +560,52 @@ var SyncEngine = class {
490
560
  /** Pull remote records to local adapter. Accepts optional `PullOptions` for partial sync. */
491
561
  async pull(options) {
492
562
  await this.ensureLoaded();
493
- this.graphBatchController?.begin();
494
563
  let pulled = 0;
495
564
  const conflicts = [];
496
565
  const erasures = [];
497
566
  const errors = [];
567
+ let periodScope = null;
568
+ let phases = null;
569
+ if (options?.periods !== void 0) {
570
+ validatePeriodsOption(options.periods);
571
+ if (!this.periodPullSource) {
572
+ throw new ValidationError(
573
+ "period-scoped pull requires a vault-attached sync engine (open the vault via createNoydb + openVault)."
574
+ );
575
+ }
576
+ phases = { summaries: { records: 0, bytes: 0 }, records: { records: 0, bytes: 0 } };
577
+ let remotePeriodCount = 0;
578
+ this.pullByteSink = phases.summaries;
579
+ try {
580
+ for (const collName of PERIOD_SUMMARY_COLLECTIONS) {
581
+ for (const id of await this.remote.list(this.vault, collName)) {
582
+ if (collName === PERIODS_COLLECTION) remotePeriodCount++;
583
+ try {
584
+ const remoteEnvelope = await this.remote.get(this.vault, collName, id);
585
+ if (!remoteEnvelope) continue;
586
+ const localEnvelope = await this.local.get(this.vault, collName, id);
587
+ if (!localEnvelope || remoteEnvelope._v > localEnvelope._v) {
588
+ await this.applyRemote(collName, id, remoteEnvelope);
589
+ pulled++;
590
+ }
591
+ } catch (err) {
592
+ errors.push(err instanceof Error ? err : new Error(String(err)));
593
+ }
594
+ }
595
+ }
596
+ } finally {
597
+ this.pullByteSink = null;
598
+ }
599
+ const periodRecords = await this.periodPullSource.periods();
600
+ if (remotePeriodCount > 0 && periodRecords.length === 0) {
601
+ throw new ValidationError(
602
+ "period-scoped pull: the vault holds _periods records but none are readable \u2014 enable the periods service (`periodsStrategy: withPeriods()`) so pull can resolve the period windows."
603
+ );
604
+ }
605
+ periodScope = buildPeriodScope(options.periods, periodRecords);
606
+ }
607
+ this.graphBatchController?.begin();
608
+ if (phases) this.pullByteSink = phases.records;
498
609
  const expanded = options?.collections ? this.pairExpander?.(options.collections) ?? options.collections : null;
499
610
  const filter = expanded ? /* @__PURE__ */ new Set([...expanded, ...this.reservedDictExpander?.(expanded) ?? []]) : null;
500
611
  try {
@@ -507,6 +618,9 @@ var SyncEngine = class {
507
618
  if (options?.modifiedSince && remoteEnvelope._ts <= options.modifiedSince && !isTombstoneShape(remoteEnvelope) && !isDeleteMarker(remoteEnvelope)) {
508
619
  continue;
509
620
  }
621
+ if (periodScope !== null && !periodScope(remoteEnvelope)) {
622
+ continue;
623
+ }
510
624
  try {
511
625
  const localEnvelope = await this.local.get(this.vault, collName, id);
512
626
  const remoteIsTombstone = isTombstoneShape(remoteEnvelope);
@@ -609,9 +723,10 @@ var SyncEngine = class {
609
723
  try {
610
724
  await this.persistMeta();
611
725
  } finally {
726
+ this.pullByteSink = null;
612
727
  await this.graphBatchController?.flush();
613
728
  }
614
- const result = { pulled, conflicts, errors, erasures };
729
+ const result = { pulled, conflicts, errors, erasures, ...phases !== null ? { phases } : {} };
615
730
  this.emitter.emit("sync:pull", result);
616
731
  return result;
617
732
  }
@@ -776,6 +891,10 @@ var SyncEngine = class {
776
891
  * (sync delete ≠ forget: freshness only, no shred/residue channel on the receiving side). */
777
892
  async applyRemote(collection, id, envelope) {
778
893
  await this.local.put(this.vault, collection, id, envelope);
894
+ if (this.pullByteSink !== null) {
895
+ this.pullByteSink.records++;
896
+ this.pullByteSink.bytes += envelopeBodySize(envelope);
897
+ }
779
898
  const action = isTombstoneShape(envelope) || isDeleteMarker(envelope) ? "delete" : "put";
780
899
  await this.cacheInvalidator?.(collection, id, action);
781
900
  }
@@ -954,4 +1073,4 @@ export {
954
1073
  SyncEngine,
955
1074
  SyncTransaction
956
1075
  };
957
- //# sourceMappingURL=chunk-HDMEGAQE.js.map
1076
+ //# sourceMappingURL=chunk-SMGEYW6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-party/team/presence.ts","../src/with-party/team/sync-period-scope.ts","../src/with-party/team/sync.ts","../src/with-party/team/sync-transaction.ts"],"sourcesContent":["/**\n * Presence handle — real-time awareness of who is viewing/editing a collection.\n * encrypted ephemeral channel keyed by collection DEK via HKDF.\n *\n * The presence key is derived from the collection DEK so:\n * - The adapter never learns user identities from presence payloads.\n * - Presence rotates automatically when the DEK rotates (revoked users\n * can no longer participate after a DEK rotation).\n *\n * Two transport strategies:\n * 1. **Pub/sub** (real-time): used when the adapter implements\n * `presencePublish` and `presenceSubscribe`.\n * 2. **Storage-poll** (fallback): presence records are written to a\n * reserved `_presence_<collection>` collection on the sync adapter\n * (if available) or local adapter, and polled periodically.\n */\n\nimport type { NoydbStore, PresencePeer } from '../../kernel/types.js'\nimport { encrypt, decrypt, generateIV, bufferToBase64, derivePresenceKey, type EnclaveKey } from '../../kernel/enclave/index.js'\n\n/** Options for constructing a PresenceHandle. @internal */\nexport interface PresenceHandleOpts {\n /** Local adapter for storage-poll fallback. */\n adapter: NoydbStore\n /** Remote (sync) adapter — preferred for broadcasting presence if available. */\n syncAdapter?: NoydbStore\n /** Vault name — used as part of the channel and storage key. */\n vault: string\n /** Collection name — used as HKDF `info` and channel suffix. */\n collectionName: string\n /** Calling user's ID, embedded unencrypted in storage records. */\n userId: string\n /** Whether encryption is active. When false, presence payloads are stored as JSON. */\n encrypted: boolean\n /** Callback that resolves the collection DEK (used to derive the presence key). */\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n /** How long (ms) before a peer's presence is considered stale. Default: 30_000. */\n staleMs?: number\n /** Poll interval (ms) for the storage-poll fallback. Default: 5_000. */\n pollIntervalMs?: number\n}\n\n/**\n * Internal storage envelope for the storage-poll fallback.\n * Written to `_presence_<collection>` as `{ userId, lastSeen, iv, data }`.\n */\ninterface StoragePresenceRecord {\n userId: string\n lastSeen: string\n iv: string // base64 AES-GCM IV (empty when not encrypted)\n data: string // base64 ciphertext or JSON string when not encrypted\n}\n\n/** Presence handle for a single collection. */\nexport class PresenceHandle<P> {\n private readonly adapter: NoydbStore\n private readonly syncAdapter: NoydbStore | undefined\n private readonly vault: string\n private readonly collectionName: string\n private readonly userId: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly staleMs: number\n private readonly pollIntervalMs: number\n private readonly channel: string\n private readonly storageCollection: string\n\n private presenceKey: EnclaveKey | null = null\n private subscribers: Array<(peers: PresencePeer<P>[]) => void> = []\n private unsubscribePubSub: (() => void) | null = null\n private pollTimer: ReturnType<typeof setInterval> | null = null\n private stopped = false\n\n constructor(opts: PresenceHandleOpts) {\n this.adapter = opts.adapter\n this.syncAdapter = opts.syncAdapter\n this.vault = opts.vault\n this.collectionName = opts.collectionName\n this.userId = opts.userId\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.staleMs = opts.staleMs ?? 30_000\n this.pollIntervalMs = opts.pollIntervalMs ?? 5_000\n // Channel used by pub/sub adapters — vault-scoped so two collections\n // in the same vault don't bleed into each other's presence channels.\n this.channel = `${opts.vault}:${opts.collectionName}:presence`\n // Reserved collection name for the storage-poll fallback.\n this.storageCollection = `_presence_${opts.collectionName}`\n }\n\n /**\n * Announce yourself (or update your cursor/status).\n * Encrypts `payload` with the presence key and publishes it.\n */\n async update(payload: P): Promise<void> {\n if (this.stopped) return\n\n const key = await this.getPresenceKey()\n const now = new Date().toISOString()\n const plaintext = JSON.stringify({ userId: this.userId, lastSeen: now, payload })\n let encryptedPayload: string\n\n if (this.encrypted && key) {\n const iv = generateIV()\n const ivB64 = bufferToBase64(iv)\n const { data } = await encrypt(plaintext, key)\n encryptedPayload = JSON.stringify({ iv: ivB64, data })\n } else {\n encryptedPayload = plaintext\n }\n\n // Pub/sub path — publish to any adapter that supports it\n const pubAdapter = this.getPubSubAdapter()\n if (pubAdapter?.presencePublish) {\n await pubAdapter.presencePublish(this.channel, encryptedPayload)\n }\n\n // Storage-poll path — write a record to the storage adapter\n await this.writeStorageRecord(payload, now)\n }\n\n /**\n * Subscribe to presence updates. The callback receives a filtered, decrypted\n * list of all currently-active peers (excluding yourself, excluding stale).\n *\n * Returns an unsubscribe function. Also call `stop()` to release all resources.\n */\n subscribe(cb: (peers: PresencePeer<P>[]) => void): () => void {\n if (this.stopped) return () => {}\n\n this.subscribers.push(cb)\n\n // Start pub/sub listener on first subscriber\n if (this.subscribers.length === 1) {\n this.startListening()\n }\n\n return () => {\n this.subscribers = this.subscribers.filter(s => s !== cb)\n if (this.subscribers.length === 0) this.stopListening()\n }\n }\n\n /** Stop all listening and clear resources. */\n stop(): void {\n this.stopped = true\n this.stopListening()\n this.subscribers = []\n }\n\n // ─── Private ────────────────────────────────────────────────────────\n\n private async getPresenceKey(): Promise<EnclaveKey | null> {\n if (!this.encrypted) return null\n if (!this.presenceKey) {\n try {\n const dek = await this.getDEK(this.collectionName)\n this.presenceKey = await derivePresenceKey(dek, this.collectionName)\n } catch {\n // no-op — presence degrades gracefully if crypto fails\n }\n }\n return this.presenceKey\n }\n\n private getPubSubAdapter(): NoydbStore | undefined {\n // Prefer the sync adapter (it broadcasts to other devices)\n if (this.syncAdapter?.presencePublish) return this.syncAdapter\n if (this.adapter.presencePublish) return this.adapter\n return undefined\n }\n\n private startListening(): void {\n const pubAdapter = this.getPubSubAdapter()\n\n if (pubAdapter?.presenceSubscribe) {\n // Real-time pub/sub path\n this.unsubscribePubSub = pubAdapter.presenceSubscribe(\n this.channel,\n (encryptedPayload) => { void this.handlePubSubMessage(encryptedPayload) },\n )\n } else {\n // Storage-poll fallback\n this.pollTimer = setInterval(\n () => { void this.pollStoragePresence() },\n this.pollIntervalMs,\n )\n // Kick off an immediate poll\n void this.pollStoragePresence()\n }\n }\n\n private stopListening(): void {\n if (this.unsubscribePubSub) {\n this.unsubscribePubSub()\n this.unsubscribePubSub = null\n }\n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = null\n }\n }\n\n private async handlePubSubMessage(encryptedPayload: string): Promise<void> {\n try {\n const peer = await this.decryptPresencePayload(encryptedPayload)\n if (!peer || peer.userId === this.userId) return\n\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n if (peer.lastSeen < cutoff) return\n\n // Deliver only this new peer to subscribers; a full snapshot poll follows\n // on next interval. For pub/sub, we could maintain a map of active peers,\n // but for simplicity: emit a snapshot read from storage.\n await this.pollStoragePresence()\n } catch {\n // Decrypt failure — stale key or tampered payload, ignore\n }\n }\n\n private async decryptPresencePayload(\n encryptedPayload: string,\n ): Promise<{ userId: string; lastSeen: string; payload: P } | null> {\n const key = await this.getPresenceKey()\n\n if (!this.encrypted || !key) {\n return JSON.parse(encryptedPayload) as { userId: string; lastSeen: string; payload: P }\n }\n\n const { iv: ivB64, data } = JSON.parse(encryptedPayload) as { iv: string; data: string }\n const plaintext = await decrypt(ivB64, data, key)\n return JSON.parse(plaintext) as { userId: string; lastSeen: string; payload: P }\n }\n\n private async writeStorageRecord(payload: P, now: string): Promise<void> {\n const key = await this.getPresenceKey()\n const plaintext = JSON.stringify(payload)\n let iv = ''\n let data: string\n\n if (this.encrypted && key) {\n const ivBytes = generateIV()\n iv = bufferToBase64(ivBytes)\n const result = await encrypt(plaintext, key)\n data = result.data\n } else {\n data = plaintext\n }\n\n const record: StoragePresenceRecord = { userId: this.userId, lastSeen: now, iv, data }\n const json = JSON.stringify(record)\n\n // Use the sync adapter if available (so other devices can read it);\n // fall back to local adapter.\n const storeAdapter = this.syncAdapter ?? this.adapter\n const envelope = {\n _noydb: 1 as const,\n _v: 1,\n _ts: now,\n _iv: '',\n _data: json,\n }\n try {\n await storeAdapter.put(\n this.vault,\n this.storageCollection,\n this.userId,\n envelope,\n )\n } catch {\n // Presence write failure is non-fatal — the user is still present locally\n }\n }\n\n private async pollStoragePresence(): Promise<void> {\n if (this.stopped || this.subscribers.length === 0) return\n\n try {\n const storeAdapter = this.syncAdapter ?? this.adapter\n const ids = await storeAdapter.list(this.vault, this.storageCollection)\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n const peers: PresencePeer<P>[] = []\n\n for (const id of ids) {\n if (id === this.userId) continue // skip ourselves\n const envelope = await storeAdapter.get(this.vault, this.storageCollection, id)\n if (!envelope) continue\n\n const record = JSON.parse(envelope._data) as StoragePresenceRecord\n if (record.lastSeen < cutoff) continue\n\n let peerPayload: P\n if (this.encrypted && this.presenceKey && record.iv) {\n const plaintext = await decrypt(record.iv, record.data, this.presenceKey)\n peerPayload = JSON.parse(plaintext) as P\n } else {\n peerPayload = JSON.parse(record.data) as P\n }\n\n peers.push({ userId: record.userId, payload: peerPayload, lastSeen: record.lastSeen })\n }\n\n for (const cb of this.subscribers) {\n cb(peers)\n }\n } catch {\n // Poll failure is non-fatal\n }\n }\n}\n","/**\n * #807 — period-scoped pull support for the `SyncEngine` (thin-client\n * bootstrap: first sync pulls the current period + the period summaries;\n * historical periods backfill on demand via `pull({ periods: ['<name>'] })`).\n *\n * ## Membership law\n *\n * The engine only ever sees ciphertext envelopes, so period membership at\n * the sync tier is by write-time `_ts` against the closed periods' windows\n * (`periodExclusiveUpperBound`) — the SAME store-tier law freeze (#604) and\n * archive (#613) use, NOT the business-date (`dateField`) seal the write\n * guard applies inside the trust boundary. A late-booked record (in-period\n * business date, current write-time) therefore syncs with the current\n * period — mirroring how it archives at the NEXT period's archive.\n *\n * Closed periods partition the timeline by their exclusive upper bounds:\n * the earliest closed period's window is unbounded below (a close seals\n * everything at-or-before its `endDate`), each later one starts at its\n * predecessor's bound, and the CURRENT window is everything at-or-after\n * the latest closed bound (everything, when no period was ever closed).\n *\n * ## What a period filter can never drop\n *\n * - **Period summaries** (`_periods` + freeze/archive/target-purge\n * companions) — the navigation index; always pulled in full, exempt from\n * every filter (`collections`, `periods`, `modifiedSince`).\n * - **Delete markers and tombstones** — an erasure or delete must never be\n * skipped by partial sync (the #589/#590 law, mirroring the\n * `modifiedSince` exemption). This is what makes a device that never\n * pulled period P converge instead of resurrecting P's deleted records\n * when it later backfills.\n * - **Reserved lookups** (`_dict_*`/`_lookup_*`) — vocabulary/config rows\n * are not period-partitioned data; their explicit pull loop is exempt.\n *\n * Push is NEVER period-filtered — `PushOptions` has no `periods` member at\n * all; a thin client's writes always flow up in full.\n */\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\nimport { ValidationError } from '../../kernel/errors.js'\nimport { isTombstoneShape, isDeleteMarker } from '../../kernel/enclave/index.js'\nimport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n periodExclusiveUpperBound,\n} from '../../with-audit/periods/window.js'\n\nexport { PERIODS_COLLECTION }\n\n/**\n * The reserved period-metadata collections a period-scoped pull always\n * fetches first (phase 1, \"summaries\"): the hash-chained `_periods` index\n * plus its freeze/archive/target-purge companions.\n */\nexport const PERIOD_SUMMARY_COLLECTIONS: readonly string[] = [\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n]\n\n/** The subset of a decrypted `PeriodRecord` the window computation needs. */\nexport interface PeriodSyncRecord {\n readonly name: string\n readonly kind: 'closed' | 'opened'\n readonly endDate: string\n}\n\n/**\n * Vault-injected source of decrypted period records, wired via\n * `SyncEngine.setPeriodPullSource` (same injection pattern as\n * `setReservedLookupSource`). MUST re-read from the local store on every\n * call — the engine invokes it right after the summaries phase applied\n * freshly pulled `_periods` envelopes.\n */\nexport interface PeriodPullSource {\n periods(): Promise<readonly PeriodSyncRecord[]>\n}\n\nconst SHAPE_MSG =\n 'pull: `periods` must be an array of closed-period names, or `{ current: true }`.'\n\n/** Validate the raw `PullOptions.periods` value (runtime shape only). */\nexport function validatePeriodsOption(\n periods: unknown,\n): asserts periods is readonly string[] | { readonly current: true } {\n if (Array.isArray(periods)) {\n for (const p of periods) {\n if (typeof p !== 'string' || p.length === 0) throw new ValidationError(SHAPE_MSG)\n }\n return\n }\n if (\n typeof periods === 'object' && periods !== null &&\n (periods as { current?: unknown }).current === true &&\n Object.keys(periods).length === 1\n ) {\n return\n }\n throw new ValidationError(SHAPE_MSG)\n}\n\n/**\n * Resolve the selected `_ts` windows and return the pull-scope predicate:\n * `true` = the envelope is in scope for this pull. Tombstones and delete\n * markers are unconditionally in scope (see module doc).\n *\n * Throws `ValidationError` for a name that is not a closed period in the\n * (freshly synced) `_periods` index — a typo'd backfill must fail loudly,\n * never silently pull nothing.\n */\nexport function buildPeriodScope(\n option: readonly string[] | { readonly current: true },\n records: readonly PeriodSyncRecord[],\n): (envelope: EncryptedEnvelope) => boolean {\n const closed = records\n .filter((r) => r.kind === 'closed')\n .map((r) => ({ name: r.name, bound: periodExclusiveUpperBound(r.endDate) }))\n .sort((a, b) => a.bound.localeCompare(b.bound))\n\n let windows: ReadonlyArray<{ lower: string | null; upper: string | null }>\n if (Array.isArray(option)) {\n windows = (option as readonly string[]).map((name) => {\n const idx = closed.findIndex((c) => c.name === name)\n if (idx < 0) {\n const other = records.find((r) => r.name === name)\n throw new ValidationError(\n other\n ? `pull: period \"${name}\" is \"${other.kind}\" — only closed periods have a backfill window; use \\`{ current: true }\\` for the open period.`\n : `pull: no closed period named \"${name}\" in this vault's _periods index.`,\n )\n }\n return { lower: idx > 0 ? closed[idx - 1]!.bound : null, upper: closed[idx]!.bound }\n })\n } else {\n // { current: true } — everything at-or-after the latest closed bound\n // (everything, when no period was ever closed: with no closed periods\n // there is nothing historical to exclude, so nothing is silently dropped).\n windows = [{ lower: closed.length > 0 ? closed[closed.length - 1]!.bound : null, upper: null }]\n }\n\n return (envelope: EncryptedEnvelope): boolean => {\n if (isTombstoneShape(envelope) || isDeleteMarker(envelope)) return true\n return windows.some(\n (w) =>\n (w.lower === null || envelope._ts >= w.lower) &&\n (w.upper === null || envelope._ts < w.upper),\n )\n }\n}\n","import type {\n NoydbStore,\n DirtyEntry,\n Conflict,\n ConflictStrategy,\n CollectionConflictResolver,\n PushOptions,\n PullOptions,\n PushResult,\n PullResult,\n SyncStatus,\n EncryptedEnvelope,\n SyncMetadata,\n SyncTargetRole,\n ErasureEnforcement,\n} from '../../kernel/types.js'\nimport { NOYDB_SYNC_VERSION } from '../../kernel/types.js'\nimport { ConflictError, ValidationError } from '../../kernel/errors.js'\nimport {\n PERIOD_SUMMARY_COLLECTIONS,\n PERIODS_COLLECTION,\n buildPeriodScope,\n validatePeriodsOption,\n type PeriodPullSource,\n} from './sync-period-scope.js'\nimport type { NoydbEventEmitter } from '../../kernel/events.js'\nimport type { SyncPolicy } from '../../kernel/sync-policy.js'\nimport { SyncScheduler } from '../../kernel/sync-policy.js'\nimport { isTombstoneShape, isDeleteMarker, envelopeBodySize } from '../../kernel/enclave/index.js'\n\n/** #650 Task 4 (#647) — the declared reserved-lookup (`_dict_*`/`_lookup_*`) collection-name\n * registry a `SyncEngine` enumerates on pull. Explicit, not a blanket underscore-glob — other\n * `_`-prefixed namespaces keep their `loadAll`-skip semantics untouched. */\nexport interface ReservedLookupSource {\n /** Declared reserved-lookup collection names to enumerate on pull. */\n collections(): readonly string[]\n}\n\n/** Sync engine: dirty tracking, push, pull, conflict resolution, scheduling. */\nexport class SyncEngine {\n private readonly local: NoydbStore\n private readonly remote: NoydbStore\n private readonly strategy: ConflictStrategy\n private readonly emitter: NoydbEventEmitter\n private readonly vault: string\n readonly role: SyncTargetRole\n readonly label: string | undefined\n\n private dirty: DirtyEntry[] = []\n private lastPush: string | null = null\n private lastPull: string | null = null\n private loaded = false\n private autoSyncInterval: ReturnType<typeof setInterval> | null = null\n private isOnline = true\n\n /** Sync scheduler. Manages push/pull timing. */\n readonly scheduler: SyncScheduler | null\n\n /** Per-collection conflict resolvers registered by Collection instances. */\n private readonly conflictResolvers = new Map<string, CollectionConflictResolver>()\n\n /**\n * Expands a collection-name filter to include its satellite pair partner(s)\n * (spec #591 convergence rule 5b) — wired from vault satellite declaration\n * via `setPairExpander`. `undefined` when no satellite has ever been\n * declared for this vault: identity behavior, zero change for non-satellite\n * users.\n */\n private pairExpander?: (names: readonly string[]) => readonly string[]\n\n /** #598: refreshes Collection in-memory views after a sync-applied local write. Wired by the\n * vault at open. `action` (#640): `'delete'` for a pulled tombstone/delete-marker, `'put'`\n * otherwise — classified at `applyRemote`, the one choke point that holds the envelope. */\n private cacheInvalidator?: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>\n\n /** Wire the Collection-cache invalidation hook (#598). Same injection pattern as `setPairExpander`. */\n setCacheInvalidator(fn: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>): void {\n this.cacheInvalidator = fn\n }\n\n /** #638 Task 4: opens/flushes the vault's graph-dispatch touch batch around a whole `pull()`/\n * `push()` call, so N `applyRemote`d records feeding the same derivation/rollup/MV target\n * recompute once. Wired by the vault at open, mirroring `cacheInvalidator`. */\n private graphBatchController?: { begin(): void; flush(): Promise<void> }\n\n /** Wire the graph-dispatch batch controller (#638 Task 4). Same injection pattern as `setCacheInvalidator`. */\n setGraphBatchController(controller: { begin(): void; flush(): Promise<void> }): void {\n this.graphBatchController = controller\n }\n\n /** #650 Task 4 (#647): declared reserved-lookup collections `pull()` enumerates explicitly (the\n * store's `list()` does not skip `_`-prefixed names, unlike `loadAll()`). Wired by the vault at\n * open, same injection pattern as `setCacheInvalidator`/`setGraphBatchController`. */\n private reservedLookup?: ReservedLookupSource\n\n /** Wire the reserved-lookup source (#650 Task 4). */\n setReservedLookupSource(source: ReservedLookupSource): void {\n this.reservedLookup = source\n }\n\n /** #653: expands a (pair-expanded) collection-name filter to include the reserved `_dict_*`\n * collections those names depend on via their lookup fields — mirrors `pairExpander` so a\n * partial `push`/`pull({collections:[...]})` never drops the dictionary a named collection's\n * labels/membership rely on. Wired unconditionally from the vault's `dictKeyFieldRegistry` via\n * `setReservedDictExpander` (returns `[]` when the vault has no dict-backed collections); only\n * `undefined` on a standalone engine that was never vault-attached. */\n private reservedDictExpander?: (names: readonly string[]) => readonly string[]\n\n /** Wire the reserved-dict expansion function (#653). Same injection pattern as `setPairExpander`. */\n setReservedDictExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.reservedDictExpander = expander\n }\n\n /** #807: vault-injected source of decrypted period records — resolves the `_ts` windows a\n * `pull({ periods })` scopes to. Re-read AFTER the summaries phase, so a fresh device's\n * freshly pulled `_periods` index is what the windows are computed from. `undefined` on a\n * standalone engine that was never vault-attached (period-scoped pull then throws). */\n private periodPullSource?: PeriodPullSource\n\n /** Wire the period-window source (#807). Same injection pattern as `setReservedLookupSource`. */\n setPeriodPullSource(source: PeriodPullSource): void {\n this.periodPullSource = source\n }\n\n /** #807: KPI accumulator `applyRemote` feeds during a period-scoped `pull()` — pointed at the\n * active phase's counters (summaries → records) and cleared before pull returns. Approximate\n * by design: a push interleaved mid-pull on the same engine would attribute its converge\n * applies to the open phase; the counters are a download-budget KPI, not an audit source. */\n private pullByteSink: { records: number; bytes: number } | null = null\n\n constructor(opts: {\n local: NoydbStore\n remote: NoydbStore\n vault: string\n strategy: ConflictStrategy\n emitter: NoydbEventEmitter\n syncPolicy?: SyncPolicy\n role?: SyncTargetRole\n label?: string\n }) {\n this.local = opts.local\n this.remote = opts.remote\n this.vault = opts.vault\n this.strategy = opts.strategy\n this.emitter = opts.emitter\n this.role = opts.role ?? 'sync-peer'\n this.label = opts.label\n\n // Create scheduler if a policy is provided\n const policy = opts.syncPolicy\n if (policy && policy.push.mode !== 'manual') {\n this.scheduler = new SyncScheduler(policy, {\n push: () => this.push().then(() => {}),\n pull: () => this.pull().then(() => {}),\n getDirtyCount: () => this.dirty.length,\n })\n } else {\n this.scheduler = null\n }\n }\n\n /** Start the sync scheduler. Called after vault is fully opened. */\n startScheduler(): void {\n this.scheduler?.start()\n }\n\n /** Stop the sync scheduler. Called on close. */\n stopScheduler(): void {\n this.scheduler?.stop()\n }\n\n /**\n * Register a per-collection conflict resolver.\n * Called by Collection when `conflictPolicy` is set.\n *\n * Pair-coupled (#591 rule 5b): registering for one satellite-pair member\n * registers the same resolver for both — the pair converges under one\n * resolution policy. Expands with whatever the pair-expander knows *at this\n * call*; resolvers registered before their pair existed are covered by\n * `remirrorPairResolvers` at pair-registration time.\n */\n registerConflictResolver(collection: string, resolver: CollectionConflictResolver): void {\n for (const n of this.pairExpander?.([collection]) ?? [collection]) this.conflictResolvers.set(n, resolver)\n }\n\n /**\n * Wire a satellite pair-expansion function (vault registration, #591 Task 11).\n * The closure re-reads the live `SatelliteRegistry` on every call, so pairs\n * declared after this is set are still picked up by `push`/`pull` filters.\n */\n setPairExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.pairExpander = expander\n }\n\n /**\n * Retroactively mirror per-collection conflict resolvers across a newly\n * registered satellite pair (#591 rule 5b) — covers the NORMAL declaration\n * order, where the base's `conflictPolicy` resolver was registered before\n * the satellite was declared (so the call-time expansion in\n * `registerConflictResolver` saw no pair yet). Tie-break: when BOTH members\n * already carry (different) resolvers, the FIRST name in `names` wins —\n * callers pass `[base, satellite]`, so the base's resolver is canonical.\n * Idempotent; a later explicit registration on either member still\n * overwrites both (last-wins, via the call-time expansion above).\n */\n remirrorPairResolvers(names: readonly string[]): void {\n const canonical = names.map(n => this.conflictResolvers.get(n)).find(r => r !== undefined)\n if (!canonical) return\n for (const n of names) this.conflictResolvers.set(n, canonical)\n }\n\n /** Record a local change for later push. */\n async trackChange(collection: string, id: string, action: 'put' | 'delete', version: number): Promise<void> {\n await this.ensureLoaded()\n\n // Deduplicate: if same collection+id already in dirty, update it\n const idx = this.dirty.findIndex(d => d.collection === collection && d.id === id)\n const entry: DirtyEntry = {\n vault: this.vault,\n collection,\n id,\n action,\n version,\n timestamp: new Date().toISOString(),\n }\n\n if (idx >= 0) {\n this.dirty[idx] = entry\n } else {\n this.dirty.push(entry)\n }\n\n await this.persistMeta()\n\n // Notify scheduler of the write (triggers on-change or debounce)\n this.scheduler?.notifyChange()\n }\n\n /** Remove a dirty entry (satellite fan-out revert cleanup — spec #591). */\n async removeDirty(collection: string, id: string): Promise<void> {\n const before = this.dirty.length\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n if (this.dirty.length !== before) await this.persistMeta()\n }\n\n /** Push dirty records to remote adapter. Accepts optional `PushOptions` for partial sync. */\n async push(options?: PushOptions): Promise<PushResult> {\n await this.ensureLoaded()\n this.graphBatchController?.begin() // #638 Task 4\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — a locally-dirty\n // dict edit pushes alongside push({collections:['orders']}), symmetric with pull below.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(entry.collection)) {\n continue\n }\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n // Record was deleted locally after being marked dirty\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (err instanceof ConflictError) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n await this.remote.put(this.vault, entry.collection, entry.id, conflict.local)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n // Merged envelope is stored in conflict.local (the winner)\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n // handled === 'deferred': leave in dirty log\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n // Remove completed entries from dirty log (reverse order to preserve indices)\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.lastPush = new Date().toISOString()\n try {\n await this.persistMeta()\n } finally {\n // #644 item 1: flush (which clears `_graphBatch` unconditionally, vault.ts:1316-1320) must\n // run even if `persistMeta()` throws — else a throw here leaves the batch open, corrupting\n // the NEXT pull()/push() call's wave with THIS call's stale touches.\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /** Pull remote records to local adapter. Accepts optional `PullOptions` for partial sync. */\n async pull(options?: PullOptions): Promise<PullResult> {\n await this.ensureLoaded()\n\n let pulled = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n\n // ── #807 period-scoped pull: validate the option, sync the period summaries\n // (`_periods` + companions — the navigation index, ALWAYS pulled in full,\n // exempt from every filter), then resolve the selected `_ts` windows from the\n // freshly synced index. All BEFORE the graph batch opens, so an invalid\n // option throws without leaving a batch dangling; summary applies route\n // through `applyRemote` like any pull (reserved names have no Collection\n // instance, so the invalidator/graph seams are no-ops for them). ──\n let periodScope: ((envelope: EncryptedEnvelope) => boolean) | null = null\n let phases: { summaries: { records: number; bytes: number }; records: { records: number; bytes: number } } | null = null\n if (options?.periods !== undefined) {\n validatePeriodsOption(options.periods)\n if (!this.periodPullSource) {\n throw new ValidationError(\n 'period-scoped pull requires a vault-attached sync engine (open the vault via createNoydb + openVault).',\n )\n }\n phases = { summaries: { records: 0, bytes: 0 }, records: { records: 0, bytes: 0 } }\n let remotePeriodCount = 0\n this.pullByteSink = phases.summaries\n try {\n for (const collName of PERIOD_SUMMARY_COLLECTIONS) {\n for (const id of await this.remote.list(this.vault, collName)) {\n if (collName === PERIODS_COLLECTION) remotePeriodCount++\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope || remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } finally {\n this.pullByteSink = null\n }\n const periodRecords = await this.periodPullSource.periods()\n if (remotePeriodCount > 0 && periodRecords.length === 0) {\n throw new ValidationError(\n 'period-scoped pull: the vault holds _periods records but none are readable — enable the ' +\n 'periods service (`periodsStrategy: withPeriods()`) so pull can resolve the period windows.',\n )\n }\n periodScope = buildPeriodScope(options.periods, periodRecords)\n }\n\n this.graphBatchController?.begin() // #638 Task 4\n if (phases) this.pullByteSink = phases.records\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — adopters never\n // name `_dict_*` in a `collections` filter, so a named collection's lookup-field dependency\n // must be pulled alongside it or its labels/membership go stale.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n try {\n const remoteSnapshot = await this.remote.loadAll(this.vault)\n\n for (const [collName, records] of Object.entries(remoteSnapshot)) {\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(collName)) {\n continue\n }\n\n for (const [id, remoteEnvelope] of Object.entries(records)) {\n // Partial sync: modifiedSince filter — arriving tombstones are exempt (#590):\n // an erasure must never be skipped by partial sync.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isTombstoneShape(remoteEnvelope) &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n // #807: period scope — a record whose `_ts` falls outside every selected\n // window is skipped. Tombstones and delete markers are ALWAYS in scope\n // (built into the predicate): an erasure or delete must never be skipped\n // by partial sync, mirroring the modifiedSince exemption above — that is\n // what lets a device that never pulled a period backfill it later without\n // resurrecting its deleted records.\n if (periodScope !== null && !periodScope(remoteEnvelope)) {\n continue\n }\n\n try {\n const localEnvelope = await this.local.get(this.vault, collName, id)\n const remoteIsTombstone = isTombstoneShape(remoteEnvelope)\n\n if (!localEnvelope) {\n // New record from remote (tombstones included — durable erasure evidence)\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (isTombstoneShape(localEnvelope)) {\n if (remoteIsTombstone) {\n // Both shredded — keep the higher version counter\n if (remoteEnvelope._v > localEnvelope._v) await this.applyRemote(collName, id, remoteEnvelope)\n } else {\n // Terminal rule (#590): a tombstone is never overwritten by a live\n // envelope, regardless of _v. Re-assert the shred outward instead.\n erasures.push(await this.reassertTombstone(collName, id, localEnvelope, remoteEnvelope))\n }\n } else if (remoteIsTombstone) {\n // Terminal rule (#590): an arriving tombstone wins over any local live\n // envelope — even a newer, dirty one. Resolvers are never consulted.\n const wasDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n if (wasDirty) erasures.push(this.reportErasure(collName, id, remoteEnvelope, localEnvelope, 'pull'))\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // #589: true concurrent delete-vs-edit at the SAME version. Version order\n // can't break the tie. A per-collection resolver decides if one is set;\n // otherwise DELETE wins (the db-level 'version' default is deliberately NOT\n // consulted — it would resolve a tie to local-wins).\n const resolver = this.conflictResolvers.get(collName)\n if (resolver) {\n const winner = await resolver(id, localEnvelope, remoteEnvelope)\n if (winner !== localEnvelope && winner !== null) {\n // #589 (review): a novel/merged winner (neither side verbatim) must also be\n // pushed to remote — mirrors handleConflict's 'merged' handling — so both\n // sides converge instead of local applying it while remote keeps its old copy.\n if (winner !== remoteEnvelope) {\n await this.remote.put(this.vault, collName, id, winner)\n }\n await this.applyRemote(collName, id, winner)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // winner === localEnvelope or null → keep local (its dirty entry, if any, pushes out)\n } else if (isDeleteMarker(remoteEnvelope)) {\n // no resolver → delete wins; the incoming marker is the delete\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // no resolver and LOCAL is the marker → keep local marker; its dirty 'put' pushes it outward\n } else if (remoteEnvelope._v > localEnvelope._v) {\n // Remote is newer — check if we have a dirty entry for this\n const isDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n if (isDirty) {\n // Both changed — conflict\n const { handled, conflict } = await this.handleConflict(\n collName,\n id,\n localEnvelope,\n remoteEnvelope,\n 'pull',\n )\n conflicts.push(conflict)\n if (handled === 'remote') {\n await this.applyRemote(collName, id, conflict.remote)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n } else if (handled === 'merged' && conflict.local !== localEnvelope) {\n const merged = conflict.local\n await this.applyRemote(collName, id, merged)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // 'local' or 'deferred': push handles it\n } else {\n // Remote is newer, no local changes — update\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n }\n // Same version or local is newer — skip (push will handle)\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n\n // #650 Task 4 (#647) — reserved lookup collections (`_dict_*`/`_lookup_*`) are invisible to\n // `remote.loadAll()` above (the store contract skips `_`-prefixed names) but DO sync via\n // this EXPLICIT, declared registry — not a blanket underscore-glob; other `_` namespaces\n // keep their `loadAll`-skip semantics untouched. Applied through the SAME `applyRemote` path,\n // still inside this try block, BEFORE `persistMeta`/`flush` below — so a pulled vocabulary\n // row lands before the wave (flushed at the end of `pull()`) recomputes any dependent.\n //\n // #647 fix wave 1: `LookupHandle.delete()`/`rename()` now write a version-ordered\n // delete-marker row (mirroring #589) instead of a raw adapter delete, so a removed key is\n // a normal row here too — reachable via `remote.list()` like any other id, applied by\n // version like any other write. The only reserved-tier-specific rule is the same-version\n // tie-break below: reserved lookups have no per-collection conflict-resolver concept\n // (dictionaries are admin-edited, not multi-actor-negotiated), so a converging delete\n // unconditionally wins over a same-version live edit.\n //\n // #807: the period scope deliberately does NOT apply here — vocabularies/config rows are\n // not period-partitioned data (a thin client's lookups must be complete regardless of\n // which periods it pulled), the same always-pull rule as the `_periods` summaries phase.\n for (const collName of this.reservedLookup?.collections() ?? []) {\n if (filter && !filter.has(collName)) continue\n for (const id of await this.remote.list(this.vault, collName)) {\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n\n // Partial sync: modifiedSince filter — a delete marker is exempt, mirroring the\n // main loop's tombstone/marker exemption above: a deletion must never be silently\n // skipped by a time-window partial pull.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // Same-version delete-vs-edit tie (#589's rule, reserved-tier default: no\n // resolver concept here, so delete always wins).\n if (isDeleteMarker(remoteEnvelope)) {\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // else: local already holds the marker (a local delete not yet observed\n // remotely) — keep it; push re-asserts it.\n } else if (remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n // Drop any now-superseded local dirty entry so a subsequent push doesn't\n // redundantly re-fight a CAS conflict over content pull just overwrote.\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n\n this.lastPull = new Date().toISOString()\n try {\n await this.persistMeta()\n } finally {\n this.pullByteSink = null // #807: stop attributing applies to this pull's KPI counters\n // #644 item 1: flush must run even if `persistMeta()` throws (see push()'s identical guard).\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PullResult = { pulled, conflicts, errors, erasures, ...(phases !== null ? { phases } : {}) }\n this.emitter.emit('sync:pull', result)\n return result\n }\n\n /** Bidirectional sync: pull then push. */\n async sync(options?: { push?: PushOptions; pull?: PullOptions }): Promise<{ pull: PullResult; push: PushResult }> {\n const pullResult = await this.pull(options?.pull)\n const pushResult = await this.push(options?.push)\n return { pull: pullResult, push: pushResult }\n }\n\n /**\n * Push a specific subset of dirty entries (for sync transactions, ).\n * Entries are matched by collection+id from the dirty log; matched entries\n * are removed from the dirty log on success.\n */\n async pushFiltered(predicate: (entry: DirtyEntry) => boolean): Promise<PushResult> {\n await this.ensureLoaded()\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n if (!predicate(entry)) continue\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (err instanceof ConflictError) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n await this.remote.put(this.vault, entry.collection, entry.id, conflict.local)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.lastPush = new Date().toISOString()\n await this.persistMeta()\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /** Get current sync status. */\n status(): SyncStatus {\n return {\n dirty: this.dirty.length,\n lastPush: this.lastPush,\n lastPull: this.lastPull,\n online: this.isOnline,\n }\n }\n\n // ─── Auto-Sync ───────────────────────────────────────────────────\n\n /** Start auto-sync: listen for online/offline events, optional periodic sync. */\n startAutoSync(intervalMs?: number): void {\n // Online/offline detection\n if (typeof globalThis.addEventListener === 'function') {\n globalThis.addEventListener('online', this.handleOnline)\n globalThis.addEventListener('offline', this.handleOffline)\n }\n\n // Periodic sync\n if (intervalMs && intervalMs > 0) {\n this.autoSyncInterval = setInterval(() => {\n if (this.isOnline) {\n void this.sync()\n }\n }, intervalMs)\n }\n }\n\n /** Stop auto-sync and scheduler. */\n stopAutoSync(): void {\n this.stopScheduler()\n if (typeof globalThis.removeEventListener === 'function') {\n globalThis.removeEventListener('online', this.handleOnline)\n globalThis.removeEventListener('offline', this.handleOffline)\n }\n if (this.autoSyncInterval) {\n clearInterval(this.autoSyncInterval)\n this.autoSyncInterval = null\n }\n }\n\n private handleOnline = (): void => {\n this.isOnline = true\n this.emitter.emit('sync:online', undefined as never)\n void this.sync()\n }\n\n private handleOffline = (): void => {\n this.isOnline = false\n this.emitter.emit('sync:offline', undefined as never)\n }\n\n /** Apply an envelope to the local store and refresh in-memory views (#598). `action` (#640):\n * classified HERE — the one choke point that still holds the envelope — so the\n * cacheInvalidator seam (and, downstream, the dispatch wave) can tell a pulled delete from an\n * ordinary put. `isTombstoneShape` covers a forgotten-elsewhere record arriving as a shred;\n * `isDeleteMarker` covers an ordinary (#589) delete — both route to the SAME 'delete' action\n * (sync delete ≠ forget: freshness only, no shred/residue channel on the receiving side). */\n private async applyRemote(collection: string, id: string, envelope: EncryptedEnvelope): Promise<void> {\n await this.local.put(this.vault, collection, id, envelope)\n if (this.pullByteSink !== null) {\n // #807: KPI — one applied envelope; bytes ≈ ciphertext payload size.\n this.pullByteSink.records++\n this.pullByteSink.bytes += envelopeBodySize(envelope)\n }\n const action: 'put' | 'delete' = isTombstoneShape(envelope) || isDeleteMarker(envelope) ? 'delete' : 'put'\n await this.cacheInvalidator?.(collection, id, action)\n }\n\n /** Record + emit a tombstone enforcement (#590). */\n private reportErasure(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressed: EncryptedEnvelope,\n direction: 'pull' | 'push',\n ): ErasureEnforcement {\n const enforcement: ErasureEnforcement = { vault: this.vault, collection, id, tombstone, suppressed, direction }\n this.emitter.emit('sync:erasure', enforcement)\n return enforcement\n }\n\n /**\n * Re-assert a local tombstone over a live remote envelope (#590): the shred\n * wins in both directions, regardless of `_v`. Bumps the tombstone to the\n * suppressed envelope's `_v` when higher so per-key version counters stay\n * monotonic on every store; `_by` (the shredding actor) is preserved.\n */\n private async reassertTombstone(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressedRemote: EncryptedEnvelope,\n ): Promise<ErasureEnforcement> {\n let winner = tombstone\n if (suppressedRemote._v > tombstone._v) {\n winner = { ...tombstone, _v: suppressedRemote._v, _ts: new Date().toISOString() }\n await this.applyRemote(collection, id, winner)\n }\n await this.remote.put(this.vault, collection, id, winner)\n // The re-assert already delivered the tombstone remotely — drop any dirty\n // entry so the following push doesn't redundantly re-put it.\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n return this.reportErasure(collection, id, winner, suppressedRemote, 'pull')\n }\n\n /**\n * Resolve a conflict, checking per-collection resolvers first,\n * then falling back to the db-level `ConflictStrategy`.\n *\n * Returns the resolved `Conflict` object (possibly with `resolve` set for\n * manual mode) and a `handled` discriminant:\n * - `'local'` — keep the local envelope; push it to remote.\n * - `'remote'` — keep the remote envelope; update local.\n * - `'merged'` — a custom merge fn produced a new envelope stored as `conflict.local`.\n * - `'deferred'` — manual mode, resolve was not called synchronously.\n */\n private async handleConflict(\n collection: string,\n id: string,\n local: EncryptedEnvelope,\n remote: EncryptedEnvelope,\n _phase: 'push' | 'pull',\n ): Promise<{ handled: 'local' | 'remote' | 'merged' | 'deferred'; conflict: Conflict }> {\n const resolver = this.conflictResolvers.get(collection)\n\n if (resolver) {\n // Per-collection resolver is responsible for emitting sync:conflict\n // (manual policy emits with a resolve callback; LWW/FWW/custom are silent).\n const winner = await resolver(id, local, remote)\n const base: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n if (winner === null) return { handled: 'deferred', conflict: base }\n if (winner === local) return { handled: 'local', conflict: base }\n if (winner === remote) return { handled: 'remote', conflict: base }\n // Custom merge fn produced a new envelope — store as conflict.local for the caller\n return {\n handled: 'merged',\n conflict: { ...base, local: winner, localVersion: winner._v },\n }\n }\n\n // Fall back to db-level strategy — emit once\n const baseConflict: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n this.emitter.emit('sync:conflict', baseConflict)\n const side = this.legacyResolve(baseConflict)\n return { handled: side, conflict: baseConflict }\n }\n\n /** DB-level ConflictStrategy resolution (legacy, kept for backward compat). */\n private legacyResolve(conflict: Conflict): 'local' | 'remote' {\n if (typeof this.strategy === 'function') {\n return this.strategy(conflict)\n }\n switch (this.strategy) {\n case 'local-wins': return 'local'\n case 'remote-wins': return 'remote'\n case 'version':\n default:\n return conflict.localVersion >= conflict.remoteVersion ? 'local' : 'remote'\n }\n }\n\n // ─── Persistence ─────────────────────────────────────────────────\n\n private async ensureLoaded(): Promise<void> {\n if (this.loaded) return\n\n const envelope = await this.local.get(this.vault, '_sync', 'meta')\n if (envelope) {\n const meta = JSON.parse(envelope._data) as SyncMetadata\n this.dirty = [...meta.dirty]\n this.lastPush = meta.last_push\n this.lastPull = meta.last_pull\n }\n\n this.loaded = true\n }\n\n private async persistMeta(): Promise<void> {\n const meta: SyncMetadata = {\n _noydb_sync: NOYDB_SYNC_VERSION,\n last_push: this.lastPush,\n last_pull: this.lastPull,\n dirty: this.dirty,\n }\n\n const envelope: EncryptedEnvelope = {\n _noydb: 1,\n _v: 1,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: JSON.stringify(meta),\n }\n\n await this.local.put(this.vault, '_sync', 'meta', envelope)\n }\n}\n","import type { SyncTransactionResult } from '../../kernel/types.js'\nimport type { SyncEngine } from './sync.js'\nimport type { Vault } from '../../kernel/vault.js'\n\ninterface TxOp {\n readonly type: 'put' | 'delete'\n readonly collection: string\n readonly id: string\n readonly record?: unknown\n}\n\n/**\n * Sync transaction.\n *\n * Stages local writes and then pushes only those records to remote in a\n * single batch. If any record conflicts during the push, the result\n * carries `status: 'conflict'` — no automatic rollback is performed;\n * the caller handles conflict resolution.\n *\n * Obtain via `db.transaction(compartmentName)`.\n */\nexport class SyncTransaction {\n private readonly comp: Vault\n private readonly engine: SyncEngine\n private readonly ops: TxOp[] = []\n\n /** @internal — constructed by `Noydb.transaction()` */\n constructor(comp: Vault, engine: SyncEngine) {\n this.comp = comp\n this.engine = engine\n }\n\n /** Stage a record write. Does not write to any adapter until `commit()`. */\n put(collection: string, id: string, record: unknown): this {\n this.ops.push({ type: 'put', collection, id, record })\n return this\n }\n\n /** Stage a record delete. Does not write to any adapter until `commit()`. */\n delete(collection: string, id: string): this {\n this.ops.push({ type: 'delete', collection, id })\n return this\n }\n\n /**\n * Commit the transaction.\n *\n * Phase 1 — writes all staged operations to the local adapter via the\n * collection layer (encryption + dirty-log tracking).\n *\n * Phase 2 — pushes only the records that were written in this\n * transaction to the remote adapter. Existing dirty entries from\n * outside this transaction are not affected.\n *\n * If any record conflicts during the push, `status` is `'conflict'`\n * and `conflicts` lists the affected records. No automatic rollback is\n * performed.\n */\n async commit(): Promise<SyncTransactionResult> {\n // Phase 1: write all staged ops to local via collection layer\n for (const op of this.ops) {\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.comp.collection<any>(op.collection)).put(op.id, op.record as any)\n } else {\n await this.comp.collection(op.collection).delete(op.id)\n }\n }\n\n // Phase 2: push only the records from this transaction\n const opSet = new Set<string>()\n for (const op of this.ops) {\n opSet.add(`${op.collection}::${op.id}`)\n }\n\n const pushResult = await this.engine.pushFiltered(\n (entry) => opSet.has(`${entry.collection}::${entry.id}`),\n )\n\n return {\n status: pushResult.conflicts.length > 0 ? 'conflict' : 'committed',\n pushed: pushResult.pushed,\n conflicts: pushResult.conflicts,\n ...(pushResult.erasures?.length ? { erasures: pushResult.erasures } : {}),\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDO,IAAM,iBAAN,MAAwB;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,cAAiC;AAAA,EACjC,cAAyD,CAAC;AAAA,EAC1D,oBAAyC;AAAA,EACzC,YAAmD;AAAA,EACnD,UAAU;AAAA,EAElB,YAAY,MAA0B;AACpC,SAAK,UAAU,KAAK;AACpB,SAAK,cAAc,KAAK;AACxB,SAAK,QAAQ,KAAK;AAClB,SAAK,iBAAiB,KAAK;AAC3B,SAAK,SAAS,KAAK;AACnB,SAAK,YAAY,KAAK;AACtB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,iBAAiB,KAAK,kBAAkB;AAG7C,SAAK,UAAU,GAAG,KAAK,KAAK,IAAI,KAAK,cAAc;AAEnD,SAAK,oBAAoB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OAAO;AAAA,MACnC,CAAC,UAAU,MAAM,IAAI,GAAG,MAAM,UAAU,KAAK,MAAM,EAAE,EAAE;AAAA,IACzD;AAEA,WAAO;AAAA,MACL,QAAQ,WAAW,UAAU,SAAS,IAAI,aAAa;AAAA,MACvD,QAAQ,WAAW;AAAA,MACnB,WAAW,WAAW;AAAA,MACtB,GAAI,WAAW,UAAU,SAAS,EAAE,UAAU,WAAW,SAAS,IAAI,CAAC;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BrokerNotEnabledError
3
- } from "./chunk-BIOUI4HL.js";
3
+ } from "./chunk-W2OG6JOL.js";
4
4
 
5
5
  // src/port/with/broker-strategy.ts
6
6
  var NO_BROKER = {
@@ -27,4 +27,4 @@ export {
27
27
  NO_BROKER,
28
28
  buildCredentialBrokerHandle
29
29
  };
30
- //# sourceMappingURL=chunk-E5ZQT5KX.js.map
30
+ //# sourceMappingURL=chunk-SMIRGMS7.js.map
@@ -0,0 +1,180 @@
1
+ import {
2
+ MaterializedViewConfigError,
3
+ ValidationError
4
+ } from "./chunk-W2OG6JOL.js";
5
+
6
+ // src/with-formula/materialized-views/with-materialized-view.ts
7
+ function withMaterializedView(spec) {
8
+ if (!spec.name || spec.name.length === 0) {
9
+ throw new ValidationError("withMaterializedView: name is required");
10
+ }
11
+ const declaredForms = [spec.query, spec.unionSources, spec.projection].filter((f) => f !== void 0).length;
12
+ if (declaredForms > 1) {
13
+ throw new MaterializedViewConfigError(
14
+ "query, unionSources, and projection are mutually exclusive \u2014 pick one"
15
+ );
16
+ }
17
+ if (declaredForms === 0) {
18
+ throw new MaterializedViewConfigError(
19
+ "strategy must declare exactly one of query, unionSources, or projection"
20
+ );
21
+ }
22
+ if (spec.query !== void 0 && typeof spec.query !== "function") {
23
+ throw new ValidationError("withMaterializedView: query must be a function returning a Query<T>");
24
+ }
25
+ if (spec.unionSources) {
26
+ if (spec.unionSources.length < 1) {
27
+ throw new MaterializedViewConfigError(
28
+ "unionSources requires at least 1 source collection"
29
+ );
30
+ }
31
+ const seen = /* @__PURE__ */ new Set();
32
+ for (const s of spec.unionSources) {
33
+ if (typeof s?.collection !== "string" || s.collection.length === 0) {
34
+ throw new MaterializedViewConfigError(
35
+ "each unionSources entry must declare a non-empty `collection` string"
36
+ );
37
+ }
38
+ if (typeof s.map !== "function") {
39
+ throw new MaterializedViewConfigError(
40
+ `unionSources entry for "${s.collection}" is missing a \`map\` function`
41
+ );
42
+ }
43
+ if (seen.has(s.collection)) {
44
+ throw new MaterializedViewConfigError(
45
+ `unionSources must reference distinct collections (duplicate: "${s.collection}")`
46
+ );
47
+ }
48
+ seen.add(s.collection);
49
+ }
50
+ if (Array.isArray(spec.groupBy) && spec.groupBy.length === 0) {
51
+ throw new MaterializedViewConfigError(
52
+ `withMaterializedView "${spec.name}": groupBy must not be an empty array \u2014 omit it or provide at least one field name`
53
+ );
54
+ }
55
+ if (spec.aggregate && !spec.groupBy) {
56
+ throw new MaterializedViewConfigError(
57
+ `withMaterializedView "${spec.name}": UNION strategy with aggregate requires groupBy \u2014 use groupBy to declare the bucketing keys, or remove aggregate for a pure dedup MV`
58
+ );
59
+ }
60
+ if (spec.moneyFields && !spec.aggregate) {
61
+ throw new MaterializedViewConfigError(
62
+ `withMaterializedView "${spec.name}": moneyFields requires aggregate \u2014 moneyFields rewrites sum/min/max reducers over money output fields, so it is meaningless without an aggregate spec`
63
+ );
64
+ }
65
+ if (spec.unionSources.some((s) => s.join && s.join.length > 0) && (!spec.sources || spec.sources.length === 0)) {
66
+ throw new MaterializedViewConfigError(
67
+ `withMaterializedView "${spec.name}": a unionSources arm declares join(s) but no \`sources\` are listed \u2014 declare sources: [...] with the right-side (join-target) collection names so writes to them trigger MV refresh`
68
+ );
69
+ }
70
+ if (spec.predicates) {
71
+ throw new MaterializedViewConfigError(
72
+ `withMaterializedView "${spec.name}": predicates are not supported on UNION strategies \u2014 UNION mode does not use a Query<T> chain, so .wherePredicate() cannot fire. Use the query() form, or open an issue if per-arm predicates are needed`
73
+ );
74
+ }
75
+ }
76
+ if (spec.projection) {
77
+ const projection = spec.projection;
78
+ if (typeof projection.source !== "string" || projection.source.length === 0) {
79
+ throw new MaterializedViewConfigError(
80
+ `withMaterializedView "${spec.name}": projection.source must be a non-empty collection name`
81
+ );
82
+ }
83
+ if (typeof projection.map !== "function") {
84
+ throw new MaterializedViewConfigError(
85
+ `withMaterializedView "${spec.name}": projection is missing a \`map\` function`
86
+ );
87
+ }
88
+ if (!Array.isArray(projection.joins) || projection.joins.length < 1) {
89
+ throw new MaterializedViewConfigError(
90
+ `withMaterializedView "${spec.name}": projection.joins must declare at least 1 leg \u2014 a leg-less single-source MV is the query() form's job`
91
+ );
92
+ }
93
+ const seenAs = /* @__PURE__ */ new Set();
94
+ for (const leg of projection.joins) {
95
+ const l = leg;
96
+ const isForward = l.field !== void 0;
97
+ const isCollect = l.collect !== void 0;
98
+ if (isForward && isCollect) {
99
+ throw new MaterializedViewConfigError(
100
+ `withMaterializedView "${spec.name}": a projection leg cannot declare both \`field\` (forward) and \`collect\` (reverse) \u2014 split it into two legs`
101
+ );
102
+ }
103
+ if (!isForward && !isCollect) {
104
+ throw new MaterializedViewConfigError(
105
+ `withMaterializedView "${spec.name}": each projection leg must declare either \`field\` (forward FK) or \`collect\` (reverse one-to-many)`
106
+ );
107
+ }
108
+ if (isForward && (typeof l.field !== "string" || l.field.length === 0)) {
109
+ throw new MaterializedViewConfigError(
110
+ `withMaterializedView "${spec.name}": a forward projection leg must declare a non-empty \`field\``
111
+ );
112
+ }
113
+ if (isCollect) {
114
+ if (typeof l.collect !== "string" || l.collect.length === 0) {
115
+ throw new MaterializedViewConfigError(
116
+ `withMaterializedView "${spec.name}": a collect projection leg must declare a non-empty \`collect\` collection name`
117
+ );
118
+ }
119
+ if (typeof l.on !== "string" || l.on.length === 0) {
120
+ throw new MaterializedViewConfigError(
121
+ `withMaterializedView "${spec.name}": collect leg for "${l.collect}" must declare a non-empty \`on\` FK field`
122
+ );
123
+ }
124
+ }
125
+ if (typeof l.as !== "string" || l.as.length === 0) {
126
+ throw new MaterializedViewConfigError(
127
+ `withMaterializedView "${spec.name}": each projection leg must declare a non-empty \`as\` alias`
128
+ );
129
+ }
130
+ if (seenAs.has(l.as)) {
131
+ throw new MaterializedViewConfigError(
132
+ `withMaterializedView "${spec.name}": projection legs must attach under distinct \`as\` aliases (duplicate: "${l.as}")`
133
+ );
134
+ }
135
+ seenAs.add(l.as);
136
+ }
137
+ if (Array.isArray(spec.groupBy) && spec.groupBy.length === 0) {
138
+ throw new MaterializedViewConfigError(
139
+ `withMaterializedView "${spec.name}": groupBy must not be an empty array \u2014 omit it or provide at least one field name`
140
+ );
141
+ }
142
+ if (spec.aggregate && !spec.groupBy) {
143
+ throw new MaterializedViewConfigError(
144
+ `withMaterializedView "${spec.name}": projection strategy with aggregate requires groupBy \u2014 use groupBy to declare the bucketing keys, or remove aggregate for a row-per-primary-record MV`
145
+ );
146
+ }
147
+ if (spec.moneyFields && !spec.aggregate) {
148
+ throw new MaterializedViewConfigError(
149
+ `withMaterializedView "${spec.name}": moneyFields requires aggregate \u2014 moneyFields rewrites sum/min/max reducers over money output fields, so it is meaningless without an aggregate spec`
150
+ );
151
+ }
152
+ if (spec.predicates) {
153
+ throw new MaterializedViewConfigError(
154
+ `withMaterializedView "${spec.name}": predicates are not supported on projection strategies \u2014 projection mode does not use a Query<T> chain, so .wherePredicate() cannot fire. Filter inside projection.map (return null to omit) instead`
155
+ );
156
+ }
157
+ }
158
+ if (spec.i18nLocale !== void 0 && spec.i18nFields === void 0) {
159
+ throw new MaterializedViewConfigError(
160
+ `withMaterializedView "${spec.name}": i18nLocale requires i18nFields \u2014 declare the i18nText descriptors of the group-key fields so they can be resolved at the mv layer before bucketing.`
161
+ );
162
+ }
163
+ if (typeof spec.rowKey !== "function") {
164
+ throw new ValidationError("withMaterializedView: rowKey is required (no default; see spec \xA7 Type surface)");
165
+ }
166
+ if (spec.refresh !== "eager" && spec.refresh !== "lazy" && spec.refresh !== "manual") {
167
+ throw new ValidationError(
168
+ `withMaterializedView: refresh must be 'eager' | 'lazy' | 'manual', got "${String(spec.refresh)}"`
169
+ );
170
+ }
171
+ return {
172
+ __noydb_strategy: "materialized-view",
173
+ spec
174
+ };
175
+ }
176
+
177
+ export {
178
+ withMaterializedView
179
+ };
180
+ //# sourceMappingURL=chunk-T36RFODW.js.map