@noy-db/hub 0.6.0-pre.8 → 0.6.0

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 (512) hide show
  1. package/CHANGELOG.md +7079 -0
  2. package/codemods/0.6.0-pre.json +211 -0
  3. package/dist/api-6X2VLZ7J.js +20 -0
  4. package/dist/attestation/index.js +19 -19
  5. package/dist/{backup-KULFZ2T4.js → backup-VL4GRIEW.js} +36 -18
  6. package/dist/backup-VL4GRIEW.js.map +1 -0
  7. package/dist/blobs/index.js +22 -20
  8. package/dist/blobs/index.js.map +1 -1
  9. package/dist/broker/index.js +12 -12
  10. package/dist/cargo/index.js +35 -35
  11. package/dist/{chunk-KUDZVJKQ.js → chunk-22GR3O4J.js} +2 -2
  12. package/dist/{chunk-CCZJJ4I2.js → chunk-2CBFYXJX.js} +6 -6
  13. package/dist/{chunk-JJNOLSG5.js → chunk-2J5IT37K.js} +15 -16
  14. package/dist/chunk-2J5IT37K.js.map +1 -0
  15. package/dist/{chunk-PNKHAKQ7.js → chunk-2ZCWHCLF.js} +17 -10
  16. package/dist/chunk-2ZCWHCLF.js.map +1 -0
  17. package/dist/{chunk-2BMRJ6LQ.js → chunk-2ZT4INZ4.js} +8 -11
  18. package/dist/{chunk-2BMRJ6LQ.js.map → chunk-2ZT4INZ4.js.map} +1 -1
  19. package/dist/{chunk-FAXZQ5UF.js → chunk-323MN67Z.js} +2 -2
  20. package/dist/{chunk-VMCCGUQB.js → chunk-36CEG6CM.js} +2 -2
  21. package/dist/{chunk-PDLLCOGD.js → chunk-3OE2QNSM.js} +20 -17
  22. package/dist/chunk-3OE2QNSM.js.map +1 -0
  23. package/dist/{chunk-AHLJSVRL.js → chunk-3YGUHUJA.js} +5 -7
  24. package/dist/chunk-3YGUHUJA.js.map +1 -0
  25. package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
  26. package/dist/chunk-4AOERLTV.js.map +1 -0
  27. package/dist/{chunk-J7FM3RAU.js → chunk-4ATF4BLF.js} +87 -34
  28. package/dist/chunk-4ATF4BLF.js.map +1 -0
  29. package/dist/{chunk-747LRSOO.js → chunk-4K6BIMLF.js} +2 -2
  30. package/dist/{chunk-PXCBVDFY.js → chunk-5ATC6UT4.js} +40 -7
  31. package/dist/chunk-5ATC6UT4.js.map +1 -0
  32. package/dist/{chunk-4GZ6XOVW.js → chunk-5F7BZAGV.js} +44 -42
  33. package/dist/chunk-5F7BZAGV.js.map +1 -0
  34. package/dist/{chunk-FNSMZQS4.js → chunk-5IHGJHWC.js} +2 -2
  35. package/dist/{chunk-4I72F5DF.js → chunk-5LZZQMIC.js} +11 -14
  36. package/dist/chunk-5LZZQMIC.js.map +1 -0
  37. package/dist/{chunk-JXIDGFKS.js → chunk-5O5ZSW7N.js} +4 -2
  38. package/dist/chunk-5O5ZSW7N.js.map +1 -0
  39. package/dist/{chunk-CEJWMBXO.js → chunk-5OT4G5N5.js} +6 -2
  40. package/dist/chunk-5OT4G5N5.js.map +1 -0
  41. package/dist/{chunk-GAG7QOVO.js → chunk-64WHKBMP.js} +53 -18
  42. package/dist/chunk-64WHKBMP.js.map +1 -0
  43. package/dist/{chunk-7TSYBD3E.js → chunk-65JXA63J.js} +2 -2
  44. package/dist/{chunk-Z45YRGFO.js → chunk-6NR36UNB.js} +2 -2
  45. package/dist/{chunk-W77KZHCW.js → chunk-6RH7PRTL.js} +16 -17
  46. package/dist/chunk-6RH7PRTL.js.map +1 -0
  47. package/dist/{chunk-3JVXVJ7L.js → chunk-7OBIBPCV.js} +10 -10
  48. package/dist/{chunk-AR2JDFAE.js → chunk-7Q3RHOA5.js} +2 -2
  49. package/dist/chunk-7ZGPQOFV.js +190 -0
  50. package/dist/chunk-7ZGPQOFV.js.map +1 -0
  51. package/dist/{chunk-QULVCV3M.js → chunk-AJGGBXWA.js} +4 -4
  52. package/dist/{chunk-CADUYBQD.js → chunk-ATL3ZVXT.js} +2 -2
  53. package/dist/{chunk-DMQCLZ4Z.js → chunk-ATY3ZASK.js} +2 -2
  54. package/dist/{chunk-4HDYQL3J.js → chunk-B4CRUZPR.js} +2 -2
  55. package/dist/{chunk-IMZLOJTK.js → chunk-BMU2DS3S.js} +30 -21
  56. package/dist/chunk-BMU2DS3S.js.map +1 -0
  57. package/dist/{chunk-6SAFL5YE.js → chunk-BZ3WMOYX.js} +3 -3
  58. package/dist/{chunk-UHXCLPGC.js → chunk-C3XWJCG7.js} +2 -2
  59. package/dist/chunk-C3XWJCG7.js.map +1 -0
  60. package/dist/{chunk-HXGUIPQB.js → chunk-CKKN25P2.js} +3 -3
  61. package/dist/{chunk-3URQC7EH.js → chunk-CXPOG3ZY.js} +355 -132
  62. package/dist/chunk-CXPOG3ZY.js.map +1 -0
  63. package/dist/{chunk-3FSX6LDG.js → chunk-D2YFQ7XG.js} +18 -3
  64. package/dist/{chunk-3FSX6LDG.js.map → chunk-D2YFQ7XG.js.map} +1 -1
  65. package/dist/{chunk-52JPHN5N.js → chunk-D6SXRMZZ.js} +27 -149
  66. package/dist/chunk-D6SXRMZZ.js.map +1 -0
  67. package/dist/{chunk-2DHSSLOD.js → chunk-DECNV4QK.js} +13 -15
  68. package/dist/chunk-DECNV4QK.js.map +1 -0
  69. package/dist/{chunk-6BU3L4UE.js → chunk-DNKVKO7K.js} +7 -10
  70. package/dist/chunk-DNKVKO7K.js.map +1 -0
  71. package/dist/{chunk-6HFM7EIT.js → chunk-EHRIDNZX.js} +2 -2
  72. package/dist/{chunk-3737A6EA.js → chunk-EHW7NLGD.js} +127 -31
  73. package/dist/chunk-EHW7NLGD.js.map +1 -0
  74. package/dist/{chunk-BEFVYAR5.js → chunk-EQOTJL76.js} +4 -4
  75. package/dist/chunk-EQOTJL76.js.map +1 -0
  76. package/dist/{chunk-E6427JU2.js → chunk-EV2TDHQZ.js} +19 -3
  77. package/dist/chunk-EV2TDHQZ.js.map +1 -0
  78. package/dist/{chunk-WFUIE565.js → chunk-FNYCT27B.js} +17 -14
  79. package/dist/chunk-FNYCT27B.js.map +1 -0
  80. package/dist/{chunk-RTAMLDWP.js → chunk-FU5VYEYK.js} +2 -2
  81. package/dist/chunk-FX3UIDCS.js +66 -0
  82. package/dist/chunk-FX3UIDCS.js.map +1 -0
  83. package/dist/{chunk-7F4DBNSP.js → chunk-GANFIM2M.js} +135 -18
  84. package/dist/chunk-GANFIM2M.js.map +1 -0
  85. package/dist/{chunk-4VUPLMZ6.js → chunk-GCU42IG7.js} +66 -71
  86. package/dist/chunk-GCU42IG7.js.map +1 -0
  87. package/dist/{chunk-RXYYFSBB.js → chunk-GKTW3KLV.js} +4 -4
  88. package/dist/chunk-HK67PX4J.js +27 -0
  89. package/dist/chunk-HK67PX4J.js.map +1 -0
  90. package/dist/{chunk-OF3L2SD6.js → chunk-HOPNIR5R.js} +2 -2
  91. package/dist/{chunk-WLZ47GSL.js → chunk-HSJBJIB2.js} +12 -10
  92. package/dist/{chunk-WLZ47GSL.js.map → chunk-HSJBJIB2.js.map} +1 -1
  93. package/dist/{chunk-ADW22QSB.js → chunk-HWI7GHJZ.js} +4 -4
  94. package/dist/{chunk-GQ3BX5EA.js → chunk-I3ISCYT7.js} +2 -2
  95. package/dist/{chunk-YJ6IONGA.js → chunk-IWKCJCLP.js} +11 -3
  96. package/dist/{chunk-YJ6IONGA.js.map → chunk-IWKCJCLP.js.map} +1 -1
  97. package/dist/{chunk-NJDQ4YSV.js → chunk-IWQPYT6S.js} +4 -4
  98. package/dist/{chunk-JRKZTEZZ.js → chunk-J6I5VR6P.js} +444 -73
  99. package/dist/chunk-J6I5VR6P.js.map +1 -0
  100. package/dist/{chunk-2Z3NCLNX.js → chunk-JHYKSMVX.js} +7 -7
  101. package/dist/{chunk-6FJWSWFT.js → chunk-JIHWBKMQ.js} +3 -3
  102. package/dist/{chunk-YAWK6AWF.js → chunk-JKATP6OE.js} +2 -2
  103. package/dist/{chunk-PL2GHSCM.js → chunk-JMJSCI7U.js} +157 -90
  104. package/dist/chunk-JMJSCI7U.js.map +1 -0
  105. package/dist/{chunk-Q6TEJXBX.js → chunk-JXHNUYQO.js} +31 -49
  106. package/dist/chunk-JXHNUYQO.js.map +1 -0
  107. package/dist/{chunk-WK5XUYYF.js → chunk-JYPRZWCZ.js} +473 -231
  108. package/dist/chunk-JYPRZWCZ.js.map +1 -0
  109. package/dist/{chunk-5ZKS6ZE2.js → chunk-K6CPIK3R.js} +4 -4
  110. package/dist/chunk-K6CPIK3R.js.map +1 -0
  111. package/dist/{chunk-CDB2HVQW.js → chunk-KM6ZXG7U.js} +14 -15
  112. package/dist/chunk-KM6ZXG7U.js.map +1 -0
  113. package/dist/{chunk-DG27IUVI.js → chunk-LC6NE4IQ.js} +2 -2
  114. package/dist/{chunk-WASHZV34.js → chunk-LIR2DJWP.js} +63 -25
  115. package/dist/chunk-LIR2DJWP.js.map +1 -0
  116. package/dist/{chunk-VZ3XFUQ7.js → chunk-LUYPYCHY.js} +16 -22
  117. package/dist/chunk-LUYPYCHY.js.map +1 -0
  118. package/dist/{chunk-G6S5VVHP.js → chunk-M7WBE3OR.js} +10 -10
  119. package/dist/chunk-M7WBE3OR.js.map +1 -0
  120. package/dist/{chunk-VJFMXYKP.js → chunk-MPKP6L5E.js} +2 -2
  121. package/dist/{chunk-IGJCYUT5.js → chunk-NSITFOCJ.js} +1 -1
  122. package/dist/chunk-NSITFOCJ.js.map +1 -0
  123. package/dist/{chunk-FUHKW252.js → chunk-OCJ3JA4O.js} +2 -2
  124. package/dist/{chunk-VCETL77O.js → chunk-ONPVHX2Y.js} +36 -7
  125. package/dist/chunk-ONPVHX2Y.js.map +1 -0
  126. package/dist/{chunk-WLYIROCJ.js → chunk-OQMCFHUX.js} +2 -2
  127. package/dist/{chunk-JRCYZEHU.js → chunk-OR2FYRYR.js} +2 -2
  128. package/dist/{chunk-HNHCQ556.js → chunk-PFWE7FJG.js} +2 -2
  129. package/dist/{chunk-NPP5R7FF.js → chunk-PJX72ICF.js} +22 -18
  130. package/dist/chunk-PJX72ICF.js.map +1 -0
  131. package/dist/{chunk-U5O6GIWZ.js → chunk-POFYIGQ2.js} +3 -3
  132. package/dist/{chunk-35EBKWQU.js → chunk-QH47SQLD.js} +4 -4
  133. package/dist/{chunk-FZ6NYJ7L.js → chunk-QQRRKO7W.js} +11 -8
  134. package/dist/chunk-QQRRKO7W.js.map +1 -0
  135. package/dist/{chunk-HVQGCKY4.js → chunk-QVXZFJBU.js} +2 -2
  136. package/dist/{chunk-FMQJZH4R.js → chunk-RDB66EKD.js} +6 -6
  137. package/dist/{chunk-X56RTUK3.js → chunk-RJZQ2PVD.js} +3 -3
  138. package/dist/{chunk-SUFG5E73.js → chunk-RPRASGEY.js} +2 -2
  139. package/dist/{chunk-XWX7GL56.js → chunk-S2I5MYSA.js} +7 -10
  140. package/dist/chunk-S2I5MYSA.js.map +1 -0
  141. package/dist/{chunk-FFDNKRCY.js → chunk-S6PJ6ZKE.js} +2 -2
  142. package/dist/chunk-S6PJ6ZKE.js.map +1 -0
  143. package/dist/{chunk-JIUVJ4M7.js → chunk-S7PM7Z4K.js} +3 -3
  144. package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
  145. package/dist/chunk-T7IR4N2S.js.map +1 -0
  146. package/dist/{chunk-N35NC4JH.js → chunk-TKBB62DN.js} +2 -2
  147. package/dist/{chunk-YPYHVOXP.js → chunk-UJ4Z67UQ.js} +2 -2
  148. package/dist/chunk-UJ4Z67UQ.js.map +1 -0
  149. package/dist/{chunk-7MNBICB5.js → chunk-W3HAIN6U.js} +16 -14
  150. package/dist/chunk-W3HAIN6U.js.map +1 -0
  151. package/dist/{chunk-4UVDI4XE.js → chunk-WPZ5FVAS.js} +4 -4
  152. package/dist/{chunk-MSWYQLMQ.js → chunk-XINT4VJA.js} +2 -2
  153. package/dist/{chunk-7G6VDWXB.js → chunk-XPEPMK4Y.js} +3 -3
  154. package/dist/chunk-XPEPMK4Y.js.map +1 -0
  155. package/dist/{chunk-W3TVWF6N.js → chunk-YCGLAANM.js} +2 -2
  156. package/dist/{chunk-O2ERS4UJ.js → chunk-YTUFV7U7.js} +80 -51
  157. package/dist/chunk-YTUFV7U7.js.map +1 -0
  158. package/dist/{chunk-FDX7OWWI.js → chunk-YYV53EHO.js} +2 -2
  159. package/dist/{chunk-HNGSV2YC.js → chunk-Z3BZXPRO.js} +67 -10
  160. package/dist/chunk-Z3BZXPRO.js.map +1 -0
  161. package/dist/{chunk-6NVPFKN3.js → chunk-ZIMQDXTQ.js} +92 -35
  162. package/dist/chunk-ZIMQDXTQ.js.map +1 -0
  163. package/dist/{chunk-5JY5TSVY.js → chunk-ZJUZOJVW.js} +25 -31
  164. package/dist/chunk-ZJUZOJVW.js.map +1 -0
  165. package/dist/{chunk-3IXIU6FP.js → chunk-ZY6P7M52.js} +7 -10
  166. package/dist/chunk-ZY6P7M52.js.map +1 -0
  167. package/dist/{chunk-H73G4XF4.js → chunk-ZYZJLYNS.js} +7 -11
  168. package/dist/chunk-ZYZJLYNS.js.map +1 -0
  169. package/dist/classified/index.js +5 -5
  170. package/dist/{classified-marker-2KJAXRRO.js → classified-marker-AZDSDG6V.js} +3 -3
  171. package/dist/collection-facade-WSUAYFJ4.js +45 -0
  172. package/dist/{computed-6G5M3UPH.js → computed-VG2PCM4L.js} +3 -3
  173. package/dist/consent/index.js +10 -10
  174. package/dist/cover/index.js +10 -3
  175. package/dist/custody/index.js +12 -11
  176. package/dist/{dead-filter-DCB62VWW.js → dead-filter-JNQNB3TA.js} +2 -2
  177. package/dist/debug/index.js +1 -1
  178. package/dist/{delegation-MO7YZYJS.js → delegation-5F36DRDH.js} +24 -23
  179. package/dist/delegation-5F36DRDH.js.map +1 -0
  180. package/dist/derivations/index.js +12 -12
  181. package/dist/derive-MPOGZ4NR.js +22 -0
  182. package/dist/directory/index.js +10 -10
  183. package/dist/{dispatch-MJ6SHB3Y.js → dispatch-3ZA733EY.js} +18 -18
  184. package/dist/{dispatch-FZEAWKVM.js → dispatch-TNM5CRLZ.js} +9 -6
  185. package/dist/dispatch-TNM5CRLZ.js.map +1 -0
  186. package/dist/{enclave-JU4YIEPB.js → enclave-Y2ALNDRD.js} +31 -9
  187. package/dist/executor-BBEEUFO3.js +9 -0
  188. package/dist/executor-G6G3YEWR.js +9 -0
  189. package/dist/executor-ZUTUMTPA.js +29 -0
  190. package/dist/export-accessible-S3KEB763.js +23 -0
  191. package/dist/extract-partition-KVCTSUVE.js +38 -0
  192. package/dist/{fanout-sidecar-NNAJQXMX.js → fanout-sidecar-3QZU7ZZX.js} +18 -27
  193. package/dist/fanout-sidecar-3QZU7ZZX.js.map +1 -0
  194. package/dist/find-V4FN5ITT.js +11 -0
  195. package/dist/forget/index.js +9 -9
  196. package/dist/guards/index.js +7 -7
  197. package/dist/history/index.js +23 -20
  198. package/dist/history/index.js.map +1 -1
  199. package/dist/i18n/index.js +14 -14
  200. package/dist/index.d.ts +30 -13
  201. package/dist/index.js +180 -188
  202. package/dist/index.js.map +1 -1
  203. package/dist/indexing/index.js +4 -4
  204. package/dist/introspection/index.js +11 -11
  205. package/dist/issue-5CFBWBRX.js +19 -0
  206. package/dist/kernel/collection.d.ts +8 -2
  207. package/dist/kernel/constants.d.ts +36 -0
  208. package/dist/kernel/enclave/crypto.d.ts +52 -4
  209. package/dist/kernel/enclave/index.d.ts +10 -3
  210. package/dist/kernel/enclave/record-aad.d.ts +131 -0
  211. package/dist/kernel/enclave/record-envelope.d.ts +76 -0
  212. package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
  213. package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
  214. package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
  215. package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
  216. package/dist/kernel/enclave/record-keys/rekey.d.ts +91 -0
  217. package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
  218. package/dist/kernel/errors.d.ts +132 -12
  219. package/dist/kernel/merge-authority.d.ts +25 -0
  220. package/dist/kernel/noydb.d.ts +27 -4
  221. package/dist/kernel/query/builder.d.ts +51 -4
  222. package/dist/kernel/query/join.d.ts +27 -0
  223. package/dist/kernel/query/live.d.ts +31 -9
  224. package/dist/kernel/query/predicate.d.ts +9 -0
  225. package/dist/kernel/refs.d.ts +3 -1
  226. package/dist/kernel/sync-policy.d.ts +0 -2
  227. package/dist/kernel/tier-visibility.d.ts +34 -0
  228. package/dist/kernel/types.d.ts +111 -13
  229. package/dist/kernel/vault.d.ts +14 -8
  230. package/dist/kernel/via/index.d.ts +11 -2
  231. package/dist/kernel/via/reconcile.d.ts +12 -0
  232. package/dist/{ledger-AETNF4OM.js → ledger-MQIIOTZB.js} +11 -11
  233. package/dist/liberate-LW7OKVBH.js +25 -0
  234. package/dist/{link-set-E5HNY67I.js → link-set-5PJBBR63.js} +11 -11
  235. package/dist/{managed-secret-CWQ6PND5.js → managed-secret-ETDG6AAE.js} +11 -3
  236. package/dist/materialized-views/index.js +24 -24
  237. package/dist/migrate-cek-V3VDRV24.js +19 -0
  238. package/dist/migrate-cek-V3VDRV24.js.map +1 -0
  239. package/dist/money/index.js +5 -5
  240. package/dist/noydb-LFDRMYZ5.js +85 -0
  241. package/dist/overlay-views/index.js +4 -4
  242. package/dist/periods/index.js +18 -12
  243. package/dist/pod/index.js +79 -89
  244. package/dist/pod-handle-AZ3CXY5Y.js +41 -0
  245. package/dist/pod-handle-AZ3CXY5Y.js.map +1 -0
  246. package/dist/policy/index.js +11 -4
  247. package/dist/port/to/index.d.ts +4 -4
  248. package/dist/port/to/locator.d.ts +54 -8
  249. package/dist/port/with/i18n-strategy.d.ts +4 -1
  250. package/dist/port/with/lookup-strategy.d.ts +4 -1
  251. package/dist/port/with/merge-authority.d.ts +52 -0
  252. package/dist/port/with/service-bus.d.ts +0 -4
  253. package/dist/port/with/strategies.d.ts +2 -0
  254. package/dist/port/with/team-strategy.d.ts +5 -1
  255. package/dist/portability/index.js +8 -8
  256. package/dist/{post-register-2XSSMGEQ.js → post-register-QCJYRMIK.js} +6 -6
  257. package/dist/query/index.js +6 -6
  258. package/dist/reduce/index.js +6 -6
  259. package/dist/register-JBOEHTVX.js +32 -0
  260. package/dist/registry-5DYHQFJS.js +9 -0
  261. package/dist/registry-EANV44W2.js +9 -0
  262. package/dist/registry-J25H6VB4.js +19 -0
  263. package/dist/registry-R23SQUQH.js +18 -0
  264. package/dist/request-withdrawal-KQ4W4UT5.js +31 -0
  265. package/dist/{reveal-BW36KCOQ.js → reveal-W7BKZSUP.js} +6 -6
  266. package/dist/revoke-H3VSTAIE.js +24 -0
  267. package/dist/satellites/index.js +1 -1
  268. package/dist/schema-update/index.js +2 -2
  269. package/dist/sealed-record/index.js +20 -13
  270. package/dist/sealed-record/index.js.map +1 -1
  271. package/dist/search/index.js +4 -4
  272. package/dist/{seed-GDV5PT4R.js → seed-55FPOMYP.js} +20 -22
  273. package/dist/seed-55FPOMYP.js.map +1 -0
  274. package/dist/sequence/index.js +9 -9
  275. package/dist/session/index.js +10 -10
  276. package/dist/shadow/index.js +2 -2
  277. package/dist/share-link/index.js +1 -1
  278. package/dist/signer-53AQ3BU2.js +25 -0
  279. package/dist/snapshots/index.js +10 -10
  280. package/dist/snapshots/index.js.map +1 -1
  281. package/dist/{stale-ARHFVL5U.js → stale-TH7SSVRV.js} +10 -10
  282. package/dist/storage-WSF7ZKTL.js +23 -0
  283. package/dist/{store-coordination-provider-GFCUOBR6.js → store-coordination-provider-R27VRD6K.js} +18 -12
  284. package/dist/store-coordination-provider-R27VRD6K.js.map +1 -0
  285. package/dist/sync/index.js +11 -11
  286. package/dist/team/index.js +15 -14
  287. package/dist/tiers/index.js +11 -10
  288. package/dist/to/index.js +17 -9
  289. package/dist/to/index.js.map +1 -1
  290. package/dist/transactions/index.js +4 -4
  291. package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
  292. package/dist/util/index.js +1 -1
  293. package/dist/vault-head/index.js +115 -0
  294. package/dist/vault-head/index.js.map +1 -0
  295. package/dist/{verify-RO5RTZOJ.js → verify-M5LQH43C.js} +5 -5
  296. package/dist/via/blob/index.d.ts +3 -0
  297. package/dist/via/lookup/handle.d.ts +4 -1
  298. package/dist/walk-NABCHDZN.js +21 -0
  299. package/dist/with-audit/periods/index.d.ts +3 -3
  300. package/dist/with-audit/periods/periods.d.ts +82 -2
  301. package/dist/with-audit/periods/strategy.d.ts +1 -1
  302. package/dist/with-audit/periods/vault-facade.d.ts +54 -1
  303. package/dist/with-audit/periods/window.d.ts +10 -0
  304. package/dist/with-audit/sealed-record/index.d.ts +13 -0
  305. package/dist/with-audit/tiers/index.d.ts +17 -2
  306. package/dist/with-cargo/adopt-partition.d.ts +1 -1
  307. package/dist/with-cargo/extract-partition.d.ts +1 -1
  308. package/dist/with-cargo/index.d.ts +1 -1
  309. package/dist/with-commit/history/history.d.ts +26 -0
  310. package/dist/with-commit/history/index.d.ts +2 -1
  311. package/dist/with-commit/history/ledger/store.d.ts +7 -1
  312. package/dist/with-commit/history/strategy.d.ts +11 -1
  313. package/dist/with-commit/numbering/index.d.ts +0 -5
  314. package/dist/with-commit/vault-head/active.d.ts +2 -0
  315. package/dist/with-commit/vault-head/head.d.ts +28 -0
  316. package/dist/with-commit/vault-head/index.d.ts +10 -0
  317. package/dist/with-commit/vault-head/strategy.d.ts +127 -0
  318. package/dist/with-commit/vault-head/verify.d.ts +90 -0
  319. package/dist/with-formula/materialized-views/dependency-analyzer.d.ts +4 -0
  320. package/dist/with-formula/materialized-views/projection-legs.d.ts +59 -0
  321. package/dist/with-formula/materialized-views/registry.d.ts +50 -0
  322. package/dist/with-formula/materialized-views/types.d.ts +68 -10
  323. package/dist/with-party/directory/cover/storage.d.ts +0 -8
  324. package/dist/with-party/directory/storage.d.ts +0 -11
  325. package/dist/with-party/directory/visibility.d.ts +0 -21
  326. package/dist/with-party/policy/storage.d.ts +0 -10
  327. package/dist/with-party/team/index.d.ts +1 -1
  328. package/dist/with-party/team/keyring.d.ts +139 -2
  329. package/dist/with-party/team/noydb-facade.d.ts +5 -1
  330. package/dist/with-party/team/roster-tag.d.ts +101 -0
  331. package/dist/with-party/team/tiers.d.ts +2 -1
  332. package/dist/with-pod/format.d.ts +10 -12
  333. package/dist/with-pod/index.d.ts +10 -10
  334. package/dist/with-pod/open.d.ts +2 -2
  335. package/dist/with-pod/pod-handle.d.ts +19 -0
  336. package/dist/with-pod/pod-store.d.ts +0 -8
  337. package/dist/with-pod/{bundle.d.ts → pod.d.ts} +11 -19
  338. package/dist/with-pod/ulid.d.ts +1 -1
  339. package/dist/with-shape/blobs/blob-compaction.d.ts +13 -0
  340. package/dist/with-shape/blobs/blob-set.d.ts +83 -11
  341. package/dist/with-shape/blobs/orphan-report.d.ts +62 -0
  342. package/dist/with-shape/introspection/index.d.ts +1 -0
  343. package/dist/with-sync/engine.d.ts +54 -5
  344. package/dist/with-sync/strategy.d.ts +3 -0
  345. package/dist/withdraw-accessible-VCINIG6V.js +28 -0
  346. package/package.json +10 -4
  347. package/dist/api-RXUMEKT3.js +0 -20
  348. package/dist/backup-KULFZ2T4.js.map +0 -1
  349. package/dist/bundle-handle-GFNHT52M.js +0 -36
  350. package/dist/bundle-handle-GFNHT52M.js.map +0 -1
  351. package/dist/chunk-2DHSSLOD.js.map +0 -1
  352. package/dist/chunk-3737A6EA.js.map +0 -1
  353. package/dist/chunk-3IXIU6FP.js.map +0 -1
  354. package/dist/chunk-3URQC7EH.js.map +0 -1
  355. package/dist/chunk-4GZ6XOVW.js.map +0 -1
  356. package/dist/chunk-4I72F5DF.js.map +0 -1
  357. package/dist/chunk-4VUPLMZ6.js.map +0 -1
  358. package/dist/chunk-52JPHN5N.js.map +0 -1
  359. package/dist/chunk-55LKVALY.js.map +0 -1
  360. package/dist/chunk-5JY5TSVY.js.map +0 -1
  361. package/dist/chunk-5ZKS6ZE2.js.map +0 -1
  362. package/dist/chunk-6BU3L4UE.js.map +0 -1
  363. package/dist/chunk-6NVPFKN3.js.map +0 -1
  364. package/dist/chunk-7F4DBNSP.js.map +0 -1
  365. package/dist/chunk-7G6VDWXB.js.map +0 -1
  366. package/dist/chunk-7H73RIE3.js +0 -45
  367. package/dist/chunk-7H73RIE3.js.map +0 -1
  368. package/dist/chunk-7MNBICB5.js.map +0 -1
  369. package/dist/chunk-AFHQATY4.js +0 -47
  370. package/dist/chunk-AFHQATY4.js.map +0 -1
  371. package/dist/chunk-AHLJSVRL.js.map +0 -1
  372. package/dist/chunk-BEFVYAR5.js.map +0 -1
  373. package/dist/chunk-CDB2HVQW.js.map +0 -1
  374. package/dist/chunk-CEJWMBXO.js.map +0 -1
  375. package/dist/chunk-E6427JU2.js.map +0 -1
  376. package/dist/chunk-FFDNKRCY.js.map +0 -1
  377. package/dist/chunk-FZ6NYJ7L.js.map +0 -1
  378. package/dist/chunk-G6S5VVHP.js.map +0 -1
  379. package/dist/chunk-GAG7QOVO.js.map +0 -1
  380. package/dist/chunk-H73G4XF4.js.map +0 -1
  381. package/dist/chunk-HNGSV2YC.js.map +0 -1
  382. package/dist/chunk-IGJCYUT5.js.map +0 -1
  383. package/dist/chunk-IMZLOJTK.js.map +0 -1
  384. package/dist/chunk-J7FM3RAU.js.map +0 -1
  385. package/dist/chunk-JJNOLSG5.js.map +0 -1
  386. package/dist/chunk-JRKZTEZZ.js.map +0 -1
  387. package/dist/chunk-JXIDGFKS.js.map +0 -1
  388. package/dist/chunk-NPP5R7FF.js.map +0 -1
  389. package/dist/chunk-O2ERS4UJ.js.map +0 -1
  390. package/dist/chunk-PDLLCOGD.js.map +0 -1
  391. package/dist/chunk-PL2GHSCM.js.map +0 -1
  392. package/dist/chunk-PNKHAKQ7.js.map +0 -1
  393. package/dist/chunk-PXCBVDFY.js.map +0 -1
  394. package/dist/chunk-Q6TEJXBX.js.map +0 -1
  395. package/dist/chunk-UHXCLPGC.js.map +0 -1
  396. package/dist/chunk-VCETL77O.js.map +0 -1
  397. package/dist/chunk-VZ3XFUQ7.js.map +0 -1
  398. package/dist/chunk-W77KZHCW.js.map +0 -1
  399. package/dist/chunk-WASHZV34.js.map +0 -1
  400. package/dist/chunk-WFUIE565.js.map +0 -1
  401. package/dist/chunk-WK5XUYYF.js.map +0 -1
  402. package/dist/chunk-XWX7GL56.js.map +0 -1
  403. package/dist/chunk-YPYHVOXP.js.map +0 -1
  404. package/dist/chunk-ZJADGNYF.js.map +0 -1
  405. package/dist/collection-facade-QEJIM6BC.js +0 -45
  406. package/dist/delegation-MO7YZYJS.js.map +0 -1
  407. package/dist/derive-IUA6JFLB.js +0 -22
  408. package/dist/dispatch-FZEAWKVM.js.map +0 -1
  409. package/dist/executor-CYJQLKKI.js +0 -9
  410. package/dist/executor-S4QIKEHW.js +0 -9
  411. package/dist/executor-YIQB2S6N.js +0 -29
  412. package/dist/export-accessible-4S36PQNR.js +0 -23
  413. package/dist/extract-partition-IO7FDZ2P.js +0 -38
  414. package/dist/fanout-sidecar-NNAJQXMX.js.map +0 -1
  415. package/dist/find-RBBYKXI7.js +0 -11
  416. package/dist/issue-RIVHSY2S.js +0 -19
  417. package/dist/liberate-GFN4C7RR.js +0 -24
  418. package/dist/noydb-3MT74MZS.js +0 -83
  419. package/dist/register-4EFJCVYD.js +0 -32
  420. package/dist/registry-4SDHHOJ7.js +0 -18
  421. package/dist/registry-CZVINVQH.js +0 -9
  422. package/dist/registry-IKUR2MXD.js +0 -9
  423. package/dist/registry-OYTFGWVK.js +0 -19
  424. package/dist/request-withdrawal-KGXGDPVQ.js +0 -31
  425. package/dist/revoke-JFN773KF.js +0 -24
  426. package/dist/seed-GDV5PT4R.js.map +0 -1
  427. package/dist/signer-TA55QB6R.js +0 -25
  428. package/dist/storage-V7MTFAQJ.js +0 -23
  429. package/dist/store-coordination-provider-GFCUOBR6.js.map +0 -1
  430. package/dist/walk-3ZECBFDA.js +0 -21
  431. package/dist/with-pod/bundle-handle.d.ts +0 -9
  432. package/dist/withdraw-accessible-7PG4DYQK.js +0 -28
  433. /package/dist/{api-RXUMEKT3.js.map → api-6X2VLZ7J.js.map} +0 -0
  434. /package/dist/{chunk-KUDZVJKQ.js.map → chunk-22GR3O4J.js.map} +0 -0
  435. /package/dist/{chunk-CCZJJ4I2.js.map → chunk-2CBFYXJX.js.map} +0 -0
  436. /package/dist/{chunk-FAXZQ5UF.js.map → chunk-323MN67Z.js.map} +0 -0
  437. /package/dist/{chunk-VMCCGUQB.js.map → chunk-36CEG6CM.js.map} +0 -0
  438. /package/dist/{chunk-747LRSOO.js.map → chunk-4K6BIMLF.js.map} +0 -0
  439. /package/dist/{chunk-FNSMZQS4.js.map → chunk-5IHGJHWC.js.map} +0 -0
  440. /package/dist/{chunk-7TSYBD3E.js.map → chunk-65JXA63J.js.map} +0 -0
  441. /package/dist/{chunk-Z45YRGFO.js.map → chunk-6NR36UNB.js.map} +0 -0
  442. /package/dist/{chunk-3JVXVJ7L.js.map → chunk-7OBIBPCV.js.map} +0 -0
  443. /package/dist/{chunk-AR2JDFAE.js.map → chunk-7Q3RHOA5.js.map} +0 -0
  444. /package/dist/{chunk-QULVCV3M.js.map → chunk-AJGGBXWA.js.map} +0 -0
  445. /package/dist/{chunk-CADUYBQD.js.map → chunk-ATL3ZVXT.js.map} +0 -0
  446. /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-ATY3ZASK.js.map} +0 -0
  447. /package/dist/{chunk-4HDYQL3J.js.map → chunk-B4CRUZPR.js.map} +0 -0
  448. /package/dist/{chunk-6SAFL5YE.js.map → chunk-BZ3WMOYX.js.map} +0 -0
  449. /package/dist/{chunk-HXGUIPQB.js.map → chunk-CKKN25P2.js.map} +0 -0
  450. /package/dist/{chunk-6HFM7EIT.js.map → chunk-EHRIDNZX.js.map} +0 -0
  451. /package/dist/{chunk-RTAMLDWP.js.map → chunk-FU5VYEYK.js.map} +0 -0
  452. /package/dist/{chunk-RXYYFSBB.js.map → chunk-GKTW3KLV.js.map} +0 -0
  453. /package/dist/{chunk-OF3L2SD6.js.map → chunk-HOPNIR5R.js.map} +0 -0
  454. /package/dist/{chunk-ADW22QSB.js.map → chunk-HWI7GHJZ.js.map} +0 -0
  455. /package/dist/{chunk-GQ3BX5EA.js.map → chunk-I3ISCYT7.js.map} +0 -0
  456. /package/dist/{chunk-NJDQ4YSV.js.map → chunk-IWQPYT6S.js.map} +0 -0
  457. /package/dist/{chunk-2Z3NCLNX.js.map → chunk-JHYKSMVX.js.map} +0 -0
  458. /package/dist/{chunk-6FJWSWFT.js.map → chunk-JIHWBKMQ.js.map} +0 -0
  459. /package/dist/{chunk-YAWK6AWF.js.map → chunk-JKATP6OE.js.map} +0 -0
  460. /package/dist/{chunk-DG27IUVI.js.map → chunk-LC6NE4IQ.js.map} +0 -0
  461. /package/dist/{chunk-VJFMXYKP.js.map → chunk-MPKP6L5E.js.map} +0 -0
  462. /package/dist/{chunk-FUHKW252.js.map → chunk-OCJ3JA4O.js.map} +0 -0
  463. /package/dist/{chunk-WLYIROCJ.js.map → chunk-OQMCFHUX.js.map} +0 -0
  464. /package/dist/{chunk-JRCYZEHU.js.map → chunk-OR2FYRYR.js.map} +0 -0
  465. /package/dist/{chunk-HNHCQ556.js.map → chunk-PFWE7FJG.js.map} +0 -0
  466. /package/dist/{chunk-U5O6GIWZ.js.map → chunk-POFYIGQ2.js.map} +0 -0
  467. /package/dist/{chunk-35EBKWQU.js.map → chunk-QH47SQLD.js.map} +0 -0
  468. /package/dist/{chunk-HVQGCKY4.js.map → chunk-QVXZFJBU.js.map} +0 -0
  469. /package/dist/{chunk-FMQJZH4R.js.map → chunk-RDB66EKD.js.map} +0 -0
  470. /package/dist/{chunk-X56RTUK3.js.map → chunk-RJZQ2PVD.js.map} +0 -0
  471. /package/dist/{chunk-SUFG5E73.js.map → chunk-RPRASGEY.js.map} +0 -0
  472. /package/dist/{chunk-JIUVJ4M7.js.map → chunk-S7PM7Z4K.js.map} +0 -0
  473. /package/dist/{chunk-N35NC4JH.js.map → chunk-TKBB62DN.js.map} +0 -0
  474. /package/dist/{chunk-4UVDI4XE.js.map → chunk-WPZ5FVAS.js.map} +0 -0
  475. /package/dist/{chunk-MSWYQLMQ.js.map → chunk-XINT4VJA.js.map} +0 -0
  476. /package/dist/{chunk-W3TVWF6N.js.map → chunk-YCGLAANM.js.map} +0 -0
  477. /package/dist/{chunk-FDX7OWWI.js.map → chunk-YYV53EHO.js.map} +0 -0
  478. /package/dist/{classified-marker-2KJAXRRO.js.map → classified-marker-AZDSDG6V.js.map} +0 -0
  479. /package/dist/{collection-facade-QEJIM6BC.js.map → collection-facade-WSUAYFJ4.js.map} +0 -0
  480. /package/dist/{computed-6G5M3UPH.js.map → computed-VG2PCM4L.js.map} +0 -0
  481. /package/dist/{dead-filter-DCB62VWW.js.map → dead-filter-JNQNB3TA.js.map} +0 -0
  482. /package/dist/{derive-IUA6JFLB.js.map → derive-MPOGZ4NR.js.map} +0 -0
  483. /package/dist/{dispatch-MJ6SHB3Y.js.map → dispatch-3ZA733EY.js.map} +0 -0
  484. /package/dist/{enclave-JU4YIEPB.js.map → enclave-Y2ALNDRD.js.map} +0 -0
  485. /package/dist/{executor-CYJQLKKI.js.map → executor-BBEEUFO3.js.map} +0 -0
  486. /package/dist/{executor-S4QIKEHW.js.map → executor-G6G3YEWR.js.map} +0 -0
  487. /package/dist/{executor-YIQB2S6N.js.map → executor-ZUTUMTPA.js.map} +0 -0
  488. /package/dist/{export-accessible-4S36PQNR.js.map → export-accessible-S3KEB763.js.map} +0 -0
  489. /package/dist/{extract-partition-IO7FDZ2P.js.map → extract-partition-KVCTSUVE.js.map} +0 -0
  490. /package/dist/{find-RBBYKXI7.js.map → find-V4FN5ITT.js.map} +0 -0
  491. /package/dist/{issue-RIVHSY2S.js.map → issue-5CFBWBRX.js.map} +0 -0
  492. /package/dist/{ledger-AETNF4OM.js.map → ledger-MQIIOTZB.js.map} +0 -0
  493. /package/dist/{liberate-GFN4C7RR.js.map → liberate-LW7OKVBH.js.map} +0 -0
  494. /package/dist/{link-set-E5HNY67I.js.map → link-set-5PJBBR63.js.map} +0 -0
  495. /package/dist/{managed-secret-CWQ6PND5.js.map → managed-secret-ETDG6AAE.js.map} +0 -0
  496. /package/dist/{noydb-3MT74MZS.js.map → noydb-LFDRMYZ5.js.map} +0 -0
  497. /package/dist/{post-register-2XSSMGEQ.js.map → post-register-QCJYRMIK.js.map} +0 -0
  498. /package/dist/{register-4EFJCVYD.js.map → register-JBOEHTVX.js.map} +0 -0
  499. /package/dist/{registry-4SDHHOJ7.js.map → registry-5DYHQFJS.js.map} +0 -0
  500. /package/dist/{registry-CZVINVQH.js.map → registry-EANV44W2.js.map} +0 -0
  501. /package/dist/{registry-IKUR2MXD.js.map → registry-J25H6VB4.js.map} +0 -0
  502. /package/dist/{registry-OYTFGWVK.js.map → registry-R23SQUQH.js.map} +0 -0
  503. /package/dist/{request-withdrawal-KGXGDPVQ.js.map → request-withdrawal-KQ4W4UT5.js.map} +0 -0
  504. /package/dist/{reveal-BW36KCOQ.js.map → reveal-W7BKZSUP.js.map} +0 -0
  505. /package/dist/{revoke-JFN773KF.js.map → revoke-H3VSTAIE.js.map} +0 -0
  506. /package/dist/{signer-TA55QB6R.js.map → signer-53AQ3BU2.js.map} +0 -0
  507. /package/dist/{stale-ARHFVL5U.js.map → stale-TH7SSVRV.js.map} +0 -0
  508. /package/dist/{storage-V7MTFAQJ.js.map → storage-WSF7ZKTL.js.map} +0 -0
  509. /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
  510. /package/dist/{verify-RO5RTZOJ.js.map → verify-M5LQH43C.js.map} +0 -0
  511. /package/dist/{walk-3ZECBFDA.js.map → walk-NABCHDZN.js.map} +0 -0
  512. /package/dist/{withdraw-accessible-7PG4DYQK.js.map → withdraw-accessible-VCINIG6V.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/port/with/i18n-strategy.ts","../src/kernel/paths.ts","../src/via/i18n/policy.ts","../src/via/i18n/script.ts","../src/via/i18n/binding.ts","../src/via/i18n/core.ts"],"sourcesContent":["/**\n * i18n strategy seam (#623 Task 7 — moved out of `via/i18n/strategy.ts`\n * and `via/i18n/dictionary.ts`, precedent: `port/with/lazy-strategy.ts`).\n * Lives on the `/with` port (the one seam the kernel spine may import\n * statically) so `Collection`/`Vault` can hold the `NO_I18N` default and the\n * two reserved-name/brand predicates without a spine→service static import.\n *\n * Core imports `I18nStrategy` type-only + `NO_I18N` stub; real\n * `applyI18nLocale` / `validateI18nTextValue` / `DictionaryHandle` are only\n * reachable via `withI18n()` in `via/i18n/active.ts`.\n *\n * Solo apps that don't use `i18nText()` fields, don't declare `dictKey()`\n * fields, and don't open a `vault.dictionary(...)` handle ship none of the\n * ~854 LOC behind this seam.\n *\n * Behavior under NO_I18N:\n *\n * - **applyI18nLocale** — returns the record unchanged. Apps without\n * any i18n descriptors never observe a difference; apps that\n * *did* declare i18nText/dictKey fields without opting into the\n * strategy still get raw values back (locale resolution silently\n * skipped). The validators below ensure the misconfiguration is\n * caught at write time instead.\n * - **validateI18nTextValue** — throws when called. Only fires when\n * a collection declared `i18nFields`; if you declared the field,\n * you must opt in.\n * - **buildDictionaryHandle** — throws when called. Only fires when\n * user code calls `vault.dictionary(...)`.\n *\n * #650 Task 1 (via-lookup extraction, phase D): the real\n * `buildDictionaryHandle` (in `via/i18n/active.ts`) now delegates to\n * `withLookup().buildLookupHandle` (`via/lookup/active.ts`) — same\n * handle (`LookupHandle`, aliased as `DictionaryHandle`), new home. This\n * interface's shape is unchanged.\n *\n * @internal\n */\n\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport type { NoydbEventEmitter } from '../../kernel/events.js'\nimport type { I18nTextDescriptor } from '../../via/i18n/core.js'\nimport type { Layer } from '../../via/i18n/policy.js'\nimport type { ScriptWarning } from '../../via/i18n/script.js'\nimport type { DictKeyDescriptor, DictionaryHandle, DictionaryOptions, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\nimport type { ViaCryptoCtx } from '../../kernel/via/index.js'\nimport type { EncryptedEnvelope } from '../../kernel/types.js'\n\n/**\n * Options accepted by `I18nStrategy.buildDictionaryHandle`. Mirrors\n * the `DictionaryHandle` constructor verbatim — kept here so core\n * code never imports the dictionary module at runtime.\n *\n * @internal\n */\nexport interface BuildDictionaryHandleOptions<Keys extends string = string> {\n adapter: NoydbStore\n compartmentName: string\n dictionaryName: string\n keyring: UnlockedKeyring\n /**\n * The `reservedEnvelopes('_dict_')` capability (#629 Task 4) — DictionaryHandle's\n * sanctioned crypto door onto its `_dict_<name>` collection. Bound by the\n * Vault to its own `getDEK`, the same per-collection-name DEK resolver\n * every other collection uses.\n */\n reservedEnvelopes: ReturnType<ViaCryptoCtx['reservedEnvelopes']>\n encrypted: boolean\n ledger: LedgerStore | undefined\n options: DictionaryOptions\n findAndUpdateReferences:\n | ((\n dictionaryName: string,\n oldKey: string,\n newKey: string,\n ) => Promise<void>)\n | undefined\n emitter: NoydbEventEmitter\n /**\n * Used by the active strategy to satisfy the generic-key parameter\n * on the returned handle. The NO_I18N stub never reads it.\n */\n // marker generic — runtime sees no value\n _keyMarker?: Keys\n /** #650 Task 4 (#647) — choke-point participation hooks, passed through to `buildLookupHandle`. */\n onDirty?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n onRecordMutated?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n /**\n * #647 fix wave 1 — mints a version-ordered delete-marker envelope, passed through to\n * `buildLookupHandle`. See `port/with/lookup-strategy.ts`'s `BuildLookupHandleOptions` doc\n * comment for why this is injected rather than imported by the handle itself.\n */\n buildDeleteMarker: (version: number, actor: string) => EncryptedEnvelope\n /** #650 Task 5 (#648) — the real reference check, passed through to `buildLookupHandle`. */\n checkReferencesOnDelete?: ((key: string) => Promise<unknown>) | undefined\n}\n\n/**\n * @internal\n */\nexport interface I18nStrategy {\n /**\n * Resolve `i18nText` fields on a record to the requested locale and\n * return a new object. Returns the input unchanged under\n * `NO_I18N`.\n */\n applyI18nLocale(\n record: Record<string, unknown>,\n fields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n layer?: Layer,\n ): Record<string, unknown>\n\n /**\n * Validate that an i18nText field's value satisfies its descriptor\n * (required locales present, etc.). Throws under `NO_I18N` —\n * declaring i18nFields without opting in is a misconfiguration.\n */\n validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n ): void\n\n /**\n * Enforce per-locale script constraints over an i18nText value map\n * (write-time). Returns the (possibly filtered) value plus any\n * non-fatal warnings. Returns the value unchanged when the field has\n * no `script` option, or under `NO_I18N`.\n */\n enforceScript(\n value: Record<string, unknown>,\n field: string,\n descriptor: I18nTextDescriptor,\n exempt?: ReadonlySet<string>,\n ): { value: Record<string, unknown>; warnings: ScriptWarning[] }\n\n /**\n * Per-field locales that are unchanged round-tripped densify fills (exempt\n * from write-time script enforcement). Empty under NO_I18N.\n */\n computeExemptFills(\n prior: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n fields: Record<string, I18nTextDescriptor>,\n ): Map<string, Set<string>>\n\n /**\n * Eager-fill empty i18n slots from each field's substitute chain and record\n * provenance in `record['_i18nFilled']`. Mutates `record`. No-op under\n * NO_I18N.\n */\n densify(\n record: Record<string, unknown>,\n prior: Record<string, unknown> | undefined,\n fields: Record<string, I18nTextDescriptor>,\n ): void\n\n /**\n * Construct a typed `DictionaryHandle` for the named dictionary.\n * Throws under `NO_I18N`.\n */\n buildDictionaryHandle<Keys extends string = string>(\n opts: BuildDictionaryHandleOptions<Keys>,\n ): DictionaryHandle<Keys>\n}\n\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op} requires the i18n strategy. Import ` +\n '`{ withI18n }` from \"@noy-db/hub/i18n\" and pass it to ' +\n '`createNoydb({ i18nStrategy: withI18n() })`.',\n )\n}\n\n/**\n * No-i18n stub. Locale resolution is the identity; validation and\n * dictionary construction throw with an actionable pointer.\n *\n * @internal\n */\nexport const NO_I18N: I18nStrategy = {\n applyI18nLocale(record) { return record },\n validateI18nTextValue() { throw notEnabled('i18nText field validation') },\n enforceScript(value) { return { value, warnings: [] } },\n computeExemptFills() { return new Map<string, Set<string>>() },\n densify() {},\n buildDictionaryHandle() { throw notEnabled('vault.dictionary()') },\n}\n\n/**\n * Return true when a collection name is a reserved dictionary collection\n * (the `_dict_*` prefix). Mirrors `DICT_COLLECTION_PREFIX` — now on\n * `via/lookup/handle.ts` (#650 Task 1), re-exported from\n * `via/i18n/dictionary.ts` for compat — duplicated here (not\n * imported) so this port has no VALUE dependency back on the feature; keep\n * the two in sync if the prefix ever changes.\n */\nexport function isDictCollectionName(name: string): boolean {\n return name.startsWith('_dict_')\n}\n\n/** Runtime predicate for detecting a StaticDictDescriptor. */\nexport function isStaticDictDescriptor(x: unknown): x is StaticDictDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbStaticDict?: unknown })._noydbStaticDict === true\n )\n}\n\n/**\n * Runtime predicate for detecting an I18nTextDescriptor. Pure tag check —\n * moved here (#623 Task 11) alongside `isStaticDictDescriptor` so\n * `kernel/via/compose.ts` (`mergeViaFields`'s descriptor-shape classification)\n * can reach it through the port instead of importing `via/i18n/core.js`\n * directly. Re-exported from that module for compat with existing importers.\n */\nexport function isI18nTextDescriptor(x: unknown): x is I18nTextDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbI18nText?: unknown })._noydbI18nText === true\n )\n}\n\n/**\n * Runtime predicate for detecting a DictKeyDescriptor. Pure tag check —\n * moved here (#623 Task 11) for the same reason as `isI18nTextDescriptor`\n * above. Re-exported from `via/i18n/dictionary.js` for compat with\n * existing importers.\n */\nexport function isDictKeyDescriptor(x: unknown): x is DictKeyDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _noydbDictKey?: unknown })._noydbDictKey === true\n )\n}\n\n/**\n * Type-only re-exports (#623 Task 8) — the kernel spine (collection.ts,\n * collection-config.ts, vault.ts, types.ts) imports these descriptor/handle\n * types through the port instead of reaching into `via/i18n/*`\n * directly, so `src/kernel/**` carries no via-i18n specifier at all.\n * `isolatedModules: true` erases these at build time — no runtime coupling.\n */\nexport type { I18nTextDescriptor } from '../../via/i18n/core.js'\nexport type { DictKeyDescriptor, DictionaryHandle, DictionaryOptions, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\nexport type { Layer } from '../../via/i18n/policy.js'\nexport type { ScriptWarning } from '../../via/i18n/script.js'\n","/**\n * Generic dotted-path / `[]`-wildcard record helpers. Kernel-owned:\n * these carry zero i18n logic — they were extracted out of\n * `via/i18n/core.ts` (Task 7, #623) so kernel call-sites (put-time\n * validation, densify) can import them without a spine→service edge.\n *\n * @internal\n */\n\n/**\n * Return all leaf values at `path`, expanding `[].` array wildcards.\n *\n * - `'name'` → `[obj.name]`\n * - `'address.lineOne'` → `[obj.address.lineOne]`\n * - `'contacts[].title'` → `[obj.contacts[0].title, obj.contacts[1].title, …]`\n *\n * Returns an empty array when the path does not resolve (missing key,\n * wrong type, etc.). Used by `enforceI18nOnPut` to validate nested fields.\n */\nexport function getAtPath(obj: Record<string, unknown>, path: string): unknown[] {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return []\n return arr.flatMap(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return []\n return getAtPath(item as Record<string, unknown>, restPath)\n })\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return []\n return getAtPath(nested as Record<string, unknown>, rest)\n }\n const val = obj[path]\n return val !== undefined ? [val] : []\n}\n\n/**\n * Mutate `obj` in-place, setting `value` at the nested `path`.\n * Supports dot notation (`'address.lineOne'`) but not array wildcards —\n * auto-translate on `contacts[].title` style paths is not supported.\n */\nexport function setAtPathInPlace(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): void {\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return\n setAtPathInPlace(nested as Record<string, unknown>, rest, value)\n return\n }\n obj[path] = value\n}\n","/**\n * Per-layer i18n resolution policy.\n *\n * `onMissing` governs what happens when a multilingual field is resolved\n * to a target locale that is absent. It may be a single scalar policy or\n * a per-layer map, so a field can be lenient at the app read boundary but\n * strict inside a materialized view.\n *\n * Effective policy for layer `λ`:\n *\n * ```\n * explicit(λ) = typeof onMissing === 'object' ? onMissing[λ] : undefined\n * scalar = typeof onMissing === 'string' ? onMissing : undefined\n * policy(λ) = explicit(λ) ?? layerDefault(λ) ?? scalar ?? 'throw'\n * ```\n *\n * - `layerDefault('guard') = 'substitute'` — guards are lenient unless\n * EXPLICITLY overridden; they never inherit a scalar policy (a guard\n * reading a display value must not hard-fail on a missing locale).\n * - every other layer has no default, so it inherits the scalar, else\n * falls back to `'throw'` (today's behavior — zero breaking change).\n *\n * @public\n */\nexport type OnMissing = 'substitute' | 'null' | 'throw'\n\n/**\n * The contexts in which a multilingual field is resolved. Each can carry\n * its own `onMissing` policy.\n *\n * - `read` — ordinary app reads (`get`/`list`/query projection).\n * - `guard` — a guard callback reading a value.\n * - `join` — a joined record expanded onto a row.\n * - `mv` — materialized-view input.\n * - `derivation` — derivation input.\n * - `export` — bundle/cover export.\n */\nexport type Layer = 'read' | 'guard' | 'join' | 'mv' | 'derivation' | 'export'\n\n/** Field-level policy: a single scalar, or a per-layer map. */\nexport type OnMissingPolicy = OnMissing | Partial<Record<Layer, OnMissing>>\n\n/**\n * Resolve the effective `OnMissing` for a layer from a field's declared\n * policy. See module docs for the resolution rule.\n */\nexport function resolvePolicy(\n onMissing: OnMissingPolicy | undefined,\n layer: Layer,\n): OnMissing {\n const explicit =\n onMissing && typeof onMissing === 'object' ? onMissing[layer] : undefined\n const scalar = typeof onMissing === 'string' ? onMissing : undefined\n const layerDefault: OnMissing | undefined =\n layer === 'guard' ? 'substitute' : undefined\n return explicit ?? layerDefault ?? scalar ?? 'throw'\n}\n","/**\n * Per-locale script enforcement for `i18nText` fields (write-time).\n *\n * Each locale slot's string is validated against an allowed set of\n * Unicode scripts. `'auto'` infers the set from the locale code with\n * **asymmetric Latin tolerance**: every non-Latin-script locale\n * also allows `Latin`, because proper names and addresses in those\n * locales routinely embed Latin brand/building/technical names — while\n * Latin-script locales do NOT allow other scripts, so the common error\n * (e.g. Thai text dumped into an `en` slot) is still caught.\n *\n * The always-on baseline is `Common` (digits, punctuation), `Inherited`\n * and `Mark` (combining diacritics, joiners, harakat, tone marks), and\n * whitespace — so Latin digits and in-script combining marks never\n * false-reject.\n *\n * @public\n */\nimport { ScriptViolationError } from '../../kernel/errors.js'\nimport type { I18nTextDescriptor } from './core.js'\n\n/** Locales whose base language is written in the Latin script. */\nconst LATIN_BASE = new Set([\n 'en', 'fr', 'de', 'es', 'it', 'pt', 'nl', 'sv', 'no', 'da', 'fi', 'is',\n 'pl', 'cs', 'sk', 'hu', 'ro', 'hr', 'sl', 'et', 'lv', 'lt', 'tr', 'vi',\n 'id', 'ms', 'tl', 'sw', 'af', 'ca', 'gl', 'eu', 'cy', 'ga',\n])\n\n/** Base-language → primary (non-Latin) scripts. Latin is appended by inferScripts. */\nconst SCRIPT_TABLE: Record<string, readonly string[]> = {\n th: ['Thai'],\n ko: ['Hangul', 'Han'],\n ja: ['Han', 'Hiragana', 'Katakana'],\n zh: ['Han'],\n ar: ['Arabic'],\n fa: ['Arabic'],\n ur: ['Arabic'],\n ru: ['Cyrillic'],\n uk: ['Cyrillic'],\n bg: ['Cyrillic'],\n sr: ['Cyrillic'],\n he: ['Hebrew'],\n el: ['Greek'],\n hi: ['Devanagari'],\n ta: ['Tamil'],\n km: ['Khmer'],\n lo: ['Lao'],\n my: ['Myanmar'],\n}\n\n/** Map a BCP-47 script subtag (e.g. `Latn`, `Cyrl`) to allowed scripts. */\nconst SUBTAG_SCRIPTS: Record<string, readonly string[]> = {\n Latn: ['Latin'],\n Cyrl: ['Cyrillic', 'Latin'],\n Hans: ['Han', 'Latin'],\n Hant: ['Han', 'Latin'],\n Thai: ['Thai', 'Latin'],\n Arab: ['Arabic', 'Latin'],\n}\n\n/**\n * Infer the allowed Unicode scripts for a BCP-47 locale, with asymmetric\n * Latin tolerance. A script subtag (`th-Latn`) wins over the base\n * language. Unknown locales default to `['Latin']`.\n */\nexport function inferScripts(locale: string): readonly string[] {\n const parts = locale.split('-')\n const subtag = parts.find((t) => /^[A-Z][a-z]{3}$/.test(t))\n if (subtag && SUBTAG_SCRIPTS[subtag]) return SUBTAG_SCRIPTS[subtag]\n\n const base = (parts[0] ?? '').toLowerCase()\n if (LATIN_BASE.has(base)) return ['Latin']\n const primary = SCRIPT_TABLE[base]\n if (primary) return [...primary, 'Latin'] // asymmetric Latin tolerance\n return ['Latin']\n}\n\n/** Resolve the allowed scripts for a field's locale slot. */\nfunction allowedFor(descriptor: I18nTextDescriptor, locale: string): readonly string[] {\n const script = descriptor.options.script\n if (script && script !== 'auto') {\n const explicit = script[locale]\n if (explicit) return explicit\n }\n return inferScripts(locale)\n}\n\n/** Always-allowed baseline character classes (besides the named scripts). */\nconst BASELINE = String.raw`\\p{White_Space}\\p{Script=Common}\\p{Script=Inherited}\\p{Mark}`\n\n/** Build a whole-string matcher for the allowed scripts. */\nfunction fullMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`^[${BASELINE}${cls}]*$`, 'u')\n}\n\n/** Build a single-character matcher (for sampling / stripping). */\nfunction charMatcher(scripts: readonly string[]): RegExp {\n const cls = scripts.map((s) => `\\\\p{Script=${s}}`).join('')\n return new RegExp(`[${BASELINE}${cls}]`, 'u')\n}\n\n/** Collect a short sample of characters that violate the allowed scripts. */\nfunction offendingSample(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n const bad: string[] = []\n for (const ch of str) {\n if (!ok.test(ch)) bad.push(ch)\n if (bad.length >= 8) break\n }\n return bad.join('')\n}\n\n/** Remove characters that violate the allowed scripts. */\nfunction stripDisallowed(str: string, scripts: readonly string[]): string {\n const ok = charMatcher(scripts)\n let out = ''\n for (const ch of str) if (ok.test(ch)) out += ch\n return out\n}\n\n/** A non-fatal script violation recorded under `'filter'`/`'warn'` modes. */\nexport interface ScriptWarning {\n readonly field: string\n readonly locale: string\n readonly expected: readonly string[]\n readonly sample: string\n}\n\n/**\n * Enforce a field's script constraint over an i18nText value map.\n *\n * - No `script` option ⇒ returns the value unchanged.\n * - `onScriptViolation: 'reject'` (default) ⇒ throws {@link ScriptViolationError}.\n * - `'filter'` ⇒ returns a copy with disallowed characters stripped + warnings.\n * - `'warn'` ⇒ returns the value unchanged + warnings.\n */\nexport function enforceScript(\n value: Record<string, unknown>,\n field: string,\n descriptor: I18nTextDescriptor,\n exempt?: ReadonlySet<string>,\n): { value: Record<string, unknown>; warnings: ScriptWarning[] } {\n const opt = descriptor.options\n if (!opt.script) return { value, warnings: [] }\n\n const mode = opt.onScriptViolation ?? 'reject'\n const warnings: ScriptWarning[] = []\n let out = value\n\n for (const [locale, raw] of Object.entries(value)) {\n if (exempt?.has(locale)) continue\n if (typeof raw !== 'string') continue\n const allowed = allowedFor(descriptor, locale)\n if (fullMatcher(allowed).test(raw)) continue\n\n const sample = offendingSample(raw, allowed)\n if (mode === 'reject') {\n throw new ScriptViolationError(field, locale, allowed, sample)\n }\n warnings.push({ field, locale, expected: allowed, sample })\n if (mode === 'filter') {\n if (out === value) out = { ...value }\n out[locale] = stripDisallowed(raw, allowed)\n }\n }\n\n return { value: out, warnings }\n}\n","/**\n * The i18n `ViaBinding` — wires the i18n engine (auto-translate/script\n * enforcement/validation/densify on write; locale + dict-label presentation\n * on read) into the kernel's generic Via port. Mirrors\n * `via/money/binding.ts`'s #553 static-link pattern.\n *\n * LIVE (#623 Task 8 wired the cutover): `i18nBinding()`/`linkI18nVia()` are\n * the real put/read path for every i18n-declaring collection —\n * `collection.ts`'s `_putInternal`/`applyLocaleToRecord` (the call sites\n * this file's bodies were moved/adapted from) now delegate their i18n\n * stages to `this.via.encodeWrite`/`this.via.present` instead of running\n * the hand-wired i18n logic inline.\n *\n * `i18nText()`, `dictKey()`, `staticDict()` each call {@link linkI18nVia}\n * first — the same #553 pattern `money()` uses.\n */\nimport type { ViaBinding, ViaWriteCtx, ViaReadCtx } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport type { I18nTextDescriptor } from './core.js'\nimport { stripI18nFilled } from './core.js'\nimport type { DictKeyDescriptor, StaticDictDescriptor } from './dictionary.js'\nimport type { I18nStrategy } from '../../port/with/i18n-strategy.js'\nimport { isStaticDictDescriptor } from '../../port/with/i18n-strategy.js'\nimport { resolvePolicy, type Layer } from './policy.js'\nimport { getAtPath, setAtPathInPlace } from '../../kernel/paths.js'\nimport { TranslatorNotConfiguredError, LocaleNotSpecifiedError } from '../../kernel/errors.js'\n\n/**\n * Config a collection's i18n declarations resolve to — the binding's\n * construction input. Fields are loosely typed (`unknown`) at this seam\n * because the kernel's `ViaBinder` contract is opaque-config-in; the\n * concrete i18n types are applied inside the binding's own functions.\n */\nexport interface I18nViaConfig {\n i18nFields?: Record<string, unknown> // I18nTextDescriptor map\n dictKeyFields?: Record<string, unknown> // DictKeyDescriptor | StaticDictDescriptor map\n i18nDensifyFields?: Record<string, unknown> // I18nTextDescriptor subset (densifyOnWrite: true)\n strategy: unknown // I18nStrategy (real or NO_I18N)\n defaultLocale?: string\n autoTranslateHook?: (...args: unknown[]) => Promise<string>\n dictLabelResolver?: (...args: unknown[]) => Promise<string | undefined>\n i18nPutValidator?: (record: unknown) => void // the vault-built closure (unchanged wiring)\n collectionName: string\n}\n\n// ─── write pipeline ─────────────────────────────────────────────────────\n\n/**\n * Auto-translate missing i18nText translations. Runs BEFORE i18n\n * validation so translated values satisfy the required-locale constraint.\n * Throws `TranslatorNotConfiguredError` when a field has\n * `autoTranslate: true` but no hook was configured. Mutates `record`\n * in place (mirrors `collection.ts:1830-1874`).\n */\nasync function runI18nAutoTranslate(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n cfg: I18nViaConfig,\n): Promise<void> {\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n if (!descriptor.options.autoTranslate) continue\n // getAtPath returns [] for array-wildcard paths — auto-translate on\n // 'contacts[].field' style paths is not supported; skip silently.\n const leafValues = getAtPath(record, field)\n if (leafValues.length !== 1) continue\n const value = leafValues[0]\n if (!value || typeof value !== 'object' || Array.isArray(value)) continue\n const map = value as Record<string, string>\n // Determine which locales need translation. For 'all', translate all\n // declared languages that are missing. For 'any', only translate if\n // none are present. For string[], translate the listed required ones.\n const { languages, required } = descriptor.options\n const missing: string[] = languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length === 0) continue\n // Find a source locale (first present non-empty value)\n const sourceLocale = languages.find((l) => l in map && map[l] !== '')\n if (!sourceLocale) continue\n if (!cfg.autoTranslateHook) {\n throw new TranslatorNotConfiguredError(field, cfg.collectionName)\n }\n // Only translate locales that are actually needed\n const toTranslate =\n required === 'any'\n ? [] // 'any' is already satisfied since sourceLocale exists\n : required === 'all'\n ? missing\n : missing.filter((l) => required.includes(l))\n const translated = { ...map }\n for (const targetLocale of toTranslate) {\n translated[targetLocale] = await cfg.autoTranslateHook(\n map[sourceLocale]!,\n sourceLocale,\n targetLocale,\n field,\n cfg.collectionName,\n )\n }\n setAtPathInPlace(record, field, translated)\n }\n}\n\n/**\n * i18nText script enforcement — runs AFTER auto-translate (so generated\n * values are checked too). Throws `ScriptViolationError` (from inside\n * `strategy.enforceScript`) under the default 'reject'; 'filter' strips\n * disallowed chars in place; 'warn' leaves the value unchanged. Mirrors\n * `collection.ts:1896-1927`.\n */\nfunction runI18nScriptEnforcement(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n strategy: I18nStrategy,\n exemptFills: Map<string, Set<string>> | undefined,\n ctx: ViaWriteCtx,\n cfg: I18nViaConfig,\n): void {\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n if (!descriptor.options.script) continue\n for (const leaf of getAtPath(record, field)) {\n if (!leaf || typeof leaf !== 'object' || Array.isArray(leaf)) continue\n const leafMap = leaf as Record<string, unknown>\n const { value: cleaned, warnings } = strategy.enforceScript(\n leafMap,\n field,\n descriptor,\n exemptFills?.get(field),\n )\n if (cleaned !== leafMap) Object.assign(leafMap, cleaned)\n // enforceScript only returns warnings under 'warn'/'filter' ('reject'\n // throws first), so this guard never fires — it makes that invariant\n // explicit and keeps `mode` off the optional-undefined type.\n const mode = descriptor.options.onScriptViolation\n if (mode === 'warn' || mode === 'filter') {\n for (const w of warnings) {\n // Exact original payload shape (collection.ts:1916-1922 pre-cutover).\n ctx.emit('i18n:script-violation', {\n vault: ctx.vault,\n collection: cfg.collectionName,\n id: ctx.id,\n mode,\n warning: w,\n })\n }\n }\n }\n }\n}\n\n/**\n * `encodeWrite` — translate → script → validate → densify, in the EXACT\n * order `_putInternal` runs them today (seam-map Part 2, stages 7-11).\n */\nasync function runI18nWriteStages(\n record: Record<string, unknown>,\n ctx: ViaWriteCtx,\n cfg: I18nViaConfig,\n): Promise<Record<string, unknown>> {\n const i18nFields = cfg.i18nFields as Record<string, I18nTextDescriptor> | undefined\n const i18nDensifyFields = cfg.i18nDensifyFields as Record<string, I18nTextDescriptor> | undefined\n const strategy = cfg.strategy as I18nStrategy\n\n // 1. Auto-translate.\n if (i18nFields) {\n await runI18nAutoTranslate(record, i18nFields, cfg)\n }\n\n // 2. densifyOnWrite: read prior fills so a round-tripped derived copy is\n // exempt from script enforcement and can be refreshed. Read once here,\n // reused by densify() below. `ctx.prior()` resolves the real prior\n // record (collection.ts wires it to `resolveDensifyPrior`, #623 Task 8).\n let densifyPrior: Record<string, unknown> | undefined\n let exemptFills: Map<string, Set<string>> | undefined\n if (i18nDensifyFields) {\n densifyPrior = (await ctx.prior()) ?? undefined\n exemptFills = strategy.computeExemptFills(densifyPrior, record, i18nDensifyFields)\n }\n\n // 3. Script enforcement.\n if (i18nFields) {\n runI18nScriptEnforcement(record, i18nFields, strategy, exemptFills, ctx, cfg)\n }\n\n // 4. i18nText validation — AFTER auto-translate + script so the record is\n // trustworthy. Throws MissingTranslationError when required translations\n // are absent. The vault-built closure (unchanged wiring).\n cfg.i18nPutValidator?.(record)\n\n // 5. Eager-fill empty slots + record provenance. Runs AFTER the authored\n // gates (required + script) so only authored slots are validated.\n if (i18nDensifyFields) {\n strategy.densify(record, densifyPrior, i18nDensifyFields)\n }\n\n return record\n}\n\n// ─── read pipeline ──────────────────────────────────────────────────────\n\n/**\n * `present` — i18nText locale resolution + dictKey/staticDict label\n * resolution + `_i18nFilled` stripping. Adapted from\n * `applyLocaleToRecord`'s i18n+dict+strip portions (`collection.ts:4184-\n * 4301`) — the money-decode portion of that method is a separate binding\n * (`via/money`) and is NOT this function's concern.\n */\nasync function runI18nPresent(\n record: Record<string, unknown>,\n ctx: ViaReadCtx,\n cfg: I18nViaConfig,\n): Promise<Record<string, unknown>> {\n const i18nFields = cfg.i18nFields as Record<string, I18nTextDescriptor> | undefined\n const dictKeyFields = cfg.dictKeyFields as Record<string, DictKeyDescriptor | StaticDictDescriptor> | undefined\n const strategy = cfg.strategy as I18nStrategy\n const hasI18n = i18nFields !== undefined && Object.keys(i18nFields).length > 0\n const hasDict = dictKeyFields !== undefined && Object.keys(dictKeyFields).length > 0\n if (!hasI18n && !hasDict) return record\n\n const locale = typeof ctx.locale === 'string' ? ctx.locale : undefined\n const fallback = ctx.fallback as string | readonly string[] | undefined\n const layer = ctx.layer as Layer\n\n let result = record\n\n // i18nText / dictKey resolution require an active locale — EXCEPT a\n // static dict declaring a `displayLocale`, which resolves its\n // `<field>Label` even under a locale-less read (the hybrid hinge). Only\n // this second gate relaxes, and ONLY for static-display fields — folding\n // `hasI18n` in here would let an i18nText-only collection fall through to\n // applyI18nLocale(…, undefined) on a locale-less read, breaking the\n // raw-{th,en}-map invariant.\n const hasStaticDisplay =\n hasDict &&\n dictKeyFields !== undefined &&\n Object.values(dictKeyFields).some(\n (d) => isStaticDictDescriptor(d) && d.displayLocale !== undefined,\n )\n\n // Strip the internal densify marker even when no locale is active\n // (applyI18nLocale, which normally strips it, is skipped on this path).\n // Non-mutating: never touches the cached/stored record object.\n if (!locale && !hasStaticDisplay) return stripI18nFilled(result)\n\n // 1. i18nText resolution — guarded on `locale`, because the relaxed gate\n // above can now be entered with `locale === undefined` (static-display).\n // The layer selects the field's per-layer `onMissing` policy inside\n // applyI18nLocale.\n if (locale && hasI18n && i18nFields) {\n result = strategy.applyI18nLocale(result, i18nFields, locale, fallback, layer)\n }\n\n // 2. dictKey / staticDict label resolution\n if (hasDict && dictKeyFields && cfg.dictLabelResolver && locale !== 'raw') {\n const withLabels = { ...result }\n const resolver = cfg.dictLabelResolver\n for (const [field, desc] of Object.entries(dictKeyFields)) {\n // dictKey default policy is 'null' (omit/null on miss) — today's\n // behavior — unless the field declares onMissing. 'substitute'\n // walks the declared substitute chain (passed as the resolver's\n // fallback); 'throw' raises LocaleNotSpecifiedError.\n const policy = desc.onMissing ? resolvePolicy(desc.onMissing, layer) : 'null'\n const fieldFallback =\n policy === 'substitute'\n ? (fallback ?? desc.substitute)\n : fallback\n // Per-field effective locale: a static dict falls back to its\n // `displayLocale` when no locale is active (the hybrid hinge); a\n // plain dictKey with no displayLocale gets `undefined` → its\n // <field>Label is omitted on a locale-less read (today's behavior).\n const effLocale =\n locale ??\n (isStaticDictDescriptor(desc) ? desc.displayLocale : undefined)\n // Resolve one key → label | null, honoring the policy. With no\n // effective locale there is nothing to resolve against.\n const resolveKey = async (key: string): Promise<string | null> => {\n if (!effLocale) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field,\n `dictKey \"${field}\": no locale active to resolve key \"${key}\".`,\n )\n }\n return null\n }\n const label = await resolver(desc.name, key, effLocale, fieldFallback)\n if (label === undefined) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field,\n `dictKey \"${field}\": no label for key \"${key}\" in locale \"${effLocale}\".`,\n )\n }\n return null\n }\n return label\n }\n\n if (field.includes('[].')) {\n // Wildcard path `arrayKey[].leaf`: add a per-element sibling\n // `<leaf>Label`. Single level + simple leaf.\n const parts = field.split('[].')\n const arrayKey = parts[0]!\n const leaf = parts[1]\n if (!leaf || leaf.includes('.')) continue\n const arr = (withLabels as Record<string, unknown>)[arrayKey]\n if (!Array.isArray(arr)) continue\n const labelKey = `${leaf}Label`\n ;(withLabels as Record<string, unknown>)[arrayKey] = await Promise.all(\n arr.map(async (el) => {\n if (!el || typeof el !== 'object' || Array.isArray(el)) return el\n const k = (el as Record<string, unknown>)[leaf]\n if (typeof k !== 'string') return el\n return { ...(el as Record<string, unknown>), [labelKey]: await resolveKey(k) }\n }),\n )\n continue\n }\n\n const val = result[field]\n if (Array.isArray(val)) {\n // Array-of-keys → [{ key, label }] pair objects (key preserved).\n withLabels[`${field}Label`] = await Promise.all(\n val.map(async (k) => ({\n key: k,\n label: typeof k === 'string' ? await resolveKey(k) : null,\n })),\n )\n } else if (typeof val === 'string') {\n const label = await resolveKey(val)\n // Scalar under 'null'/default omits the label key (today's\n // behavior); 'substitute' returns a value; 'throw' threw above.\n if (label !== null) withLabels[`${field}Label`] = label\n }\n }\n result = withLabels\n }\n\n // Final guard: the locale-less static-display path skips\n // applyI18nLocale's strip, so ensure the densify marker never leaks here\n // either. Non-mutating (no-op when absent or already stripped above).\n return stripI18nFilled(result)\n}\n\n// ─── introspection ──────────────────────────────────────────────────────\n\nfunction buildI18nDescribeFragment(cfg: I18nViaConfig): Record<string, unknown> {\n return {\n i18nFields: cfg.i18nFields ? Object.keys(cfg.i18nFields) : [],\n dictKeyFields: cfg.dictKeyFields ? Object.keys(cfg.dictKeyFields) : [],\n ...(cfg.defaultLocale !== undefined ? { defaultLocale: cfg.defaultLocale } : {}),\n }\n}\n\n// ─── binding ────────────────────────────────────────────────────────────\n\nexport function i18nBinding(cfg: I18nViaConfig): ViaBinding {\n return {\n brand: 'i18n',\n posture: { encryptedAtRest: 'envelope', queryable: 'full', exportable: true, forgettable: true },\n // DictionaryHandle's `_dict_*` reserved collections (#629 Task 4) — the\n // codec boundary's `reservedEnvelopes` door may address any collection\n // name under this prefix.\n reservedPrefixes: ['_dict_'],\n covers: (field) =>\n (cfg.i18nFields !== undefined && field in cfg.i18nFields)\n || (cfg.dictKeyFields !== undefined && field in cfg.dictKeyFields),\n encodeWrite: async (record, ctx) => runI18nWriteStages(record, ctx, cfg),\n present: async (record, ctx) => runI18nPresent(record, ctx, cfg),\n describeFragment: () => buildI18nDescribeFragment(cfg),\n }\n}\n\nexport function linkI18nVia(): void {\n installViaBinder('i18n', (c) => i18nBinding(c as I18nViaConfig))\n}\n","/**\n * i18nText schema type —\n *\n * `i18nText({ languages, required })` creates a descriptor for a\n * multi-language content field whose value is stored as a\n * `{ [locale]: string }` map (e.g. `{ en: 'Consulting', th: 'ที่ปรึกษา' }`).\n *\n * On put, the descriptor validates that required languages are present.\n * On read (when a `locale` option is passed), the map is collapsed to the\n * caller's locale string via the fallback chain.\n *\n * Design decisions\n * ────────────────\n *\n * **Descriptor pattern (not a Zod type).**\n * `i18nText()` returns a plain descriptor object used in the collection's\n * `i18nFields` option — same pattern as `ref()` / `dictKey()`. This keeps\n * `@noy-db/core` at zero runtime dependencies and avoids Zod v3 field-type\n * constraints. TypeScript inference is handled via the descriptor's type.\n *\n * **Enforcement at the collection boundary.**\n * The `required` option is checked by `Collection.put()` via the compartment's\n * registered `i18nFields`. Failed validation throws `MissingTranslationError`\n * — a distinct class from `SchemaValidationError` so callers can tell\n * \"wrong shape\" from \"missing translations\".\n *\n * **Resolution is post-decryption.**\n * Locale resolution happens AFTER `decryptRecord()`, as a pure in-memory\n * transform. No additional crypto work is needed. The resolved record is\n * returned in place of the stored one, with i18nText fields replaced by\n * their locale-resolved strings.\n *\n * **`locale: 'raw'`.**\n * Passing `{ locale: 'raw' }` skips resolution and returns the full\n * `{ [locale]: string }` map — useful for bilingual exports, admin UIs,\n * and any context where all translations must be visible at once.\n *\n * **Out of scope.**\n * Pluralization, RTL rendering, date/number formatting, per-locale CRDT\n * merging.\n */\n\nimport { MissingTranslationError, LocaleNotSpecifiedError } from '../../kernel/errors.js'\nimport type { OnMissing, OnMissingPolicy, Layer } from './policy.js'\nimport { resolvePolicy } from './policy.js'\nimport { inferScripts } from './script.js'\nimport { linkI18nVia } from './binding.js'\n\n// ─── I18nMap type helper ───────────────────────────────────────────────\n\n/** Flatten an intersection into a single object literal for nicer hovers. */\ntype Prettify<T> = { [K in keyof T]: T[K] } & {}\n\n/**\n * The stored shape of a multilingual field, inferred from its `required`\n * mode — so the compiler forces you to handle an absent optional locale\n * (`string | undefined`) instead of silently yielding `undefined`.\n *\n * Mirrors `i18nText({ languages, required })`:\n * - `'all'` (default) — every locale required: `{ th: string; en: string }`\n * - `'any'` — every locale optional: `{ th?: string; en?: string }`\n * (the \"at least one present\" guarantee is runtime-only — not expressible\n * in TypeScript — so each key is optional)\n * - `readonly L[]` — listed locales required, the rest optional:\n * `I18nMap<'th'|'en', ['th']>` → `{ th: string; en?: string }`\n *\n * @example\n * ```ts\n * type Lang = 'th' | 'en'\n * interface Contact {\n * name: I18nMap<Lang, 'any'> // { th?: string; en?: string }\n * legalName: I18nMap<Lang, ['th']> // { th: string; en?: string }\n * slug: I18nMap<Lang> // { th: string; en: string }\n * }\n * ```\n *\n * @public\n */\nexport type I18nMap<\n Langs extends string,\n Required extends 'all' | 'any' | readonly Langs[] = 'all',\n> = Required extends 'all'\n ? Record<Langs, string>\n : Required extends 'any'\n ? Partial<Record<Langs, string>>\n : Required extends readonly (infer R extends Langs)[]\n ? Prettify<Record<R, string> & Partial<Record<Exclude<Langs, R>, string>>>\n : never\n\n// ─── i18nText descriptor ───────────────────────────────────────────────\n\n/**\n * Options for `i18nText()`.\n *\n * `languages` declares the full set of supported locales. `required`\n * controls which must be present on every `put()`.\n *\n * `autoTranslate` is the per-field opt-in for the `plaintextTranslator`\n * hook. When `true` and a `plaintextTranslator` is configured\n * on `createNoydb()`, missing translations are generated before `put()`.\n * Default: `false`.\n */\nexport interface I18nTextOptions {\n /** All supported locale codes (BCP 47). */\n readonly languages: readonly string[]\n /**\n * Which locales must be present on every `put()`.\n *\n * - `'all'` — every declared language must be present.\n * - `'any'` — at least one declared language must be present.\n * - `string[]` — listed locales are required; others are optional.\n */\n readonly required: 'all' | 'any' | readonly string[]\n /**\n * Per-field opt-in for the `plaintextTranslator` hook.\n * When `true`, missing required translations are auto-generated\n * before `put()` if a translator is configured. Default: `false`.\n */\n readonly autoTranslate?: boolean\n /**\n * What to do when this field is resolved to a locale that is absent.\n * A single policy, or a per-layer map (read/guard/join/mv/derivation/\n * export). Default `'throw'` — today's behavior, zero breaking change.\n * See {@link OnMissingPolicy}.\n *\n * NOTE (current wiring): ALL layers are enforced — `read` (`get`/`list`),\n * `guard`, `derivation`, `mv`, `join`, `export`. Guard / derivation\n * `ctx.vault` reads resolve under their own layer policy (`guard` defaults to\n * the lenient `'substitute'`). The `mv` layer fires for materialized views\n * that declare `{ i18nLocale, i18nFields }` — UNION (group-key i18n fields\n * resolve before the unified-row bucketing) and query-form (resolved in\n * `GroupedReduction.run` before `groupAndReduce`); grouping a raw i18n field\n * without a locale throws. The `join` layer resolves a joined right-side i18n\n * field to the query locale (`toArray({ locale })` or the vault default; raw\n * when locale-less). The `export` layer fires for\n * `exportStream`/`exportJSON({ resolveLabels })` — records collapse to the\n * export locale.\n */\n readonly onMissing?: OnMissingPolicy\n /**\n * Ordered preferred-substitute locales used when `onMissing` resolves\n * to `'substitute'` and the target locale is absent. `'any'` as an\n * element means \"first non-empty value\". A caller-supplied `fallback`\n * at read time takes precedence over this declared list.\n */\n readonly substitute?: readonly string[]\n /**\n * Smart-substitute. When `true`, a missing-locale `substitute` walk that\n * misses the explicit chain prefers the available locale whose script is\n * nearest the target (same script, then Latin) rather than an arbitrary value\n * — e.g. a missing Thai label prefers another Thai (or Latin) translation over\n * an unreadable script. Default `false` (legacy first-non-empty behavior).\n */\n readonly smartSubstitute?: boolean\n /**\n * Per-locale script enforcement (write-time). `'auto'` infers the\n * allowed Unicode scripts per locale (asymmetric Latin tolerance); an\n * object overrides per slot. Absent ⇒ no check. See `./script.ts`.\n */\n readonly script?: 'auto' | Partial<Record<string, readonly string[]>>\n /**\n * What to do when a slot's value contains characters outside its\n * allowed script set. Default `'reject'`.\n */\n readonly onScriptViolation?: 'reject' | 'filter' | 'warn'\n /**\n * Eager-fill empty locale slots from the substitute chain at\n * write time, recording provenance in the internal `_i18nFilled` marker.\n * Mutually exclusive with an EXPLICIT `'throw'` onMissing policy (densify\n * fills every hole, so a throw would be unreachable). Without an explicit\n * `substitute`, fills from `'any'` (first non-empty). Default absent.\n */\n readonly densifyOnWrite?: boolean\n}\n\n/**\n * Descriptor returned by `i18nText()`. Attach to the collection's\n * `i18nFields` option:\n *\n * ```ts\n * const lineItems = company.collection<LineItem>('line-items', {\n * i18nFields: {\n * description: i18nText({ languages: ['en', 'th'], required: 'all' }),\n * },\n * })\n * ```\n */\nexport interface I18nTextDescriptor {\n readonly _noydbI18nText: true\n /** Via port brand marker — lets an `I18nTextDescriptor` satisfy the kernel's opaque `ViaDescriptor` (#623 Task 9). */\n readonly _viaBrand: 'i18n'\n readonly options: I18nTextOptions\n}\n\n/**\n * Create an `I18nTextDescriptor` for a multi-language content field.\n *\n * @param options Language list + enforcement mode.\n *\n * @example\n * ```ts\n * i18nText({ languages: ['en', 'th'], required: 'all' })\n * i18nText({ languages: ['en', 'th'], required: ['th'], autoTranslate: true })\n * ```\n */\nexport function i18nText(options: I18nTextOptions): I18nTextDescriptor {\n // The declaration is the Via binding's opt-in unit (#553): constructing\n // a descriptor statically links the i18n binding into the kernel's Via\n // port, so every later kernel consultation finds it already installed.\n linkI18nVia()\n if (options.densifyOnWrite === true && hasThrowPolicy(options.onMissing)) {\n throw new Error(\n `i18nText: densifyOnWrite cannot be combined with an explicit onMissing 'throw' ` +\n `policy — densify fills every empty slot, so a 'throw' would be unreachable. ` +\n `Remove the 'throw' policy or disable densifyOnWrite.`,\n )\n }\n return { _noydbI18nText: true, _viaBrand: 'i18n', options }\n}\n\n/** True when `onMissing` declares `'throw'` for any layer (scalar or per-layer). */\nfunction hasThrowPolicy(onMissing: OnMissingPolicy | undefined): boolean {\n if (onMissing === undefined) return false\n if (typeof onMissing === 'string') return onMissing === 'throw'\n return Object.values(onMissing).includes('throw')\n}\n\n// `isI18nTextDescriptor` now lives on the kernel port (#623 Task 11,\n// port/with/i18n-strategy.ts, alongside `isStaticDictDescriptor`) —\n// re-exported here for compat with existing importers of this module.\nexport { isI18nTextDescriptor } from '../../port/with/i18n-strategy.js'\n\n// ─── Validation helpers ────────────────────────────────────────────────\n\n/**\n * Validate that a value is a valid `{ [locale]: string }` map and that\n * all required locales are present. Throws `MissingTranslationError`\n * when the required constraint is violated.\n *\n * Called by `Collection.put()` for each registered `i18nField`.\n *\n * @param value The raw field value from the record being put.\n * @param field The field name (used in the thrown error message).\n * @param descriptor The `i18nText()` descriptor for this field.\n */\nexport function validateI18nTextValue(\n value: unknown,\n field: string,\n descriptor: I18nTextDescriptor,\n): void {\n const { options } = descriptor\n\n // Must be a non-null object\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" must be a { [locale]: string } map, got ${typeof value}.`,\n )\n }\n\n const map = value as Record<string, unknown>\n\n // All values must be strings\n for (const [locale, v] of Object.entries(map)) {\n if (typeof v !== 'string') {\n throw new MissingTranslationError(\n field,\n [locale],\n `Field \"${field}\": locale \"${locale}\" must be a string, got ${typeof v}.`,\n )\n }\n }\n\n // Check required constraint\n const { required } = options\n if (required === 'all') {\n const missing = options.languages.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires all declared languages. Missing: ${missing.join(', ')}.`,\n )\n }\n } else if (required === 'any') {\n const present = options.languages.some(\n (lang) => lang in map && map[lang] !== '',\n )\n if (!present) {\n throw new MissingTranslationError(\n field,\n options.languages,\n `Field \"${field}\" requires at least one declared language. None present.`,\n )\n }\n } else {\n // string[] — named required locales; TypeScript narrows required to readonly string[]\n const requiredList = required\n const missing = requiredList.filter(\n (lang) => !(lang in map) || map[lang] === '',\n )\n if (missing.length > 0) {\n throw new MissingTranslationError(\n field,\n missing,\n `Field \"${field}\" requires: ${requiredList.join(', ')}. Missing: ${missing.join(', ')}.`,\n )\n }\n }\n}\n\n// ─── Locale resolution ─────────────────────────────────────────────────\n\n/**\n * Resolve an i18nText value (`{ [locale]: string }` map) to a string\n * for the given locale.\n *\n * @param value The stored locale map.\n * @param locale The requested locale code, or `'raw'` to return the map.\n * @param fallback Single locale or ordered list; use `'any'` as the last\n * element to fall back to any available translation.\n * @param field Field name used in `LocaleNotSpecifiedError` messages.\n * @returns The resolved string, OR the original map when `locale === 'raw'`.\n */\n/** Options for the policy-aware form of {@link resolveI18nText}. */\nexport interface ResolveI18nOptions {\n /** Effective policy for the resolution layer. Default `'throw'`. */\n readonly policy?: OnMissing\n /** Declared substitute chain; applied only under policy `'substitute'`. */\n readonly substitute?: readonly string[]\n /**\n * Smart-substitute. When `true` and policy is `'substitute'`, after the\n * explicit chain misses, pick the available locale whose script is nearest the\n * target (same script first, then Latin's broad readability) instead of an\n * arbitrary value. Default `false`.\n */\n readonly smartSubstitute?: boolean\n}\n\n/** Normalize a single-or-list fallback into an array. */\nfunction toChain(fallback: string | readonly string[] | undefined): readonly string[] {\n return Array.isArray(fallback) ? fallback : fallback ? [fallback as string] : []\n}\n\n/** Walk a chain, returning the first non-empty value (or `'any'` match). */\nfunction pickFromChain(\n value: Record<string, string>,\n chain: readonly string[],\n): string | undefined {\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(value).find((v) => v !== '')\n if (any !== undefined) return any\n } else if (value[fb] !== undefined && value[fb] !== '') {\n return value[fb]\n }\n }\n return undefined\n}\n\n// Legacy 4-arg form: can only throw or return — never null. Keeps every\n// existing call site's type unchanged (default policy is 'throw').\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n): string | Record<string, string>\n// Policy-aware form: may return null under 'null'/'substitute' policies.\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback: string | readonly string[] | undefined,\n field: string | undefined,\n opts: ResolveI18nOptions,\n): string | Record<string, string> | null\nexport function resolveI18nText(\n value: Record<string, string>,\n locale: string,\n fallback?: string | readonly string[],\n field?: string,\n opts?: ResolveI18nOptions,\n): string | Record<string, string> | null {\n if (locale === 'raw') {\n return value\n }\n\n if (!locale) {\n throw new LocaleNotSpecifiedError(field ?? '<unknown>')\n }\n\n // Primary locale\n if (value[locale] !== undefined && value[locale] !== '') {\n return value[locale]\n }\n\n const policy: OnMissing = opts?.policy ?? 'throw'\n\n // Caller-supplied fallback ALWAYS applies first (backward compat +\n // explicit read-time override), regardless of policy.\n const callerChain = toChain(fallback)\n const callerHit = pickFromChain(value, callerChain)\n if (callerHit !== undefined) return callerHit\n\n // Declared substitute applies ONLY under policy 'substitute'.\n if (policy === 'substitute') {\n const subHit = pickFromChain(value, toChain(opts?.substitute))\n if (subHit !== undefined) return subHit\n // Smart-substitute: after the explicit chain, prefer the script-nearest\n // available locale over an arbitrary first-non-empty value.\n if (opts?.smartSubstitute) {\n const smartHit = pickNearestScript(value, locale)\n if (smartHit !== undefined) return smartHit\n }\n }\n\n // Exhausted.\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(\n field ?? '<unknown>',\n `No translation available for locale \"${locale}\"` +\n (callerChain.length > 0 ? ` or fallback chain [${callerChain.join(', ')}]` : '') +\n '.',\n )\n }\n return null\n}\n\n/**\n * Smart-substitute: among the non-empty locales in `value`, pick the one\n * whose primary script is nearest the target `locale` — same script first, then\n * Latin (broadly readable), then any other — so a missing Thai label falls back\n * to another Thai (or Latin) value rather than, say, an Arabic one. First-seen\n * wins on ties. Returns the value string, or `undefined` when `value` has no\n * non-empty entry.\n */\nfunction pickNearestScript(value: Record<string, string>, target: string): string | undefined {\n const targetScript = inferScripts(target)[0] ?? 'Latin'\n let best: { score: number; v: string } | undefined\n for (const [loc, v] of Object.entries(value)) {\n if (typeof v !== 'string' || v === '') continue\n const s = inferScripts(loc)[0] ?? 'Latin'\n const score = s === targetScript ? 0 : s === 'Latin' ? 1 : 2\n if (best === undefined || score < best.score) best = { score, v }\n if (score === 0) break // nothing beats a same-script match\n }\n return best?.v\n}\n\n// ─── Path helpers (nested i18nFields like 'address.lineOne') ──────────\n\n// `getAtPath`/`setAtPathInPlace` are generic dotted-path/[]-wildcard record\n// helpers, not i18n logic — moved to `kernel/paths.ts` (Task 7, #623).\n// `getAtPath` re-exported here for compat with existing importers of this\n// module (embeddings/descriptor.ts, search/build-docs.ts); `setAtPathInPlace`\n// is not re-exported — its only consumer (via-i18n/binding.ts) imports it\n// directly from kernel/paths.ts.\nexport { getAtPath } from '../../kernel/paths.js'\n\n/** Recursively resolve i18nText at a single path within a record copy. */\nfunction applyAtPath(\n obj: Record<string, unknown>,\n path: string,\n locale: string,\n fallback: string | readonly string[] | undefined,\n opts: ResolveI18nOptions,\n): Record<string, unknown> {\n const arrayIdx = path.indexOf('[].')\n if (arrayIdx !== -1) {\n const arrayKey = path.slice(0, arrayIdx)\n const restPath = path.slice(arrayIdx + 3)\n const arr = obj[arrayKey]\n if (!Array.isArray(arr)) return obj\n return {\n ...obj,\n [arrayKey]: arr.map(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return item\n return applyAtPath(item as Record<string, unknown>, restPath, locale, fallback, opts)\n }),\n }\n }\n const dotIdx = path.indexOf('.')\n if (dotIdx !== -1) {\n const head = path.slice(0, dotIdx)\n const rest = path.slice(dotIdx + 1)\n const nested = obj[head]\n if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return obj\n return {\n ...obj,\n [head]: applyAtPath(nested as Record<string, unknown>, rest, locale, fallback, opts),\n }\n }\n const raw = obj[path]\n if (raw === undefined || raw === null) return obj\n if (typeof raw !== 'object' || Array.isArray(raw)) return obj\n return {\n ...obj,\n [path]: resolveI18nText(raw as Record<string, string>, locale, fallback, path, opts),\n }\n}\n\n/**\n * Apply locale resolution to a single record, returning a new copy.\n *\n * For each field registered as an `i18nText` descriptor:\n * - If `locale === 'raw'`, the field value is left as the stored map.\n * - Otherwise, the field value is replaced with the resolved string.\n *\n * Field paths support dot notation (`'address.lineOne'`) and array\n * wildcards (`'contacts[].title'`). Top-level fields work as before.\n *\n * @param record The decrypted record.\n * @param i18nFields Map of field path → `I18nTextDescriptor`.\n * @param locale The requested locale (or `'raw'`).\n * @param fallback Fallback chain (optional).\n * @param layer Resolution layer (default `'read'`). Each field's\n * `onMissing` policy is resolved for this layer, so the\n * same record resolves leniently on a get but strictly\n * inside an mv/derivation.\n */\nexport function applyI18nLocale(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n fallback?: string | readonly string[],\n layer: Layer = 'read',\n): Record<string, unknown> {\n const fieldNames = Object.keys(i18nFields)\n if (fieldNames.length === 0) return record\n\n let result = record\n\n for (const [field, descriptor] of Object.entries(i18nFields)) {\n const { onMissing, substitute, smartSubstitute } = descriptor.options\n const opts: ResolveI18nOptions = {\n policy: resolvePolicy(onMissing, layer),\n ...(substitute !== undefined ? { substitute } : {}),\n ...(smartSubstitute ? { smartSubstitute } : {}),\n }\n result = applyAtPath(result, field, locale, fallback, opts)\n }\n\n // The internal densify provenance marker never leaves the store.\n result = stripI18nFilled(result)\n\n return result\n}\n\n/**\n * Sync i18n-text-only present-for-join dressing — the exact `join`-layer\n * partial application `kernel/query/join.ts` used to import and call\n * directly before #626's retirement (#650 Task 6): fixes `fallback`\n * `undefined` and `layer` `'join'`. `via/lookup/snapshot.ts`'s\n * `buildPresentForJoin` composes this with the lookup-label half to build\n * the `JoinableSource.presentForJoin` hook the join executor now calls\n * instead of reaching into this module.\n */\nexport function presentI18nForJoin(\n record: Record<string, unknown>,\n i18nFields: Record<string, I18nTextDescriptor>,\n locale: string,\n): Record<string, unknown> {\n return applyI18nLocale(record, i18nFields, locale, undefined, 'join')\n}\n\n/**\n * Remove the internal densify provenance marker (`_i18nFilled`) from a\n * read-facing record. NON-mutating: returns the same object when the\n * marker is absent, otherwise a shallow copy without the marker.\n *\n * MUST be applied on every user-facing read return — even locale-less ones,\n * which bypass {@link applyI18nLocale}. MUST NOT be applied on the internal\n * prior-read path (decryptRecord / resolveDensifyPrior), where densify needs\n * the marker.\n */\nexport function stripI18nFilled<T extends Record<string, unknown>>(record: T): T {\n if (!Object.prototype.hasOwnProperty.call(record, '_i18nFilled')) return record\n const rest: T = { ...record }\n delete (rest as Record<string, unknown>)._i18nFilled\n return rest\n}\n"],"mappings":";;;;;;;;;;;AAyKA,SAAS,WAAW,IAAmB;AACrC,SAAO,IAAI;AAAA,IACT,GAAG,EAAE;AAAA,EAGP;AACF;AAQO,IAAM,UAAwB;AAAA,EACnC,gBAAgB,QAAQ;AAAE,WAAO;AAAA,EAAO;AAAA,EACxC,wBAAwB;AAAE,UAAM,WAAW,2BAA2B;AAAA,EAAE;AAAA,EACxE,cAAc,OAAO;AAAE,WAAO,EAAE,OAAO,UAAU,CAAC,EAAE;AAAA,EAAE;AAAA,EACtD,qBAAqB;AAAE,WAAO,oBAAI,IAAyB;AAAA,EAAE;AAAA,EAC7D,UAAU;AAAA,EAAC;AAAA,EACX,wBAAwB;AAAE,UAAM,WAAW,oBAAoB;AAAA,EAAE;AACnE;AAUO,SAAS,qBAAqB,MAAuB;AAC1D,SAAO,KAAK,WAAW,QAAQ;AACjC;AAGO,SAAS,uBAAuB,GAAuC;AAC5E,SACE,OAAO,MAAM,YACb,MAAM,QACL,EAAqC,qBAAqB;AAE/D;AASO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AAG,QAAO;AACzE,QAAM,OAAU,EAAE,GAAG,OAAO;AAC5B,SAAQ,KAAiC;AACzC,SAAO;AACT;","names":[]}
@@ -1,45 +0,0 @@
1
- import {
2
- NOYDB_FORMAT_VERSION
3
- } from "./chunk-YPYHVOXP.js";
4
-
5
- // src/kernel/enclave/record-keys/tombstone.ts
6
- function isTombstoneShape(envelope) {
7
- return envelope._data === "" && envelope._cek === void 0 && envelope._del !== true;
8
- }
9
- function isTombstone(envelope, encrypted) {
10
- if (!encrypted) return false;
11
- return isTombstoneShape(envelope);
12
- }
13
- function buildTombstone(version, actor) {
14
- return {
15
- _noydb: NOYDB_FORMAT_VERSION,
16
- _v: version,
17
- _ts: (/* @__PURE__ */ new Date()).toISOString(),
18
- _iv: "",
19
- _data: "",
20
- ...actor ? { _by: actor } : {}
21
- };
22
- }
23
- function isDeleteMarker(envelope) {
24
- return envelope._del === true;
25
- }
26
- function buildDeleteMarker(version, actor) {
27
- return {
28
- _noydb: NOYDB_FORMAT_VERSION,
29
- _v: version,
30
- _ts: (/* @__PURE__ */ new Date()).toISOString(),
31
- _iv: "",
32
- _data: "",
33
- _del: true,
34
- ...actor ? { _by: actor } : {}
35
- };
36
- }
37
-
38
- export {
39
- isTombstoneShape,
40
- isTombstone,
41
- buildTombstone,
42
- isDeleteMarker,
43
- buildDeleteMarker
44
- };
45
- //# sourceMappingURL=chunk-7H73RIE3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kernel/enclave/record-keys/tombstone.ts"],"sourcesContent":["/**\n * Tombstone shape + predicate for the per-record-key (CEK) layer.\n *\n * A *tombstone* is the residue a GDPR crypto-shred (`vault.forget()`)\n * leaves on disk: the live envelope rewritten to `{ _noydb, _v, _ts, _by,\n * _iv:'', _data:'' }`, dropping `_iv`/`_data`/`_cek`/`_det`. With the wrapped\n * per-record CEK gone, the body — and every history version under the same\n * CEK — is permanently undecryptable, while the record KEY survives so the\n * version counter and \"record existed and was erased\" persist for the audit\n * ledger.\n *\n * These two helpers are the pure, collection-independent core of that\n * contract: {@link buildTombstone} mints the shape, {@link isTombstone}\n * recognises it on the read path. The orchestration that *writes* a tombstone\n * (`_writeTombstone`) and drives `vault.forget()` lives with the collection /\n * vault; it calls into these.\n */\nimport { NOYDB_FORMAT_VERSION, type EncryptedEnvelope } from '../../types.js'\n\n/**\n * Shape-only tombstone recognition for layers that have no per-collection\n * context (the sync engine, #590): a tombstone carries an empty `_data` and\n * no wrapped CEK. No live envelope can match — record bodies never serialize\n * to the empty string (the `_sync` meta envelope carries non-empty `_data`,\n * and legacy migration envelopes carry non-empty `_iv`/`_data`).\n */\nexport function isTombstoneShape(envelope: EncryptedEnvelope): boolean {\n return envelope._data === '' && envelope._cek === undefined && envelope._del !== true\n}\n\n/**\n * Is this envelope a crypto-shred tombstone?\n *\n * A tombstone carries no body (`_data` empty) and no wrapped CEK (`_cek`\n * absent) — decrypting it would call `decrypt('', '', dek)` → an AES-GCM\n * throw, so every read choke point must short-circuit to `null` instead.\n *\n * `encrypted` is the collection's encryption flag: on an unencrypted\n * collection there are no envelopes to shred, so nothing is ever a tombstone.\n * (Legacy migration envelopes carry non-empty `_iv`/`_data`, so they are not\n * tombstones and stay readable.)\n */\nexport function isTombstone(envelope: EncryptedEnvelope, encrypted: boolean): boolean {\n if (!encrypted) return false\n return isTombstoneShape(envelope)\n}\n\n/**\n * Mint a tombstone envelope from a record's live version + actor.\n *\n * Keeps `_v` (the displaced version) so the counter is monotonic across the\n * shred, stamps a fresh `_ts`, and records `_by` when an actor is supplied.\n * Deliberately omits `_iv`/`_data`/`_cek`/`_det` — that omission *is* the\n * erasure.\n */\nexport function buildTombstone(version: number, actor: string): EncryptedEnvelope {\n return {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: version,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: '',\n ...(actor ? { _by: actor } : {}),\n }\n}\n\n/** #589: is this envelope an ordinary-delete marker (version-ordered, reads as absent)? */\nexport function isDeleteMarker(envelope: EncryptedEnvelope): boolean {\n return envelope._del === true\n}\n\n/**\n * Mint a delete marker from the deleted record's next version + actor (#589).\n * Minted at the NEXT version (`existing._v + 1`) — unlike `buildTombstone`, which\n * keeps the displaced `_v` — so it wins convergence over the pre-delete copy and a\n * re-create can still win over it at a higher version.\n */\nexport function buildDeleteMarker(version: number, actor: string): EncryptedEnvelope {\n return {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: version,\n _ts: new Date().toISOString(),\n _iv: '',\n _data: '',\n _del: true,\n ...(actor ? { _by: actor } : {}),\n }\n}\n"],"mappings":";;;;;AA0BO,SAAS,iBAAiB,UAAsC;AACrE,SAAO,SAAS,UAAU,MAAM,SAAS,SAAS,UAAa,SAAS,SAAS;AACnF;AAcO,SAAS,YAAY,UAA6B,WAA6B;AACpF,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,iBAAiB,QAAQ;AAClC;AAUO,SAAS,eAAe,SAAiB,OAAkC;AAChF,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,MAAK,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC5B,KAAK;AAAA,IACL,OAAO;AAAA,IACP,GAAI,QAAQ,EAAE,KAAK,MAAM,IAAI,CAAC;AAAA,EAChC;AACF;AAGO,SAAS,eAAe,UAAsC;AACnE,SAAO,SAAS,SAAS;AAC3B;AAQO,SAAS,kBAAkB,SAAiB,OAAkC;AACnF,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,MAAK,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC5B,KAAK;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN,GAAI,QAAQ,EAAE,KAAK,MAAM,IAAI,CAAC;AAAA,EAChC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-commit/sequence/active.ts","../src/with-commit/sequence/strategy.ts","../src/with-commit/sequence/index.ts"],"sourcesContent":["/**\n * Enable the atomic-sequence capability.\n * Pass to `createNoydb({ sequenceStrategy: withSequence() })` to make\n * `vault.sequence('name').next()` / `.peek()` / `.seedTo()` live. The\n * {@link SequenceStore} CAS engine is statically imported here, so it is pulled\n * into the bundle only when `withSequence()` is referenced (the floor never\n * imports it).\n */\nimport type { SequenceStrategy } from './strategy.js'\nimport { SequenceStore } from './index.js'\n\nexport function withSequence(): SequenceStrategy {\n return {\n createStore(opts) {\n return new SequenceStore(opts)\n },\n }\n}\n","/**\n * Sequence capability strategy — the single on-demand factory the vault routes\n * `vault.sequence()` through to build its atomic-CAS {@link SequenceStore}. The\n * active engine ({@link withSequence}) constructs the real store (kept out of\n * the floor bundle — the store class is reached only via the opt-in\n * `active.ts` chunk); {@link NO_SEQUENCE} throws. The vault always assembles the\n * per-call {@link SequenceStoreOptions} and delegates here, so an un-opted-in\n * caller hits `NO_SEQUENCE`'s throw at `vault.sequence()`.\n *\n * Note: `vault.sequence()` is synchronous, so the factory is a plain (sync)\n * constructor — the engine is tree-shaken by reachability (only `withSequence()`\n * pulls `active.ts`, which statically imports the store), not by a dynamic\n * import. Deferred-numbering series (`withDeferredNumbering`) are a distinct\n * capability and are NOT routed through this strategy.\n * @internal\n */\nimport type { SequenceStore, SequenceStoreOptions } from './index.js'\nimport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport interface SequenceStrategy {\n createStore(opts: SequenceStoreOptions): SequenceStore\n}\n\n/**\n * No-op stub — the floor default. The capability factory throws\n * {@link SequenceNotEnabledError}; opt in with `sequenceStrategy: withSequence()`\n * in createNoydb. @internal\n */\nexport const NO_SEQUENCE: SequenceStrategy = {\n createStore(): SequenceStore {\n throw new SequenceNotEnabledError()\n },\n}\n","/**\n * Atomic sequence primitive — online-coordinated gap-free numbering.\n *\n * `vault.sequence('invoice-2026').next()` returns 1, 2, 3, … with no\n * gaps and no duplicates, even under concurrent callers. Each named\n * sequence is an independent counter record at `_sequences/<name>`,\n * incremented with an optimistic compare-and-swap retry loop — the same\n * proven pattern as the ledger head (`history/ledger/store.ts`).\n *\n * **Explicitly online-only.** Gap-free numbering requires single-authority\n * serialization, which an offline / non-CAS store cannot provide. `next()`\n * throws {@link SequenceOfflineError} unless the backing store advertises\n * `capabilities.casAtomic`. This is a deliberate, honest wall — an offline\n * writer cannot safely allocate a global sequence number.\n *\n * Note on \"gap-free\": the *sequence* is gap-free (each `next()` yields a\n * unique, +1 value). If a caller discards a value without using it, that\n * is a gap in *usage*, not in the sequence — assign each `next()` result\n * to its record in the same operation.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport type { ConflictError} from '../../kernel/errors.js';\nimport { isConflictError, SequenceContentionError, SequenceOfflineError, ValidationError } from '../../kernel/errors.js'\n\n// Capability opt-in seam (S4): `vault.sequence()` builds its CAS store through\n// the sequenceStrategy, so it throws SequenceNotEnabledError unless opted in.\nexport { withSequence } from './active.js'\nexport { NO_SEQUENCE, type SequenceStrategy } from './strategy.js'\nexport { SequenceNotEnabledError } from '../../kernel/errors.js'\n\nexport const SEQUENCE_COLLECTION = '_sequences'\n// A sequence is a single hot CAS row — higher contention than a ledger\n// append. A larger budget + jittered backoff absorbs moderate concurrency;\n// a genuine burst beyond this surfaces SequenceContentionError so the\n// caller can retry / queue (the honest online-only contract).\nconst MAX_NEXT_ATTEMPTS = 16\n\ninterface SequenceState {\n value: number\n}\n\n/** Options for `SequenceHandle.next`. Deferred-numbering series use `for`; the CAS counter ignores all of these. */\nexport interface NextOptions {\n /** Deferred mode: the record id to number. Ignored by the CAS counter. */\n readonly for?: string\n /** Deferred mode: reject after this many ms if still unsealed (reserved; not yet enforced in this slice). */\n readonly timeoutMs?: number\n}\n\n/**\n * Partitioning for a CAS sequence. A partitioned sequence is an\n * independent counter scoped to one tuple of values — e.g.\n * `sequence('invoice', { partition: [2026, 'EU'] })` numbers EU-2026 invoices\n * separately from `[2026, 'US']` and from the bare `invoice` series.\n *\n * Partition components are URI-encoded (so `/`, null bytes and other\n * separators in a value can never collide with the structural separators) and\n * `'/'`-joined, then appended to the series with a null-byte (`\\x00`)\n * separator. The null byte is illegal in a plain series name, which guarantees\n * a partitioned key is always disjoint from any unpartitioned series.\n */\nexport interface SequenceOptions {\n /** Partition tuple. Each component is URI-encoded and `'/'`-joined. */\n readonly partition?: readonly (string | number)[]\n /**\n * Render template for the serial string. When set, `vault.sequence`\n * returns a {@link FormattedSequenceHandle} whose `next()` resolves to\n * `{ serial, formatted }`. Tokens:\n * - `{seq}` — the allocated integer\n * - `{seq:0N}` — zero-padded to width N (e.g. `{seq:04}` → `0001`)\n * - `{partition.i}` — the i-th `partition` component (original value)\n *\n * Any other token, or a `{partition.i}` index beyond the supplied\n * `partition`, throws `ValidationError` at `vault.sequence()` construction.\n * Per-partition reset is inherent: a new partition tuple starts at 1.\n */\n readonly format?: string\n}\n\n/**\n * A formatted sequence handle. Identical to {@link SequenceHandle}\n * except `next()` also returns the rendered `formatted` string. `peek()` /\n * `seedTo()` operate on the underlying integer counter, unchanged.\n */\nexport interface FormattedSequenceHandle {\n /** Allocate the next value and return it with its rendered serial string. */\n next(opts?: NextOptions): Promise<{ serial: number; formatted: string }>\n /** Read the current integer value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /** Set-if-greater on the underlying integer counter. See {@link SequenceHandle.seedTo}. */\n seedTo(n: number): Promise<void>\n}\n\n// Matches a single `{...}` token with no nested braces.\nconst SEQ_FORMAT_TOKEN = /\\{([^{}]*)\\}/g\nconst SEQ_PAD_TOKEN = /^seq:0(\\d+)$/\nconst SEQ_PARTITION_TOKEN = /^partition\\.(\\d+)$/\n\n/**\n * Validate a sequence `format` against the supplied partition and return a\n * pure `(serial) => string` renderer. Eager validation: every token is\n * checked now, so a bad pattern throws `ValidationError` at construction —\n * never at `next()` time.\n */\nexport function compileSequenceFormat(\n format: string,\n series: string,\n partition: readonly (string | number)[] | undefined,\n): (serial: number) => string {\n const parts = partition ?? []\n for (const m of format.matchAll(SEQ_FORMAT_TOKEN)) {\n const token = m[1] ?? ''\n if (token === 'seq') continue\n if (SEQ_PAD_TOKEN.test(token)) continue\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) {\n const idx = Number(partMatch[1])\n if (idx >= parts.length) {\n throw new ValidationError(\n `sequence(\"${series}\"): format token \"{${token}}\" references partition index ${idx}, ` +\n `but only ${parts.length} partition component(s) were supplied.`,\n )\n }\n continue\n }\n throw new ValidationError(\n `sequence(\"${series}\"): format contains unknown token \"{${token}}\". ` +\n `Accepted tokens: {seq}, {seq:0N}, {partition.i}.`,\n )\n }\n return (serial: number): string =>\n format.replace(SEQ_FORMAT_TOKEN, (full, token: string) => {\n if (token === 'seq') return String(serial)\n const padMatch = SEQ_PAD_TOKEN.exec(token)\n if (padMatch) return String(serial).padStart(Number(padMatch[1]), '0')\n const partMatch = SEQ_PARTITION_TOKEN.exec(token)\n if (partMatch) return String(parts[Number(partMatch[1])])\n return full // unreachable — validated above\n })\n}\n\n/**\n * Resolve the CAS storage key for a (series, partition) pair.\n *\n * With no partition the key is `series` verbatim. With a partition the key is\n * `${series}\\x00${parts}` where `parts` is each component passed through\n * `encodeURIComponent(String(part))` and `'/'`-joined. The null-byte separator\n * is illegal in a plain series name, so partitioned keys never collide with\n * unpartitioned ones; URI-encoding keeps any component containing `/` distinct\n * from a multi-component partition.\n *\n * @throws {ValidationError} if any partition component is empty after `String()`\n * or is a non-finite number (`NaN`, `±Infinity`).\n */\nexport function resolveSequenceKey(series: string, opts?: SequenceOptions): string {\n const partition = opts?.partition\n if (!partition || partition.length === 0) return series\n const parts = partition.map((p) => {\n if (typeof p === 'number' && !Number.isFinite(p)) {\n throw new ValidationError(`sequence partition component must be a finite number, got ${p}`)\n }\n const s = String(p)\n if (s === '') {\n throw new ValidationError('sequence partition component must not be empty')\n }\n return encodeURIComponent(s)\n })\n return `${series}\\x00${parts.join('/')}`\n}\n\nexport interface SequenceHandle {\n /** Atomically allocate and return the next value (1, 2, 3, …). Deferred series resolve at the next pass. */\n next(opts?: NextOptions): Promise<number>\n /** Read the current value without allocating. Returns 0 if never used. */\n peek(): Promise<number>\n /**\n * Set-if-greater: advance the counter to at least `n`. A no-op if the\n * current value is already `>= n` (so it never rewinds), and `seedTo(0)` is\n * a no-op. Idempotent and CAS-safe under concurrent `next()` / `seedTo()`.\n *\n * Use after a bundle / CSV import to fast-forward the counter past the\n * highest imported serial, so subsequent `next()` calls cannot re-use a\n * number that is already on a record.\n *\n * Online-only: throws {@link SequenceOfflineError} on a non-CAS store.\n */\n seedTo(n: number): Promise<void>\n}\n\nasync function sleepBackoff(attempt: number): Promise<void> {\n // Exponential backoff with full jitter to break the thundering herd\n // when many writers contend on the same counter row.\n const ceil = Math.min(2 ** attempt, 32)\n const ms = Math.floor(Math.random() * ceil)\n await new Promise((r) => setTimeout(r, ms))\n}\n\n/** Per-call context the vault assembles to build a {@link SequenceStore}. */\nexport interface SequenceStoreOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\nexport class SequenceStore {\n private readonly adapter: NoydbStore\n private readonly vault: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly actor: string\n /**\n * Memoized DEK promise. The `_sequences` collection DEK is created on\n * first access; without sharing one promise, a burst of concurrent\n * `next()` calls would each trigger DEK creation and diverge (one\n * writer's ciphertext unreadable by another). One shared promise → one\n * DEK.\n */\n private dekPromise: Promise<EnclaveKey> | null = null\n\n constructor(opts: SequenceStoreOptions) {\n this.adapter = opts.adapter\n this.vault = opts.vault\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.actor = opts.actor\n }\n\n /** A handle bound to one sequence name. */\n handle(name: string): SequenceHandle {\n return {\n next: () => this.next(name),\n peek: () => this.peek(name),\n seedTo: (n) => this.seedTo(name, n),\n }\n }\n\n private assertOnline(): void {\n if (this.adapter.capabilities?.casAtomic !== true) {\n throw new SequenceOfflineError()\n }\n }\n\n private dek(): Promise<EnclaveKey> {\n if (!this.dekPromise) this.dekPromise = this.getDEK(SEQUENCE_COLLECTION)\n return this.dekPromise\n }\n\n private async read(name: string): Promise<{ env: EncryptedEnvelope | null; value: number }> {\n const env = await this.adapter.get(this.vault, SEQUENCE_COLLECTION, name)\n if (!env) return { env: null, value: 0 }\n const json = this.encrypted ? await openEnvelopeJson(env, await this.dek()) : env._data\n const state = JSON.parse(json) as SequenceState\n return { env, value: state.value }\n }\n\n private async encryptState(state: SequenceState, version: number): Promise<EncryptedEnvelope> {\n const json = JSON.stringify(state)\n if (!this.encrypted) {\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: '', _data: json, _by: this.actor }\n }\n const { iv, data } = await encrypt(json, await this.dek())\n return { _noydb: NOYDB_FORMAT_VERSION, _v: version, _ts: new Date().toISOString(), _iv: iv, _data: data, _by: this.actor }\n }\n\n async peek(name: string): Promise<number> {\n return (await this.read(name)).value\n }\n\n async next(name: string): Promise<number> {\n this.assertOnline()\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n const nextValue = value + 1\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: nextValue }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return nextValue\n } catch (err) {\n if (isConflictError(err)) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n\n async seedTo(name: string, n: number): Promise<void> {\n this.assertOnline()\n if (n <= 0) return // set-if-greater: 0 (and any non-positive seed) is a no-op\n let lastConflict: ConflictError | undefined\n for (let attempt = 0; attempt < MAX_NEXT_ATTEMPTS; attempt++) {\n const { env, value } = await this.read(name)\n if (value >= n) return // already at or past the floor — no write, idempotent\n const expectedVersion = env?._v ?? 0 // 0 ≡ \"must not yet exist\" (create)\n const envelope = await this.encryptState({ value: n }, expectedVersion + 1)\n try {\n await this.adapter.put(this.vault, SEQUENCE_COLLECTION, name, envelope, expectedVersion)\n return\n } catch (err) {\n if (isConflictError(err)) {\n lastConflict = err\n if (attempt < MAX_NEXT_ATTEMPTS - 1) await sleepBackoff(attempt)\n continue\n }\n throw err\n }\n }\n void lastConflict\n throw new SequenceContentionError(name, MAX_NEXT_ATTEMPTS)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWO,SAAS,eAAiC;AAC/C,SAAO;AAAA,IACL,YAAY,MAAM;AAChB,aAAO,IAAI,cAAc,IAAI;AAAA,IAC/B;AAAA,EACF;AACF;;;ACWO,IAAM,cAAgC;AAAA,EAC3C,cAA6B;AAC3B,UAAM,IAAI,wBAAwB;AAAA,EACpC;AACF;;;ACCO,IAAM,sBAAsB;AAKnC,IAAM,oBAAoB;AA2D1B,IAAM,mBAAmB;AACzB,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAQrB,SAAS,sBACd,QACA,QACA,WAC4B;AAC5B,QAAM,QAAQ,aAAa,CAAC;AAC5B,aAAW,KAAK,OAAO,SAAS,gBAAgB,GAAG;AACjD,UAAM,QAAQ,EAAE,CAAC,KAAK;AACtB,QAAI,UAAU,MAAO;AACrB,QAAI,cAAc,KAAK,KAAK,EAAG;AAC/B,UAAM,YAAY,oBAAoB,KAAK,KAAK;AAChD,QAAI,WAAW;AACb,YAAM,MAAM,OAAO,UAAU,CAAC,CAAC;AAC/B,UAAI,OAAO,MAAM,QAAQ;AACvB,cAAM,IAAI;AAAA,UACR,aAAa,MAAM,sBAAsB,KAAK,iCAAiC,GAAG,cACpE,MAAM,MAAM;AAAA,QAC5B;AAAA,MACF;AACA;AAAA,IACF;A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,CAAC;AAC1E,UAAI;AACF,cAAM,KAAK,QAAQ,IAAI,KAAK,OAAO,qBAAqB,MAAM,UAAU,eAAe;AACvF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,gBAAgB,GAAG,GAAG;AACxB,yBAAe;AACf,cAAI,UAAU,oBAAoB,EAAG,OAAM,aAAa,OAAO;AAC/D;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AACA,SAAK;AACL,UAAM,IAAI,wBAAwB,MAAM,iBAAiB;AAAA,EAC3D;AACF;","names":[]}
@@ -1,47 +0,0 @@
1
- // src/with-commit/history/strategy.ts
2
- function notEnabled(op) {
3
- return new Error(
4
- `${op} requires the history strategy. Import \`{ withHistory }\` from "@noy-db/hub/history" and pass it to \`createNoydb({ historyStrategy: withHistory() })\`.`
5
- );
6
- }
7
- var NO_HISTORY = {
8
- async saveHistory() {
9
- },
10
- async getHistoryEntries() {
11
- throw notEnabled("collection.history()");
12
- },
13
- async getVersionEnvelope() {
14
- throw notEnabled("collection.getVersion()");
15
- },
16
- async pruneHistory() {
17
- return 0;
18
- },
19
- async clearHistory() {
20
- return 0;
21
- },
22
- async tombstoneHistory() {
23
- return 0;
24
- },
25
- async rewrapHistory() {
26
- },
27
- async envelopePayloadHash() {
28
- return "";
29
- },
30
- computePatch() {
31
- return [];
32
- },
33
- diff() {
34
- throw notEnabled("collection.diff()");
35
- },
36
- buildLedger() {
37
- return null;
38
- },
39
- buildVaultInstant() {
40
- throw notEnabled("vault.at() / vault.timeMachine()");
41
- }
42
- };
43
-
44
- export {
45
- NO_HISTORY
46
- };
47
- //# sourceMappingURL=chunk-AFHQATY4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-commit/history/strategy.ts"],"sourcesContent":["/**\n * Strategy seam for the optional history + ledger + time-machine\n * service. Core imports `HistoryStrategy` type-only + `NO_HISTORY`\n * stub; real implementations of `saveHistory`, `LedgerStore`,\n * `VaultInstant`, `computePatch`, `diff` etc. are only reachable via\n * `withHistory()` in `./active.ts`.\n *\n * Applications that don't track per-record versioning, don't need the\n * hash-chained audit ledger, and don't restore to past instants ship\n * none of the ~1,880 LOC behind this seam.\n *\n * Strategy contract:\n *\n * - **saveHistory / pruneHistory / clearHistory** — no-ops under\n * NO_HISTORY. Writes still succeed; no snapshot is captured.\n * - **getHistoryEntries / getVersionEnvelope / diff** — throw under\n * NO_HISTORY. These are read APIs the consumer would only call\n * after explicitly asking for history; the throw guides them to\n * `@noy-db/hub/history`.\n * - **envelopePayloadHash / computePatch** — return empty / `[]`\n * under NO_HISTORY. These are only used inside the\n * `if (this.ledger)` branch, which is itself gated by\n * `buildLedger()` returning null.\n * - **buildLedger** — returns `null` under NO_HISTORY. The Vault's\n * public `vault.ledger()` accessor throws when null.\n * - **buildVaultInstant** — throws under NO_HISTORY. `vault.at()`\n * propagates the throw.\n *\n * @internal\n */\n\nimport type {\n EncryptedEnvelope,\n NoydbStore,\n HistoryOptions,\n PruneOptions,\n} from '../../kernel/types.js'\nimport type { LedgerStore } from './ledger/store.js'\nimport type { JsonPatch } from './ledger/patch.js'\nimport type { DiffEntry } from './diff.js'\nimport type { VaultInstant, VaultEngine } from './time-machine.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\n\n/**\n * Options accepted by `HistoryStrategy.buildLedger`. Mirrors the\n * `LedgerStore` constructor verbatim — kept in this file so `core`\n * code never imports the LedgerStore module at runtime.\n *\n * @internal\n */\nexport interface BuildLedgerOptions {\n adapter: NoydbStore\n vault: string\n encrypted: boolean\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n actor: string\n}\n\n/**\n * @internal\n */\nexport interface HistoryStrategy {\n /**\n * Persist a full encrypted envelope snapshot of the prior version\n * under `_history/{collection}:{id}:{paddedVersion}`. No-op under\n * `NO_HISTORY`.\n */\n saveHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n envelope: EncryptedEnvelope,\n ): Promise<void>\n\n /**\n * List history envelopes for a record, newest first. Throws under\n * `NO_HISTORY` — callers reach this via `collection.history()` /\n * `collection.getVersion()` / `collection.diff()`, which only work\n * with the strategy enabled.\n */\n getHistoryEntries(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n options?: HistoryOptions,\n ): Promise<EncryptedEnvelope[]>\n\n /**\n * Fetch a specific version's envelope. Throws under `NO_HISTORY`.\n */\n getVersionEnvelope(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n version: number,\n ): Promise<EncryptedEnvelope | null>\n\n /**\n * Prune history entries by retention rule. Returns `0` under\n * `NO_HISTORY`.\n */\n pruneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string | undefined,\n options: PruneOptions,\n ): Promise<number>\n\n /**\n * Clear all history for vault/collection/record. Returns `0` under\n * `NO_HISTORY`.\n */\n clearHistory(\n adapter: NoydbStore,\n vault: string,\n collection?: string,\n recordId?: string,\n ): Promise<number>\n\n /**\n * Crypto-shred (overwrite-to-tombstone) every `_history` version of a\n * record for GDPR erasure. Returns the number of versions newly\n * tombstoned, or `0` under `NO_HISTORY` (no history = nothing to shred).\n */\n tombstoneHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n actor: string,\n encrypted: boolean,\n ): Promise<number>\n\n /**\n * Re-key every `_history` snapshot of a record from `fromDek` to `toDek`\n * on a tier move (elevate/demote/putAtTier), mirroring the live-body\n * rewrap so prior versions are not left decryptable at rest under a tier\n * the record has moved away from. Optional `tier0Dek` enables the legacy\n * fallback for snapshots written before this rewrap existed (see\n * `history.ts` for the full contract). No-op under `NO_HISTORY` (no\n * history = nothing to rewrap).\n */\n rewrapHistory(\n adapter: NoydbStore,\n vault: string,\n collection: string,\n recordId: string,\n fromDek: EnclaveKey,\n toDek: EnclaveKey,\n tier0Dek?: EnclaveKey,\n ): Promise<void>\n\n /**\n * Compute the SHA-256 hash of an envelope's encrypted payload, used\n * by `LedgerStore.append` to track tamper-evidence. Returns the\n * empty string under `NO_HISTORY` (the call site is gated by\n * `if (this.ledger)`, so the value is never observed).\n */\n envelopePayloadHash(envelope: EncryptedEnvelope | null): Promise<string>\n\n /**\n * Compute the JSON patch from `from` → `to`. Returns `[]` under\n * `NO_HISTORY`.\n */\n computePatch(from: unknown, to: unknown): JsonPatch\n\n /**\n * Compute the typed diff between two records. Throws under\n * `NO_HISTORY` — `collection.diff()` is a history-read API.\n */\n diff(recordA: unknown, recordB: unknown): DiffEntry[]\n\n /**\n * Construct (or return null) a `LedgerStore` for the vault. Returns\n * `null` under `NO_HISTORY`; the Vault treats null as \"no ledger\n * attached\" — collection write paths skip the append branch and the\n * public `vault.ledger()` accessor throws.\n */\n buildLedger(opts: BuildLedgerOptions): LedgerStore | null\n\n /**\n * Construct a `VaultInstant` for time-machine reads. Throws under\n * `NO_HISTORY`.\n */\n buildVaultInstant(engine: VaultEngine, timestamp: string): VaultInstant\n}\n\n/**\n * Error thrown when the consumer reaches a history-gated surface\n * without opting into the strategy. The message names the offending\n * operation and points to the subpath import.\n *\n * @internal\n */\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op} requires the history strategy. Import ` +\n '`{ withHistory }` from \"@noy-db/hub/history\" and pass it to ' +\n '`createNoydb({ historyStrategy: withHistory() })`.',\n )\n}\n\n/**\n * No-history stub. Snapshots and prune/clear are no-ops; reads and\n * time-machine throw with an actionable message; ledger construction\n * returns null so the write-path's `if (this.ledger)` branch is dead\n * code in the bundle.\n *\n * @internal\n */\nexport const NO_HISTORY: HistoryStrategy = {\n async saveHistory() {},\n async getHistoryEntries() { throw notEnabled('collection.history()') },\n async getVersionEnvelope() { throw notEnabled('collection.getVersion()') },\n async pruneHistory() { return 0 },\n async clearHistory() { return 0 },\n async tombstoneHistory() { return 0 },\n async rewrapHistory() {},\n async envelopePayloadHash() { return '' },\n computePatch() { return [] },\n diff() { throw notEnabled('collection.diff()') },\n buildLedger() { return null },\n buildVaultInstant() { throw notEnabled('vault.at() / vault.timeMachine()') },\n}\n"],"mappings":";AAsMA,SAAS,WAAW,IAAmB;AACrC,SAAO,IAAI;AAAA,IACT,GAAG,EAAE;AAAA,EAGP;AACF;AAUO,IAAM,aAA8B;AAAA,EACzC,MAAM,cAAc;AAAA,EAAC;AAAA,EACrB,MAAM,oBAAoB;AAAE,UAAM,WAAW,sBAAsB;AAAA,EAAE;AAAA,EACrE,MAAM,qBAAqB;AAAE,UAAM,WAAW,yBAAyB;AAAA,EAAE;AAAA,EACzE,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,eAAe;AAAE,WAAO;AAAA,EAAE;AAAA,EAChC,MAAM,mBAAmB;AAAE,WAAO;AAAA,EAAE;AAAA,EACpC,MAAM,gBAAgB;AAAA,EAAC;AAAA,EACvB,MAAM,sBAAsB;AAAE,WAAO;AAAA,EAAG;AAAA,EACxC,eAAe;AAAE,WAAO,CAAC;AAAA,EAAE;AAAA,EAC3B,OAAO;AAAE,UAAM,WAAW,mBAAmB;AAAA,EAAE;AAAA,EAC/C,cAAc;AAAE,WAAO;AAAA,EAAK;AAAA,EAC5B,oBAAoB;AAAE,UAAM,WAAW,kCAAkC;AAAA,EAAE;AAC7E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-party/team/tiers.ts"],"sourcesContent":["/**\n * Hierarchical access — tier-aware keyring helpers.\n *\n * The keyring's existing `deks: Map<string, CryptoKey>` is keyed by\n * collection name. extends the key space:\n *\n * `'invoices'` — tier-0 DEK (unchanged from v0.x)\n * `'invoices#1'` — tier-1 DEK\n * `'invoices#2'` — tier-2 DEK\n *\n * Tier 0 keeps the bare collection name so any keyring written\n * before tiers existed loads without migration. Tiers ≥ 1 use `#N`\n * suffixes that\n * would be invalid as user-supplied collection names (see\n * `ReservedCollectionNameError` — `#` is reserved).\n *\n * @module\n */\n\nimport type { UnlockedKeyring } from './keyring.js'\nimport { TierNotGrantedError } from '../../kernel/errors.js'\n\n/** Canonical DEK key for a given collection + tier. Tier 0 → bare name. */\nexport function dekKey(collection: string, tier: number): string {\n if (tier <= 0) return collection\n return `${collection}#${tier}`\n}\n\n/**\n * Returns the user's effective clearance for a given collection: the\n * maximum tier for which their keyring holds a DEK. Falls back to 0\n * when the user has only the tier-0 DEK (or none — the getDEK caller\n * will raise separately).\n */\nexport function effectiveClearance(keyring: UnlockedKeyring, collection: string): number {\n let max = 0\n const prefix = `${collection}#`\n for (const key of keyring.deks.keys()) {\n if (!key.startsWith(prefix)) continue\n const suffix = key.slice(prefix.length)\n const n = Number.parseInt(suffix, 10)\n if (Number.isFinite(n) && n > max) max = n\n }\n return max\n}\n\n/**\n * Assert the caller is cleared for the requested tier. Owners and\n * admins always pass (they can mint any new tier DEK on demand);\n * other roles must already hold the tier DEK — via a prior grant or\n * an active delegation — otherwise this throws `TierNotGrantedError`.\n *\n * This gate runs BEFORE `getDEK()` on the mutation path so a\n * non-cleared operator never has the opportunity to silently\n * auto-create a tier DEK they shouldn't have.\n */\nexport function assertTierAccess(\n keyring: UnlockedKeyring,\n collection: string,\n tier: number,\n): void {\n if (tier <= 0) return\n // FR-6: custodian operates every collection at every tier (admin-level\n // operational authority), so it may mint a tier DEK on demand like admin.\n if (keyring.role === 'owner' || keyring.role === 'admin' || keyring.role === 'custodian') return\n if (!keyring.deks.has(dekKey(collection, tier))) {\n throw new TierNotGrantedError(collection, tier)\n }\n}\n"],"mappings":";;;;;AAuBO,SAAS,OAAO,YAAoB,MAAsB;AAC/D,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO,GAAG,UAAU,IAAI,IAAI;AAC9B;AA8BO,SAAS,iBACd,SACA,YACA,MACM;AACN,MAAI,QAAQ,EAAG;AAGf,MAAI,QAAQ,SAAS,WAAW,QAAQ,SAAS,WAAW,QAAQ,SAAS,YAAa;AAC1F,MAAI,CAAC,QAAQ,KAAK,IAAI,OAAO,YAAY,IAAI,CAAC,GAAG;AAC/C,UAAM,IAAI,oBAAoB,YAAY,IAAI;AAAA,EAChD;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-formula/materialized-views/stale.ts"],"sourcesContent":["import type { Collection } from '../../kernel/collection.js'\nimport type { MaterializedViewExecutor as MVExecutorType } from './executor.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { PutDerivedOutputCtx } from '../../kernel/via/dispatch.js'\nimport type { MaterializedViewRegistry, RegisteredMV } from './registry.js'\n// Type-only — runtime class loaded via dynamic import in\n// `resolveStaleMVOnRead` only when a stale flag actually fires.\n// Keeps the executor chunk out of the floor bundle (mirrors v1 floor-bundle isolation).\nimport type { MVQueryContext } from './types.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport { RecordCodec } from '../../kernel/enclave/index.js'\n\nimport { lazy } from '../../kernel/lazy.js'\n\n/** #846c — one memoized binding instead of a cast at the call site. */\nconst loadMVExecutor = lazy(() => import('./executor.js'))\n\n/**\n * Accessor shape passed in from the owning Vault. Provides the\n * registry (used as a stable WeakMap key + to look up MVs by output\n * collection) and the runtime context the lazy refresh needs.\n * Mirrors v1's `DerivationStaleAccessor`.\n */\nexport interface MVStaleAccessor {\n registry(): MaterializedViewRegistry\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n getActiveTxContext(): TxContext | null\n getQueryContext(): MVQueryContext\n}\n\n/**\n * In-memory stale map keyed by `MaterializedViewRegistry` instance\n * (stable per vault). Each registry maps to a set of MV names that\n * have at least one pending source-change requiring a re-materialize.\n *\n * Persistence across vault close is NOT implemented in this iteration\n * (concern flagged in the v2 spec, mirrors v1 derivation behavior).\n * On vault re-open, the unset stale flag is interpreted as \"fresh\" —\n * `vault.refreshView(name)` is the explicit recompute escape hatch.\n *\n * @internal\n */\nconst _staleByRegistry = new WeakMap<MaterializedViewRegistry, Set<string>>()\n\n/**\n * Mark an MV as stale. Called from `Collection.dispatchMaterializedViews`\n * when a source-write fires for a `refresh: 'lazy'` MV.\n *\n * @internal\n */\nexport function markMVStale(registry: MaterializedViewRegistry, mvName: string): void {\n let set = _staleByRegistry.get(registry)\n if (!set) {\n set = new Set()\n _staleByRegistry.set(registry, set)\n }\n set.add(mvName)\n}\n\n/**\n * Test-only: check whether a given MV name is currently flagged stale\n * against a registry. Exported so the regression suite can pin the\n * stale-bit lifecycle without touching the internal `WeakMap`.\n *\n * @internal\n */\nexport function isMVStale(registry: MaterializedViewRegistry, mvName: string): boolean {\n return _staleByRegistry.get(registry)?.has(mvName) ?? false\n}\n\n/**\n * Reserved collection holding CONTENT-FREE lazy-stale markers (record id =\n * MV name, plaintext `_iv: ''` envelope, no payload) — mirrors the\n * `_meta`/schema-fence marker envelope shape. Written only from the\n * delete/forget/elevate dispatcher (#736); ordinary source writes stay\n * in-memory-only (the cheap path). Read via the adapter directly, never\n * through `vault.collection()` — same reserved-collection convention as\n * `_subject_index`/`_meta`.\n */\nexport const MV_STALE_COLLECTION = '_mv_stale'\n\n/**\n * Once-per-registry hydrate guard for `resolveStaleMVOnRead`'s persisted-marker fold-in.\n * Stores the in-flight/settled PROMISE (not a boolean) — a concurrent cold first read that\n * arrives while the hydrate is still awaiting `adapter.list` must await the SAME promise\n * rather than observing \"already hydrating\" and reading an empty pending set (#736\n * whole-branch review).\n */\nconst _hydratedByRegistry = new WeakMap<MaterializedViewRegistry, Promise<void>>()\n\n/** The adapter + vault name backing any collection in this vault (all collections share both). */\nfunction storeOf(accessor: MVStaleAccessor, collectionName: string): { adapter: NoydbStore; vault: string } {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const c = accessor.getCollection(collectionName) as any\n return { adapter: c.adapter as NoydbStore, vault: c.vault as string }\n}\n\nasync function writeMVStaleMarker(adapter: NoydbStore, vault: string, mvName: string): Promise<void> {\n // Content-free — the marker's only payload is its key (the MV name).\n const env = RecordCodec.buildPlaintextEnvelope({ version: 1, data: '{}' })\n await adapter.put(vault, MV_STALE_COLLECTION, mvName, env)\n}\n\nasync function deleteMVStaleMarker(adapter: NoydbStore, vault: string, mvName: string): Promise<void> {\n await adapter.delete(vault, MV_STALE_COLLECTION, mvName)\n}\n\n/**\n * On first `resolveStaleMVOnRead` call for a (cold-reopened) registry, fold every\n * persisted `_mv_stale` marker into the in-memory pending set — otherwise a cold\n * session's empty `WeakMap` entry reads as \"fresh\" and serves the emptied output\n * collection forever.\n */\nasync function hydratePersistedStaleMarkers(accessor: MVStaleAccessor, registry: MaterializedViewRegistry): Promise<void> {\n const mvs = registry.all()\n if (mvs.length === 0) return\n const { adapter, vault } = storeOf(accessor, mvs[0]!.outputCollection)\n // No try/catch: a genuine store failure here must surface, not be read as\n // \"nothing pending\" — silently treating it as fresh is the exact leak class\n // this module closes (mirrors `subject-index.ts`'s bare `adapter.list` reads).\n for (const name of await adapter.list(vault, MV_STALE_COLLECTION)) markMVStale(registry, name)\n}\n\n/**\n * Invalidate an MV from the delete/forget/elevate dispatcher (#736) — the ordinary\n * source-write path (`dispatchMaterializedViews`) never calls this. Deletes EVERY\n * persisted row in `reg.outputCollection` via `_internalDelete` (the at-rest law: a\n * stale mark alone leaves the elevated/forgotten source's plaintext sitting in the\n * output row) using the adapter directly so the read-path's `resolveStaleMVOnRead`\n * isn't triggered mid-invalidation. `mode: 'lazy'` also persists the stale mark so a\n * cold session recomputes on next read; `'manual'` gets the purge only — the MV\n * serves empty until an explicit `vault.refreshView()` (erasure wins). Deletion is\n * stamp-scoped (`_materializedFrom.mvName === reg.spec.name` — see the loop below),\n * so another registered MV sharing this output collection keeps its own rows intact:\n * no cross-MV re-marking is needed here, only `reg` itself is marked stale.\n *\n * Returns the count of rows actually `_internalDelete`d (#761 item 1) — folded by the\n * caller into `dispatchMaterializedViewsOnDelete`'s `deleted` so `ForgetResult.derivedRecordsErased`\n * counts lazy/manual purges too, not just the eager executor's tombstone leg — plus\n * `residueUndecodable`, the bare ids whose ownership stamp could NOT be decoded (#776): a\n * candidate row that fails to decode under the collection's default DEK (e.g. elevated above\n * tier 0 on a tiered output collection) has UNKNOWN ownership — it might be this MV's own\n * output, or (same-collection shape) a plain user record — so it is never erased, but it must\n * be SURFACED rather than silently skipped (the #724 posture), since it may still hold the\n * forgotten/pre-elevation contribution, decryptable by tier-holders — and `residueDeclined`\n * (#785), the bare ids that DID decode and stamp-match but whose `_internalDelete` declined\n * (ownership CONFIRMED, erasure declined).\n *\n * @internal\n */\nexport async function invalidateMVAtRest(\n accessor: MVStaleAccessor,\n reg: RegisteredMV,\n mode: 'lazy' | 'manual',\n): Promise<{ deleted: number; residueUndecodable: string[]; residueDeclined: string[] }> {\n const outputColl = accessor.getCollection(reg.outputCollection)\n const txCtx = accessor.getActiveTxContext()\n const { adapter, vault } = storeOf(accessor, reg.outputCollection)\n let deleted = 0\n const residueUndecodable: string[] = []\n const residueDeclined: string[] = []\n for (const id of await adapter.list(vault, reg.outputCollection)) {\n // A same-collection partition MV (`output: { collection: <source>, partition }`,\n // the DERIV-PP30-001 shape) writes INTO its own source collection — `adapter.list`\n // over `reg.outputCollection` then also returns untouched user source records.\n // Decode each candidate row (the invalidation path is rare; this cost is fine\n // here) and only erase rows THIS MV stamped via `_materializedFrom.mvName` —\n // an unstamped row, or one stamped by a different MV, is never this MV's to\n // delete (#736 whole-branch review, Critical).\n const envelope = await adapter.get(vault, reg.outputCollection, id)\n if (envelope === null) continue\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const decoded = await (outputColl as any)._decodeEnvelope(envelope, id)\n if (decoded === null) { residueUndecodable.push(id); continue } // #776 — ownership unknown, surfaced not skipped\n const stampedBy = (decoded as Record<string, unknown>)._materializedFrom as { mvName?: string } | undefined\n if (stampedBy?.mvName !== reg.spec.name) continue\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (await (outputColl as any)._internalDelete(id, txCtx)) {\n deleted++\n } else {\n // #782 part b — decoded AND stamp-owned, but erasure declined (#718 tier-elevation\n // gate). Ownership IS confirmed — a real silent survival, not a legit stamp-mismatch\n // skip. Surface it too, in its own channel (#785 — distinct from the decode-null case).\n residueDeclined.push(id)\n }\n }\n\n // `mode: 'manual'` gets the purge only (erasure wins, no auto-recompute promise);\n // `'lazy'` also marks + persists ITS OWN stale bit for cold-session recompute. No\n // sibling MV on the same output collection is touched here — the stamp-scoped\n // deletion above never erased sibling rows in the first place (#736 re-review).\n if (mode === 'lazy') {\n const registry = accessor.registry()\n markMVStale(registry, reg.spec.name)\n await writeMVStaleMarker(adapter, vault, reg.spec.name)\n }\n return { deleted, residueUndecodable, residueDeclined }\n}\n\n/**\n * Called from `Collection.get` (and any reader that materializes the\n * MV's output collection). If any MV producing `outputCollection` is\n * flagged stale, runs the executor against the live source state\n * before returning. No-op when there is no pending work — keeps the\n * read fast path negligible.\n *\n * `dispatchCtx` (#641): threaded from the calling `Collection`'s\n * `#dispatchCtx({ collection: outputCollection, id: 'resolve-on-read' })` — a read has no\n * real \"reacting write\" record, so `'resolve-on-read'` is the sentinel id, mirroring\n * `Vault.refreshView()`'s `'refreshView'` sentinel for the same reason. Passed straight\n * through to the executor so a stale row whose output lands in a closed period follows the\n * frozen-output rule (skip + `derivation:skipped-frozen`, #637) instead of throwing\n * `PeriodClosedError` out of a read.\n *\n * Dynamic-imports the executor only when a stale flag actually fires\n * (the floor-bundle isolation pattern v1 derivations established in\n * floor-bundle isolation pattern).\n */\nexport async function resolveStaleMVOnRead(\n accessor: MVStaleAccessor,\n outputCollection: string,\n dispatchCtx?: PutDerivedOutputCtx,\n): Promise<void> {\n const registry = accessor.registry()\n // Cold session: the in-memory WeakMap has no entry for this (freshly\n // constructed) registry yet — fold any persisted `_mv_stale` markers in\n // before reading the pending set, once per registry (#736). Memoize the\n // PROMISE, not a boolean: a concurrent first read arriving while the\n // hydrate is still awaiting `adapter.list` must await the SAME promise —\n // otherwise it observes \"already hydrating\", skips straight to an empty\n // pending set, and serves the purged/stale view as fresh (#736\n // whole-branch review, hydrate-once race). On rejection, evict the entry\n // BEFORE rethrowing — a cached rejected promise would otherwise poison the\n // MV read surface for the rest of the session (every later read re-awaits\n // the same rejection instead of retrying the store call) (#736 re-review).\n let hydrate = _hydratedByRegistry.get(registry)\n if (!hydrate) {\n hydrate = hydratePersistedStaleMarkers(accessor, registry).catch((err: unknown) => {\n _hydratedByRegistry.delete(registry)\n throw err\n })\n _hydratedByRegistry.set(registry, hydrate)\n }\n await hydrate\n const pending = _staleByRegistry.get(registry)\n if (!pending || pending.size === 0) return\n\n const { adapter, vault } = storeOf(accessor, outputCollection)\n\n // Clean up persisted markers for MV names no longer registered (renamed or\n // removed since the marker was written). Without this sweep an orphaned name\n // can never become a `candidate` below — `candidates` is built from\n // `registry.all()`, which no longer lists it — so both the in-memory pending\n // entry and the persisted `_mv_stale` row would linger forever, re-hydrating\n // on every cold session (#736 whole-branch review).\n for (const name of pending) {\n if (registry.byName(name)) continue\n pending.delete(name)\n await deleteMVStaleMarker(adapter, vault, name)\n }\n if (pending.size === 0) return\n\n // Find every MV that writes to this output collection AND is\n // currently flagged stale. Multiple MVs CAN share an output\n // collection in theory; in practice the registration validation +\n // cycle detection make this unusual.\n const candidates: string[] = []\n for (const mv of registry.all()) {\n if (mv.outputCollection !== outputCollection) continue\n if (!pending.has(mv.spec.name)) continue\n candidates.push(mv.spec.name)\n }\n if (candidates.length === 0) return\n\n let executor: typeof MVExecutorType | null = null\n for (const name of candidates) {\n const reg = registry.byName(name)\n if (!reg) {\n // Unreachable in practice — `candidates` is drawn from `registry.all()`,\n // and the orphan sweep above already cleared any name absent from it.\n // Kept as a defensive fallback; also clears the persisted marker so it\n // can't linger if this ever does fire.\n pending.delete(name)\n await deleteMVStaleMarker(adapter, vault, name)\n continue\n }\n executor ??= (await loadMVExecutor()).MaterializedViewExecutor\n // A cold-hydrated stale flag (unlike an in-session one) can fire with\n // NONE of the MV's dependency collections touched yet this session —\n // the sync `Query.toArray()` `spec.query()` runs reads straight off\n // `Collection`'s in-memory cache, populated only by a prior async\n // touch (`ensureHydrated()`, called from `get`/`list`/`put`, never\n // from `query()` itself). Warm every dependency first so the recompute\n // sees the live persisted state instead of an empty cache (#736).\n for (const dep of reg.dependencies) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (accessor.getCollection(dep) as any).ensureHydrated()\n }\n await executor.refresh(reg, {\n getCollection: (n) => accessor.getCollection(n),\n getActiveTxContext: () => accessor.getActiveTxContext(),\n getQueryContext: () => accessor.getQueryContext(),\n ...(dispatchCtx !== undefined ? { dispatchCtx } : {}),\n })\n pending.delete(name)\n // Runs even when no marker was ever persisted for this name (an in-session-only\n // stale bit — e.g. the cheap ordinary-write path never writes one, see the\n // \"cheap-path guarantee\" test). `adapter.delete` on an absent key is a harmless\n // void — keeping this unconditional avoids branching on marker origin here.\n await deleteMVStaleMarker(adapter, vault, name)\n }\n}\n\n/**\n * Drop every stale flag for a registry. Used after a manual\n * `vault.refreshView(name)` runs the executor explicitly — the\n * post-refresh state matches the registered strategies, so\n * lingering stale bits would force a redundant refresh on the next\n * read.\n *\n * @internal\n */\nexport function clearMVStale(registry: MaterializedViewRegistry, mvName: string): void {\n _staleByRegistry.get(registry)?.delete(mvName)\n}\n\n/**\n * `clearMVStale` plus the persisted marker (#736) — `Vault.refreshView()`'s\n * completion path. A lingering persisted marker after a manual refresh would\n * make the NEXT cold session recompute redundantly.\n *\n * @internal\n */\nexport async function clearMVStaleFully(\n adapter: NoydbStore,\n vault: string,\n registry: MaterializedViewRegistry,\n mvName: string,\n): Promise<void> {\n clearMVStale(registry, mvName)\n await deleteMVStaleMarker(adapter, vault, mvName)\n}\n"],"mappings":";;;;;;;;AAeA,IAAM,iBAAiB,KAAK,MAAM,OAAO,wBAAe,CAAC;AA4BzD,IAAM,mBAAmB,oBAAI,QAA+C;AAQrE,SAAS,YAAY,UAAoC,QAAsB;AACpF,MAAI,MAAM,iBAAiB,IAAI,QAAQ;AACvC,MAAI,CAAC,KAAK;AACR,UAAM,oBAAI,IAAI;AACd,qBAAiB,IAAI,UAAU,GAAG;AAAA,EACpC;AACA,MAAI,IAAI,MAAM;AAChB;AASO,SAAS,UAAU,UAAoC,QAAyB;AACrF,SAAO,iBAAiB,IAAI,QAAQ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AAK,IAAI;AAAA,EAC9B;AACA,MAAI,WAAW,WAAW,EAAG;AAE7B,MAAI,WAAyC;AAC7C,aAAW,QAAQ,YAAY;AAC7B,UAAM,MAAM,SAAS,OAAO,IAAI;AAChC,QAAI,CAAC,KAAK;AAKR,cAAQ,OAAO,IAAI;AACnB,YAAM,oBAAoB,SAAS,OAAO,IAAI;AAC9C;AAAA,IACF;AACA,kBAAc,MAAM,eAAe,GAAG;AAQtC,eAAW,OAAO,IAAI,cAAc;AAElC,YAAO,SAAS,cAAc,GAAG,EAAU,eAAe;AAAA,IAC5D;AACA,UAAM,SAAS,QAAQ,KAAK;AAAA,MAC1B,eAAe,CAAC,MAAM,SAAS,cAAc,CAAC;AAAA,MAC9C,oBAAoB,MAAM,SAAS,mBAAmB;AAAA,MACtD,iBAAiB,MAAM,SAAS,gBAAgB;AAAA,MAChD,GAAI,gBAAgB,SAAY,EAAE,YAAY,IAAI,CAAC;AAAA,IACrD,CAAC;AACD,YAAQ,OAAO,IAAI;AAKnB,UAAM,oBAAoB,SAAS,OAAO,IAAI;AAAA,EAChD;AACF;AAWO,SAAS,aAAa,UAAoC,QAAsB;AACrF,mBAAiB,IAAI,QAAQ,GAAG,OAAO,MAAM;AAC/C;AASA,eAAsB,kBACpB,SACA,OACA,UACA,QACe;AACf,eAAa,UAAU,MAAM;AAC7B,QAAM,oBAAoB,SAAS,OAAO,MAAM;AAClD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-shape/persisted-schemas/storage.ts"],"sourcesContent":["/**\n * Read / write the per-collection persisted-schema envelope. Mirrors the\n * standard noy-db record envelope shape and is **AES-GCM encrypted with\n * the collection's DEK** — the schema body (field names, enum values,\n * constraints) is sensitive metadata, so it gets the same encryption\n * envelope as the records it describes.\n *\n * Storage layout:\n *\n * <vault>/_schemas/<collection> → EncryptedEnvelope\n *\n * The DEK passed to {@link savePersistedSchema} / {@link loadPersistedSchema}\n * is the same key the collection uses for its records.\n *\n * @module\n */\n\nimport { encrypt, openEnvelopeJson, type EnclaveKey } from '../../kernel/enclave/index.js'\nimport { NOYDB_FORMAT_VERSION } from '../../kernel/types.js'\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { PersistedSchemaEnvelope } from './types.js'\n\n/** Reserved collection name where persisted schemas live. */\nexport const SCHEMAS_COLLECTION = '_schemas' as const\n\n/**\n * A decrypted persisted-schema read paired with the wrapping envelope's\n * `_v`. The version is the optimistic-concurrency token: pass it back to\n * {@link savePersistedSchema} as `expectedVersion` to make the write a CAS\n * that rejects a stale put (see #583 — the `_schemas` record is shared by\n * the JSON-Schema writer and the classified-marker writer).\n */\nexport interface PersistedSchemaEntry {\n /** Wrapping envelope `_v` (0 when no record exists yet). */\n readonly version: number\n /** Decrypted payload, or `undefined` when absent/corrupt/wrong-DEK. */\n readonly payload: PersistedSchemaEnvelope | undefined\n}\n\n/**\n * Read the persisted-schema envelope for one collection together with its\n * wrapping `_v`. The version reflects the raw stored envelope even when the\n * payload cannot be decrypted/parsed (so a CAS still guards a corrupt record\n * rather than silently clobbering it).\n */\nexport async function loadPersistedSchemaEntry(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n): Promise<PersistedSchemaEntry> {\n const envelope = await store.get(vault, SCHEMAS_COLLECTION, collection)\n if (!envelope) return { version: 0, payload: undefined }\n const version = envelope._v\n try {\n const plaintext = await openEnvelopeJson(envelope, dek)\n const parsed = JSON.parse(plaintext) as PersistedSchemaEnvelope\n if (parsed._noydb_schema !== 1) return { version, payload: undefined }\n return { version, payload: parsed }\n } catch {\n return { version, payload: undefined }\n }\n}\n\n/**\n * Read and decrypt the persisted-schema envelope for one collection.\n * Returns `undefined` when no envelope has been written or when decryption\n * fails (e.g. wrong DEK passed). Tolerates corrupted records — JSON parse\n * failures surface as `undefined`, mirroring `_meta/handle`'s contract.\n */\nexport async function loadPersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n): Promise<PersistedSchemaEnvelope | undefined> {\n return (await loadPersistedSchemaEntry(store, vault, collection, dek)).payload\n}\n\n/**\n * Encrypt and persist a schema envelope for one collection. Always\n * overwrites any prior write (callers gate on hash equality before calling\n * to avoid no-op writes).\n *\n * Pass `expectedVersion` — the `version` from {@link loadPersistedSchemaEntry}\n * captured at load time — to make the write an optimistic CAS: on a store with\n * `casAtomic`, `store.put` throws {@link ConflictError} when the record was\n * bumped concurrently, so a lost update on the shared `_schemas` record is\n * rejected instead of silently clobbering the other writer's field (#583).\n * When omitted, keeps the legacy unconditional last-writer-wins behaviour.\n */\nexport async function savePersistedSchema(\n store: NoydbStore,\n vault: string,\n collection: string,\n dek: EnclaveKey,\n payload: PersistedSchemaEnvelope,\n expectedVersion?: number,\n): Promise<void> {\n const json = JSON.stringify(payload)\n const { iv, data } = await encrypt(json, dek)\n const baseVersion = expectedVersion ?? (await store.get(vault, SCHEMAS_COLLECTION, collection))?._v ?? 0\n const env: EncryptedEnvelope = {\n _noydb: NOYDB_FORMAT_VERSION,\n _v: baseVersion + 1,\n _ts: new Date().toISOString(),\n _iv: iv,\n _data: data,\n }\n await store.put(vault, SCHEMAS_COLLECTION, collection, env, expectedVersion)\n}\n"],"mappings":";;;;;;;;;;;AAuBO,IAAM,qBAAqB;AAsBlC,eAAsB,yBACpB,OACA,OACA,YACA,KAC+B;AAC/B,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,oBAAoB,UAAU;AACtE,MAAI,CAAC,SAAU,QAAO,EAAE,SAAS,GAAG,SAAS,OAAU;AACvD,QAAM,UAAU,SAAS;AACzB,MAAI;AACF,UAAM,YAAY,MAAM,iBAAiB,UAAU,GAAG;AACtD,UAAM,SAAS,KAAK,MAAM,SAAS;AACnC,QAAI,OAAO,kBAAkB,EAAG,QAAO,EAAE,SAAS,SAAS,OAAU;AACrE,WAAO,EAAE,SAAS,SAAS,OAAO;AAAA,EACpC,QAAQ;AACN,WAAO,EAAE,SAAS,SAAS,OAAU;AAAA,EACvC;AACF;AAQA,eAAsB,oBACpB,OACA,OACA,YACA,KAC8C;AAC9C,UAAQ,MAAM,yBAAyB,OAAO,OAAO,YAAY,GAAG,GAAG;AACzE;AAcA,eAAsB,oBACpB,OACA,OACA,YACA,KACA,SACA,iBACe;AACf,QAAM,OAAO,KAAK,UAAU,OAAO;AACnC,QAAM,EAAE,IAAI,KAAK,IAAI,MAAM,QAAQ,MAAM,GAAG;AAC5C,QAAM,cAAc,oBAAoB,MAAM,MAAM,IAAI,OAAO,oBAAoB,UAAU,IAAI,MAAM;AACvG,QAAM,MAAyB;AAAA,IAC7B,QAAQ;AAAA,IACR,IAAI,cAAc;AAAA,IAClB,MAAK,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC5B,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AACA,QAAM,MAAM,IAAI,OAAO,oBAAoB,YAAY,KAAK,eAAe;AAC7E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-formula/materialized-views/with-materialized-view.ts"],"sourcesContent":["import { MaterializedViewConfigError, ValidationError } from '../../kernel/errors.js'\nimport type { MaterializedViewSpec, MaterializedViewStrategy } from './types.js'\n\n/**\n * Register a materialized view: a declared query whose result is\n * persisted as a queryable collection and kept fresh as sources\n * change. Writes go through the standard `Collection.put` pipeline;\n * refresh-driven deletes route through `Collection._internalDelete` so\n * user `onDelete` guards on the output collection aren't tripped by\n * housekeeping.\n *\n * Three registration modes:\n * - **single-source** — declare `query: (db) => Query<TRow>`; the\n * dependency analyzer derives source collections from the plan.\n * - **UNION** — declare `unionSources: [{ collection, map }, ...]`\n * plus optional `groupBy` + `aggregate`; the executor reads each\n * arm, maps to the unified row shape, concatenates, then groups\n * and aggregates.\n * - **projection** (#810) — declare `projection: { source, joins,\n * map }`; one output row per primary record, enriched with\n * forward FK legs and reverse \"collect\" legs before `map` runs.\n *\n * The three modes are mutually exclusive — exactly one of `query` /\n * `unionSources` / `projection` must be set at registration time.\n *\n * See design-history/2026-05-20-dim14-mv-v2-design.md (single-source v2),\n * design-history/2026-05-21-dim14-mv-multikey-and-union.md (UNION),\n * and design-history/2026-07-25-join-projection-mv-design.md (projection).\n */\nexport function withMaterializedView<TRow extends Record<string, unknown>>(\n spec: MaterializedViewSpec<TRow>,\n): MaterializedViewStrategy {\n if (!spec.name || spec.name.length === 0) {\n throw new ValidationError('withMaterializedView: name is required')\n }\n // Mutual exclusion: exactly one of the three forms must be declared.\n const declaredForms = [spec.query, spec.unionSources, spec.projection]\n .filter((f) => f !== undefined).length\n if (declaredForms > 1) {\n throw new MaterializedViewConfigError(\n 'query, unionSources, and projection are mutually exclusive — pick one',\n )\n }\n if (declaredForms === 0) {\n throw new MaterializedViewConfigError(\n 'strategy must declare exactly one of query, unionSources, or projection',\n )\n }\n if (spec.query !== undefined && typeof spec.query !== 'function') {\n throw new ValidationError('withMaterializedView: query must be a function returning a Query<T>')\n }\n // UNION-form invariants.\n if (spec.unionSources) {\n // A single arm is a deliberate shape: map→group→aggregate over\n // ONE collection with a COMPUTED bucket key (e.g. month sliced from a\n // date field) — something the query form's stored-field groupBy cannot\n // express. The executor and dependency analyzer are arm-count-agnostic.\n if (spec.unionSources.length < 1) {\n throw new MaterializedViewConfigError(\n 'unionSources requires at least 1 source collection',\n )\n }\n const seen = new Set<string>()\n for (const s of spec.unionSources) {\n if (typeof s?.collection !== 'string' || s.collection.length === 0) {\n throw new MaterializedViewConfigError(\n 'each unionSources entry must declare a non-empty `collection` string',\n )\n }\n if (typeof s.map !== 'function') {\n throw new MaterializedViewConfigError(\n `unionSources entry for \"${s.collection}\" is missing a \\`map\\` function`,\n )\n }\n if (seen.has(s.collection)) {\n throw new MaterializedViewConfigError(\n `unionSources must reference distinct collections (duplicate: \"${s.collection}\")`,\n )\n }\n seen.add(s.collection)\n }\n if (Array.isArray(spec.groupBy) && spec.groupBy.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": groupBy must not be an empty array — omit it or provide at least one field name`,\n )\n }\n if (spec.aggregate && !spec.groupBy) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": UNION strategy with aggregate requires groupBy — `\n + `use groupBy to declare the bucketing keys, or remove aggregate for a pure dedup MV`,\n )\n }\n // `moneyFields` only has meaning when there's an aggregate to\n // money-rewrite — it keys reducer outputs, so declaring it without\n // `aggregate` is a no-op config mistake.\n if (spec.moneyFields && !spec.aggregate) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": moneyFields requires aggregate — `\n + `moneyFields rewrites sum/min/max reducers over money output fields, `\n + `so it is meaningless without an aggregate spec`,\n )\n }\n // Per-arm joins resolve right-side collections that the union\n // dependency set (built from arm `collection`s alone) does NOT\n // include. The consumer must list those right-side collections in\n // `sources` so writes to them trigger MV refresh.\n if (spec.unionSources.some(s => s.join && s.join.length > 0) && (!spec.sources || spec.sources.length === 0)) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": a unionSources arm declares join(s) but `\n + `no \\`sources\\` are listed — declare sources: [...] with the right-side `\n + `(join-target) collection names so writes to them trigger MV refresh`,\n )\n }\n if (spec.predicates) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": predicates are not supported on UNION strategies — `\n + `UNION mode does not use a Query<T> chain, so .wherePredicate() cannot fire. `\n + `Use the query() form, or open an issue if per-arm predicates are needed`,\n )\n }\n }\n // Projection-form invariants (#810). Shape checks only — the\n // semantic ref() check on collect legs (the `on` field must carry a\n // ref() targeting the projection source) runs at first\n // materialization, parity with join-time ref errors.\n if (spec.projection) {\n const projection = spec.projection\n if (typeof projection.source !== 'string' || projection.source.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": projection.source must be a non-empty collection name`,\n )\n }\n if (typeof projection.map !== 'function') {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": projection is missing a \\`map\\` function`,\n )\n }\n if (!Array.isArray(projection.joins) || projection.joins.length < 1) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": projection.joins must declare at least 1 leg — `\n + `a leg-less single-source MV is the query() form's job`,\n )\n }\n const seenAs = new Set<string>()\n for (const leg of projection.joins) {\n const l = leg as { field?: unknown; collect?: unknown; on?: unknown; as?: unknown }\n const isForward = l.field !== undefined\n const isCollect = l.collect !== undefined\n if (isForward && isCollect) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": a projection leg cannot declare both \\`field\\` `\n + `(forward) and \\`collect\\` (reverse) — split it into two legs`,\n )\n }\n if (!isForward && !isCollect) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": each projection leg must declare either \\`field\\` `\n + `(forward FK) or \\`collect\\` (reverse one-to-many)`,\n )\n }\n if (isForward && (typeof l.field !== 'string' || l.field.length === 0)) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": a forward projection leg must declare a non-empty \\`field\\``,\n )\n }\n if (isCollect) {\n if (typeof l.collect !== 'string' || l.collect.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": a collect projection leg must declare a non-empty \\`collect\\` collection name`,\n )\n }\n if (typeof l.on !== 'string' || l.on.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": collect leg for \"${l.collect}\" must declare a non-empty \\`on\\` FK field`,\n )\n }\n }\n if (typeof l.as !== 'string' || l.as.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": each projection leg must declare a non-empty \\`as\\` alias`,\n )\n }\n if (seenAs.has(l.as)) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": projection legs must attach under distinct \\`as\\` aliases (duplicate: \"${l.as}\")`,\n )\n }\n seenAs.add(l.as)\n }\n // Post-map grouping invariants — same rules as UNION (the mapped\n // stream feeds the same shared groupAndReduce tail).\n if (Array.isArray(spec.groupBy) && spec.groupBy.length === 0) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": groupBy must not be an empty array — omit it or provide at least one field name`,\n )\n }\n if (spec.aggregate && !spec.groupBy) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": projection strategy with aggregate requires groupBy — `\n + `use groupBy to declare the bucketing keys, or remove aggregate for a row-per-primary-record MV`,\n )\n }\n if (spec.moneyFields && !spec.aggregate) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": moneyFields requires aggregate — `\n + `moneyFields rewrites sum/min/max reducers over money output fields, `\n + `so it is meaningless without an aggregate spec`,\n )\n }\n if (spec.predicates) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": predicates are not supported on projection strategies — `\n + `projection mode does not use a Query<T> chain, so .wherePredicate() cannot fire. `\n + `Filter inside projection.map (return null to omit) instead`,\n )\n }\n }\n // i18nLocale + i18nFields drive compute-time i18n resolution of group-key\n // i18nText fields before bucketing — UNION mode (resolved on the unified rows)\n // AND query mode (resolved in GroupedReduction.run before groupAndReduce).\n // i18nLocale without i18nFields cannot resolve anything, so reject it early.\n if (spec.i18nLocale !== undefined && spec.i18nFields === undefined) {\n throw new MaterializedViewConfigError(\n `withMaterializedView \"${spec.name}\": i18nLocale requires i18nFields — `\n + `declare the i18nText descriptors of the group-key fields so they can be `\n + `resolved at the mv layer before bucketing.`,\n )\n }\n if (typeof spec.rowKey !== 'function') {\n throw new ValidationError('withMaterializedView: rowKey is required (no default; see spec § Type surface)')\n }\n if (spec.refresh !== 'eager' && spec.refresh !== 'lazy' && spec.refresh !== 'manual') {\n throw new ValidationError(\n `withMaterializedView: refresh must be 'eager' | 'lazy' | 'manual', got \"${String(spec.refresh)}\"`,\n )\n }\n return {\n __noydb_strategy: 'materialized-view',\n spec,\n }\n}\n"],"mappings":";;;;;;AA6BO,SAAS,qBACd,MAC0B;AAC1B,MAAI,CAAC,KAAK,QAAQ,KAAK,KAAK,WAAW,GAAG;AACxC,UAAM,IAAI,gBAAgB,wCAAwC;AAAA,EACpE;AAEA,QA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IAGpC;AAAA,EACF;AACA,MAAI,OAAO,KAAK,WAAW,YAAY;AACrC,UAAM,IAAI,gBAAgB,mFAAgF;AAAA,EAC5G;AACA,MAAI,KAAK,YAAY,WAAW,KAAK,YAAY,UAAU,KAAK,YAAY,UAAU;AACpF,UAAM,IAAI;AAAA,MACR,2EAA2E,OAAO,KAAK,OAAO,CAAC;AAAA,IACjG;AAAA,EACF;AACA,SAAO;AAAA,IACL,kBAAkB;AAAA,IAClB;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kernel/query/join.ts"],"sourcesContent":["/**\n * Query DSL `.join()` — eager, single-FK, intra-vault joins.\n *\n * resolves a ref()-declared foreign key into an attached\n * right-side record under an alias, using one of two planner paths\n * selected automatically:\n *\n * - **nested-loop** — right-side source exposes `lookupById`, so\n * each left row costs O(1). This is the common path for joins\n * against a Collection, which backs `lookupById` with a Map\n * lookup.\n * - **hash** — right-side has only `snapshot()`. Build a\n * `Map<id, record>` once, probe per left row. Same asymptotic\n * cost for our collections, but the path exists as a fallback\n * for custom QuerySource implementations and as an explicit\n * test-only override via `{ strategy: 'hash' }`.\n *\n * Scope:\n *\n * - Equi-joins on declared `ref()` fields only. Joins on\n * undeclared fields throw at plan time with an actionable error\n * naming the field and collection.\n * - Same-vault only. Cross-vault correlation goes\n * through `queryAcross`; this is an architectural\n * invariant, not a limitation we plan to lift.\n * - Hard row ceiling via `JoinTooLargeError` — default 50k per\n * side, override via `{ maxRows }`. Warns at 80% of the ceiling\n * on the existing warn channel.\n * - Three ref-mode behaviors on dangling refs:\n * strict → `DanglingReferenceError`,\n * warn → attach `null` with a one-shot warning,\n * cascade → attach `null` silently (cascade is a delete-time\n * mode; any dangling refs still present at read time are\n * mid-flight cascades or orphans from earlier, not a DSL error).\n *\n * Partition-awareness seam:\n *\n * Every `JoinLeg` carries a `partitionScope` field that is always\n * `'all'` in. The executor never reads this field.\n * partition-aware joins will start populating it from `where()`\n * predicates on the partition key without changing the planner's\n * external shape — this is the whole reason it exists now.\n *\n * Joins stay OUT of the ledger: reads don't touch `_ledger/`,\n * including joined reads.\n */\n\nimport type { RefDescriptor, RefMode } from '../refs.js'\nimport { readPath } from './predicate.js'\nimport { JoinTooLargeError, DanglingReferenceError } from '../errors.js'\n\n/** Planner strategy for a single join leg. Auto-selected unless overridden. */\nexport type JoinStrategy = 'hash' | 'nested'\n\n/** Default per-side row ceiling before `.join()` throws `JoinTooLargeError`. */\nexport const DEFAULT_JOIN_MAX_ROWS = 50_000\n\n/**\n * Fraction of the row ceiling at which a one-shot warning is emitted.\n * At 80% we warn; at 100% we throw. The warn gives consumers a\n * heads-up before the hard error so they can raise the ceiling or\n * filter further without first hitting a broken query.\n */\nconst JOIN_WARN_FRACTION = 0.8\n\n/**\n * Internal representation of a single join leg in the query plan.\n *\n * This is the primary place where constraint #1 is honored:\n * every leg carries a `partitionScope` field that is always `'all'`\n * in and is never read by the executor. partition-aware\n * joins will start populating it from `where()` predicates on the\n * partition key without changing the planner's external shape.\n */\nexport interface JoinLeg {\n /** Field on the left-side record holding the foreign key value. */\n readonly field: string\n /** Alias key under which the joined right-side record attaches. */\n readonly as: string\n /** Target collection name, resolved from the `ref()` declaration. */\n readonly target: string\n /** Ref mode controlling behavior on dangling refs at read time. */\n readonly mode: RefMode\n /** Manual planner strategy override. `undefined` → auto-select. */\n readonly strategy: JoinStrategy | undefined\n /** Per-side row ceiling override. `undefined` → DEFAULT_JOIN_MAX_ROWS. */\n readonly maxRows: number | undefined\n /**\n * Partition scope for future partition-aware joins. Always `'all'`\n * today — the executor never reads this field. Future versions will\n * populate it from `where()` predicates without breaking the\n * planner's external shape. Do not remove even though it looks\n * unused today — that's the whole point of having it.\n */\n readonly partitionScope: 'all' | readonly string[]\n /**\n * When `true`, this is a dictionary join. The executor\n * resolves the left-field value against the dict snapshot and\n * attaches `{ ...labels, key }` rather than a right-side record.\n * `target` holds the dictionary name (not a collection name).\n */\n readonly isDictJoin?: true\n}\n\n/**\n * Minimal shape of a joinable right-side record source.\n *\n * Collections implement this structurally via their `QuerySource`;\n * sources without `lookupById` force the hash-join fallback. Kept as\n * a thin interface so tests can wire up plain-object sources without\n * pulling in the full Collection class.\n *\n * The optional `subscribe` is used by `Query.live()` to merge\n * right-side change streams into the live re-run trigger. Sources\n * that omit `subscribe` still work for live joins — they just\n * don't drive re-fires when their right side mutates. Collection\n * implements `subscribe` by hooking into the existing per-\n * vault event emitter.\n */\nexport interface JoinableSource {\n snapshot(): readonly unknown[]\n lookupById?(id: string): unknown\n /**\n * Default locale a label-resolving query falls back to when the query\n * itself is locale-less. Set by a `staticDict()`-backed source from its\n * `displayLocale` so `{ by: 'label' }` resolves under a locale-less read.\n * Plain `_dict_*`-backed sources omit it.\n */\n readonly displayLocale?: string\n /**\n * Sync present-for-join dressing (#626 retirement, #650 Task 6) — when\n * present and the query carries a locale, each joined right-side record\n * is passed through this hook (built by the right-side `Collection` from\n * its own i18n-text + lookup-label bindings) BEFORE it is attached under\n * the leg's alias — so a joined `i18nText` field resolves to a string\n * (not a raw `{ locale }` map) and a joined lookup field gains its\n * `<field>Label`. Locale-less queries leave joined fields raw\n * (consistent with a locale-less read). Replaces the old `i18nFields`\n * data field — the join executor no longer resolves i18n locale itself,\n * it just calls this hook.\n */\n readonly presentForJoin?: (record: unknown, locale: string) => unknown\n /**\n * Subscribe to mutations on this source. The callback fires\n * AFTER the underlying record set has been updated. Returns an\n * unsubscribe function. Optional — sources without this method\n * cannot trigger live-join re-fires from their side.\n */\n subscribe?(cb: () => void): () => void\n}\n\n/**\n * Join resolution context attached to a `Query` when it's constructed\n * from a `Collection`. Holds everything the `.join()` method needs to\n * translate a field name into a target collection + ref mode, and\n * everything the executor needs to read the right side.\n *\n * Kept as a structural interface so `Vault` can implement it\n * without `Query` needing to import `Vault` (circular-import\n * avoid). The Collection wires this up in its `query()` method using\n * the `joinResolver` back-reference the Vault passes in.\n */\nexport interface JoinContext {\n /** Name of the left-side (owning) collection. */\n readonly leftCollection: string\n /**\n * The owning collection's default locale. Used to resolve joined\n * i18n fields at the `join` layer when a terminal call doesn't pass an\n * explicit locale — so `openVault({ locale })` flows to joins like it does\n * to `get`/`list`. A per-call `toArray({ locale })` overrides it.\n */\n readonly defaultLocale?: string\n /** Look up a `RefDescriptor` by field name on the left collection. */\n resolveRef(field: string): RefDescriptor | null\n /** Resolve a right-side source by target collection name. */\n resolveSource(collectionName: string): JoinableSource | null\n /**\n * Resolve a dictKey join source. Returns a `JoinableSource`\n * whose snapshot exposes `{ key, ...labels }` records, keyed by the\n * stable dictionary key. `null` when the field is not a dictKey.\n *\n * The source is built from the compartment's in-memory dictionary\n * snapshot — same data as `DictionaryHandle.list()`, O(1) per lookup.\n */\n resolveDictSource?(field: string): JoinableSource | null\n}\n\n/**\n * Coerce an unknown FK value into a lookup key string.\n *\n * Legitimate ref values are strings or numbers — the same narrowing\n * the write-time `enforceRefsOnPut` path applies. Anything else\n * (objects, arrays, booleans, null, undefined) is treated as \"no\n * ref\" and returns `null`, so the join attaches `null` instead of\n * running `String({})` and producing `'[object Object]'` as a\n * bucket key. This matches the lint rule guidance and keeps\n * bizarre FK values from producing silently-wrong lookups.\n */\nfunction coerceRefKey(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'bigint') return String(value)\n return null\n}\n\n/**\n * Warn-channel deduplication for dangling-ref `'warn'` mode. Keyed\n * by `field → target:refId` so the same dangling ref only produces\n * one warning even across many rows or repeated queries.\n */\nconst warnedDanglingKeys = new Set<string>()\nfunction warnOnceDangling(field: string, target: string, refId: string): void {\n const key = `${field}→${target}:${refId}`\n if (warnedDanglingKeys.has(key)) return\n warnedDanglingKeys.add(key)\n console.warn(\n `[noy-db] .join() encountered dangling ref in 'warn' mode: ` +\n `field \"${field}\" → \"${target}:${refId}\" not found. Attaching null.`,\n )\n}\n\n/**\n * Track row-ceiling warnings to fire only once per (target, side).\n * Prevents per-query spam when a consumer is running the same query\n * repeatedly (e.g. in a reactive loop).\n */\nconst warnedCeilingKeys = new Set<string>()\nfunction warnCeilingApproaching(\n target: string,\n side: 'left' | 'right',\n rows: number,\n maxRows: number,\n): void {\n const key = `${target}:${side}`\n if (warnedCeilingKeys.has(key)) return\n warnedCeilingKeys.add(key)\n const pct = Math.round((rows / maxRows) * 100)\n console.warn(\n `[noy-db] .join() ${side} side is at ${pct}% of the ${maxRows}-row ` +\n `ceiling for target \"${target}\" (${rows} rows). Streaming joins over ` +\n `scan() are not yet supported for collections that need to exceed this.`,\n )\n}\n\n/**\n * Apply every join leg in the plan against a base set of left-side\n * rows. Called by the query executor after `where` / `orderBy` /\n * `offset` / `limit` have narrowed the left set.\n *\n * Each leg attaches a `leg.as` field to every row. Returns a new\n * array of plain objects — the original left rows are not mutated\n * (structural sharing is fine for the inner fields, but the\n * top-level object is a fresh clone so consumers can further mutate\n * safely).\n *\n * **Ordering:** joins run AFTER orderBy / limit / offset in v1.\n * This keeps the planner simple and means queries like \"top 10\n * invoices with client\" sort and paginate the left side first, then\n * join. Sorting *by* a joined field is out of scope for — users\n * can post-sort the result array in userland or wait for \n * (multi-FK chaining) which can be layered on top.\n *\n * **Multi-FK chaining:** each leg's `maxRows` is enforced\n * against the current left-row count independently. Because\n * joins are equi-joins on the target's primary key (one-to-one or\n * one-to-null), the left row count is constant across legs — no\n * cartesian blowup. The per-leg left-side check is still necessary\n * so that a later leg with a tighter ceiling correctly fires on a\n * query like `.join('a', { maxRows: 100_000 }).join('b', { maxRows: 50 })`,\n * which should throw on the second leg if the left set exceeds 50.\n */\nexport function applyJoins(\n rows: readonly unknown[],\n joins: readonly JoinLeg[],\n context: JoinContext,\n locale?: string,\n): unknown[] {\n if (joins.length === 0) return [...rows]\n\n let result: unknown[] = [...rows]\n for (const leg of joins) {\n result = applyOneJoin(result, leg, context, locale)\n }\n return result\n}\n\nfunction applyOneJoin(\n leftRows: readonly unknown[],\n leg: JoinLeg,\n context: JoinContext,\n locale?: string,\n): unknown[] {\n // Dict join path — resolve left-field value against the\n // dictionary snapshot and attach { key, ...labels } under leg.as.\n if (leg.isDictJoin) {\n const dictSource = context.resolveDictSource?.(leg.field)\n if (!dictSource) {\n throw new Error(\n `.join() field \"${leg.field}\" on \"${context.leftCollection}\" is declared as a ` +\n `dictKey join but the dict source could not be resolved. ` +\n `Ensure the dictionary has at least one entry.`,\n )\n }\n const out: unknown[] = []\n const snapshot = dictSource.snapshot()\n const dictMap = new Map<string, unknown>()\n for (const entry of snapshot) {\n const k = readPath(entry, 'key')\n if (typeof k === 'string') dictMap.set(k, entry)\n }\n for (const left of leftRows) {\n const rawId = readPath(left, leg.field)\n const key = coerceRefKey(rawId)\n const dictEntry = key === null ? undefined : dictMap.get(key)\n out.push({ ...(left as Record<string, unknown>), [leg.as]: dictEntry ?? null })\n }\n return out\n }\n\n const source = context.resolveSource(leg.target)\n if (!source) {\n throw new Error(\n `.join() cannot resolve target collection \"${leg.target}\" ` +\n `(referenced from field \"${leg.field}\" on \"${context.leftCollection}\"). ` +\n `Make sure the target collection has been opened via vault.collection() ` +\n `at least once before running the query.`,\n )\n }\n\n const maxRows = leg.maxRows ?? DEFAULT_JOIN_MAX_ROWS\n\n // Per-leg left-side ceiling check. In a\n // multi-FK chain, each leg's `maxRows` is enforced independently\n // against the current left-row count, so\n // `.join('a', { maxRows: 100_000 }).join('b', { maxRows: 50 })`\n // correctly throws on the second leg if the left set exceeds 50.\n if (leftRows.length > maxRows) {\n throw new JoinTooLargeError({\n leftRows: leftRows.length,\n rightRows: -1,\n maxRows,\n side: 'left',\n message:\n `.join() left side has ${leftRows.length} rows, exceeding the ${maxRows}-row ` +\n `ceiling for target \"${leg.target}\". Filter the left side further with ` +\n `where()/limit() before joining, or raise the ceiling via { maxRows }. ` +\n `Streaming joins over scan() are not yet supported.`,\n })\n }\n if (leftRows.length > maxRows * JOIN_WARN_FRACTION) {\n warnCeilingApproaching(leg.target, 'left', leftRows.length, maxRows)\n }\n\n const rightSnapshot = source.snapshot()\n if (rightSnapshot.length > maxRows) {\n throw new JoinTooLargeError({\n leftRows: leftRows.length,\n rightRows: rightSnapshot.length,\n maxRows,\n side: 'right',\n message:\n `.join() right side \"${leg.target}\" has ${rightSnapshot.length} rows, ` +\n `exceeding the ${maxRows}-row ceiling. Raise the ceiling via { maxRows } ` +\n `if the data genuinely fits in memory, or track for streaming joins.`,\n })\n }\n if (rightSnapshot.length > maxRows * JOIN_WARN_FRACTION) {\n warnCeilingApproaching(leg.target, 'right', rightSnapshot.length, maxRows)\n }\n\n // `join`-layer dressing (#650 Task 6, #626 retirement). When the query\n // carries a locale (per-call or the owning collection's default) and the\n // right side declares a `presentForJoin` hook, resolve each matched right\n // record through it before it's attached. Locale-less → leave raw.\n const effLocale = locale ?? context.defaultLocale\n const presentResolve: ((right: unknown) => unknown) | undefined =\n effLocale !== undefined && source.presentForJoin !== undefined\n ? (right) =>\n right !== null && typeof right === 'object'\n ? source.presentForJoin!(right, effLocale)\n : right\n : undefined\n\n // Strategy selection: explicit override wins; otherwise prefer\n // nested-loop when the source exposes lookupById (O(1) per row),\n // falling back to hash join when it doesn't.\n const strategy: JoinStrategy =\n leg.strategy ?? (source.lookupById ? 'nested' : 'hash')\n\n if (strategy === 'nested' && source.lookupById) {\n // Bind through an arrow so the `this` context of lookupById\n // doesn't drift — same pattern as the existing candidateRecords\n // helper in builder.ts.\n const lookup = (id: string): unknown => source.lookupById?.(id)\n return nestedLoopJoin(leftRows, leg, lookup, presentResolve)\n }\n return hashJoin(leftRows, leg, rightSnapshot, presentResolve)\n}\n\nfunction nestedLoopJoin(\n leftRows: readonly unknown[],\n leg: JoinLeg,\n lookupById: (id: string) => unknown,\n presentResolve?: (right: unknown) => unknown,\n): unknown[] {\n const out: unknown[] = []\n for (const left of leftRows) {\n const rawId = readPath(left, leg.field)\n const key = coerceRefKey(rawId)\n let right = key === null ? undefined : lookupById(key)\n if (presentResolve && right !== undefined) right = presentResolve(right)\n out.push(attachJoin(left, leg, right, rawId))\n }\n return out\n}\n\nfunction hashJoin(\n leftRows: readonly unknown[],\n leg: JoinLeg,\n rightSnapshot: readonly unknown[],\n presentResolve?: (right: unknown) => unknown,\n): unknown[] {\n // Build the right-side hash once per query execution. We key on\n // the `id` field because ref() always points to a target's primary\n // key — non-equi and non-id joins are out of scope for.\n const rightMap = new Map<string, unknown>()\n for (const record of rightSnapshot) {\n const rawId = readPath(record, 'id')\n const key = coerceRefKey(rawId)\n if (key !== null) {\n rightMap.set(key, record)\n }\n }\n const out: unknown[] = []\n for (const left of leftRows) {\n const rawId = readPath(left, leg.field)\n const key = coerceRefKey(rawId)\n let right = key === null ? undefined : rightMap.get(key)\n if (presentResolve && right !== undefined) right = presentResolve(right)\n out.push(attachJoin(left, leg, right, rawId))\n }\n return out\n}\n\n/**\n * Attach the resolved right-side record (or null) to the left row\n * under the alias, applying ref-mode semantics for the dangling\n * case.\n *\n * A left-side record whose FK field is null/undefined is NOT a\n * dangling ref — it's \"no reference at all\", which is always\n * allowed regardless of mode. This matches the write-time\n * `enforceRefsOnPut` behavior: \"Nullish ref values are allowed —\n * treat them as 'no reference'.\"\n *\n * Only non-null FKs pointing at non-existent targets trigger the\n * mode behavior.\n */\nfunction attachJoin(\n left: unknown,\n leg: JoinLeg,\n right: unknown,\n rawId: unknown,\n): unknown {\n if (left === null || typeof left !== 'object') {\n // Pathological input — return as-is. Shouldn't happen in\n // practice because QuerySource yields objects, but defensive\n // because plan execution is untyped at this layer.\n return left\n }\n const merged: Record<string, unknown> = { ...(left as Record<string, unknown>) }\n\n // \"No ref at all\" — null/undefined FK value, or a non-string/non-\n // number FK that coerceRefKey treated as no-ref. Never throws\n // regardless of mode; matches the write-time policy that nullish\n // refs are allowed.\n const refKey = coerceRefKey(rawId)\n if (right === undefined) {\n if (refKey !== null && leg.mode === 'strict') {\n throw new DanglingReferenceError({\n field: leg.field,\n target: leg.target,\n refId: refKey,\n message:\n `.join() strict dangling: record references \"${leg.target}:${refKey}\" ` +\n `via field \"${leg.field}\", but no such record exists. Use ref() mode 'warn' ` +\n `or 'cascade' if dangling refs are acceptable, or run ` +\n `vault.checkIntegrity() to find and fix the orphans.`,\n })\n }\n if (refKey !== null && leg.mode === 'warn') {\n warnOnceDangling(leg.field, leg.target, refKey)\n }\n // For 'cascade' and null refs we attach null silently. Cascade\n // is a delete-time mode; any dangling refs visible at read time\n // are either mid-flight or pre-existing orphans, not a DSL error.\n merged[leg.as] = null\n } else {\n merged[leg.as] = right\n }\n return merged\n}\n\n/**\n * Test-only: reset the join warning deduplication state between\n * tests. Production code never calls this — the dedup state is\n * intentionally process-scoped so a noisy query doesn't spam the\n * console once per component render.\n */\nexport function resetJoinWarnings(): void {\n warnedDanglingKeys.clear()\n warnedCeilingKeys.clear()\n}\n"],"mappings":";;;;;;;;;AAuDO,IAAM,wBAAwB;AAQrC,IAAM,qBAAqB;AAuI3B,SAAS,aAAa,OAA+B;AACnD,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAC/E,SAAO;AACT;AAOA,IAAM,qBAAqB,oBAAI,IAAY;AAC3C,SAAS,iBAAiB,OAAe,QAAgB,OAAqB;AAC5E,QAAM,MAAM,GAAG,KAAK,SAAI,MAAM,IAAI,KAAK;AACvC,MAAI,mBAAmB,IAAI,GAAG,EAAG;AACjC,qBAAmB,IAAI,GAAG;AAC1B,UAAQ;AAAA,IACN,oEACY,KAAK,aAAQ,MAAM,IAAI,KAAK;AAAA,EAC1C;AACF;AAOA,IAAM,oBAAoB,oBAAI,IAAY;AAC1C,SAAS,uBACP,QACA,MACA,MACA,SACM;AACN,QAAM,MAAM,GAAG,MAAM,IAAI,IAAI;AAC7B,MAAI,kBAAkB,IAAI,GAAG,EAAG;AAChC,oBAAkB,IAAI,GAAG;AACzB,QAAM,MAAM,KAAK,MAAO,OAAO,UAAW,GAAG;AAC7C,UAAQ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AAW,QAAQ,IAAI,SAAS,QAAQ;AAC1C,uBAAiB,IAAI,OAAO,IAAI,QAAQ,MAAM;AAAA,IAChD;AAIA,WAAO,IAAI,EAAE,IAAI;AAAA,EACnB,OAAO;AACL,WAAO,IAAI,EAAE,IAAI;AAAA,EACnB;AACA,SAAO;AACT;AAQO,SAAS,oBAA0B;AACxC,qBAAmB,MAAM;AACzB,oBAAkB,MAAM;AAC1B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-audit/portability/export-accessible.ts"],"sourcesContent":["/**\n * `exportMyAccessibleData`: a non-owner user exports the scope they\n * can decrypt as a portable, re-keyed `.noydb` bundle. Non-destructive and\n * **always allowed** (the \"data sovereignty by construction\" property of\n * sealing-at-dimension — the firm cannot deny it) but **audited**.\n *\n * Reuses the existing bundle machinery: the access boundary is the caller's DEK\n * set (operator/client → `keyring.permissions`; owner/admin/viewer → all), so a\n * record outside the caller's keys can never enter the bundle. Re-keying to a\n * new owner reuses `writePod`'s `exportSecret` shorthand.\n */\nimport type { Vault } from '../../kernel/vault.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport { writePod } from '../../with-pod/bundle.js'\n\n/**\n * Resolve the collections a caller may export/withdraw: operator/client are\n * scoped to their granted collections; owner/admin/viewer see everything\n * (`undefined` = no allowlist). A `scope.collections` sub-scope intersects the\n * granted set. `writableOnly` keeps only `rw` grants (for destructive ops).\n */\nexport function resolveAccessibleCollections(\n keyring: UnlockedKeyring,\n scope: { collections?: readonly string[] } | undefined,\n writableOnly = false,\n): string[] | undefined {\n let collections: string[] | undefined\n if (keyring.role === 'operator' || keyring.role === 'client') {\n collections = Object.entries(keyring.permissions)\n .filter(([, mode]) => !writableOnly || mode === 'rw')\n .map(([c]) => c)\n }\n if (scope?.collections) {\n const allow = new Set(scope.collections)\n collections = (collections ?? [...scope.collections]).filter((c) => allow.has(c))\n }\n return collections\n}\n\n/** Produce a (optionally re-keyed, scoped) `.noydb` bundle — no audit. */\nexport async function buildAccessibleBundle(\n vault: Vault,\n collections: string[] | undefined,\n reKey: { secret: string } | undefined,\n compression: 'auto' | 'brotli' | 'gzip' | 'none' = 'auto',\n): Promise<Uint8Array> {\n return writePod(vault, {\n compression,\n ...(collections !== undefined ? { collections } : {}),\n ...(reKey ? { exportSecret: reKey.secret } : {}),\n })\n}\n\nexport interface ExportAccessibleOptions {\n /**\n * Re-key the bundle so it is independently openable by a new owner with this\n * secret (the receiving firm / the client themselves). Omit to inherit\n * the source keyring (personal backup).\n */\n readonly reKey?: { readonly secret: string }\n /** Narrow the export to a subset of the caller's accessible collections. */\n readonly scope?: { readonly collections?: readonly string[] }\n readonly compression?: 'auto' | 'brotli' | 'gzip' | 'none'\n}\n\n/**\n * Produce a re-keyed, access-scoped `.noydb` bundle of the caller's accessible\n * data. Appends a tamper-evident audit entry (`reason: 'user-export:<userId>'`).\n */\nexport async function exportAccessibleData(\n vault: Vault,\n opts: ExportAccessibleOptions = {},\n): Promise<Uint8Array> {\n const { keyring } = vault._introspectState()\n const collections = resolveAccessibleCollections(keyring, opts.scope)\n const bytes = await buildAccessibleBundle(vault, collections, opts.reKey, opts.compression ?? 'auto')\n\n // §11.11 audit — non-destructive, always-allowed export. No-op when the vault\n // has no history/ledger strategy (avoids minting a phantom _ledger DEK).\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle',\n collection: '',\n id: '',\n version: 0,\n actor: keyring.userId,\n payloadHash: '',\n reason: `user-export:${keyring.userId}`,\n })\n\n return bytes\n}\n"],"mappings":";;;;;AAqBO,SAAS,6BACd,SACA,OACA,eAAe,OACO;AACtB,MAAI;AACJ,MAAI,QAAQ,SAAS,cAAc,QAAQ,SAAS,UAAU;AAC5D,kBAAc,OAAO,QAAQ,QAAQ,WAAW,EAC7C,OAAO,CAAC,CAAC,EAAE,IAAI,MAAM,CAAC,gBAAgB,SAAS,IAAI,EACnD,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;AAAA,EACnB;AACA,MAAI,OAAO,aAAa;AACtB,UAAM,QAAQ,IAAI,IAAI,MAAM,WAAW;AACvC,mBAAe,eAAe,CAAC,GAAG,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EAClF;AACA,SAAO;AACT;AAGA,eAAsB,sBACpB,OACA,aACA,OACA,cAAmD,QAC9B;AACrB,SAAO,SAAS,OAAO;AAAA,IACrB;AAAA,IACA,GAAI,gBAAgB,SAAY,EAAE,YAAY,IAAI,CAAC;AAAA,IACnD,GAAI,QAAQ,EAAE,cAAc,MAAM,OAAO,IAAI,CAAC;AAAA,EAChD,CAAC;AACH;AAkBA,eAAsB,qBACpB,OACA,OAAgC,CAAC,GACZ;AACrB,QAAM,EAAE,QAAQ,IAAI,MAAM,iBAAiB;AAC3C,QAAM,cAAc,6BAA6B,SAAS,KAAK,KAAK;AACpE,QAAM,QAAQ,MAAM,sBAAsB,OAAO,aAAa,KAAK,OAAO,KAAK,eAAe,MAAM;AAIpG,QAAM,MAAM,iBAAiB,GAAG,OAAO;AAAA,IACrC,IAAI;AAAA,IACJ,YAAY;AAAA,IACZ,IAAI;AAAA,IACJ,SAAS;AAAA,IACT,OAAO,QAAQ;AAAA,IACf,aAAa;AAAA,IACb,QAAQ,eAAe,QAAQ,MAAM;AAAA,EACvC,CAAC;AAED,SAAO;AACT;","names":[]}