sandforge 1.83.0 → 1.84.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 (254) hide show
  1. package/README.md +1 -1
  2. package/lib/chunk-23SEDORH.mjs +11 -0
  3. package/lib/{chunk-I5C4O3VA.mjs → chunk-24RFOFYT.mjs} +1 -1
  4. package/lib/chunk-26POJDIT.mjs +7 -0
  5. package/lib/{chunk-WJAZ5LHL.mjs → chunk-2AZQHBEF.mjs} +1 -1
  6. package/lib/{chunk-IHGYJZZ2.mjs → chunk-2HVOZUM4.mjs} +1 -1
  7. package/lib/{chunk-3V4YH5KO.mjs → chunk-2JDAOWUW.mjs} +1 -1
  8. package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
  9. package/lib/chunk-2WFIVO4F.mjs +13 -0
  10. package/lib/chunk-2YHZBUZE.mjs +7 -0
  11. package/lib/{chunk-7DPHZWA4.mjs → chunk-326AJTIU.mjs} +14 -14
  12. package/lib/{chunk-UIR77ZJD.mjs → chunk-36JOHEJL.mjs} +1 -1
  13. package/lib/chunk-3PVRGTVK.mjs +7 -0
  14. package/lib/{chunk-2WMKJVD2.mjs → chunk-3Q353S2R.mjs} +1 -1
  15. package/lib/chunk-3TZSBHEY.mjs +7 -0
  16. package/lib/{chunk-T36DZJPH.mjs → chunk-43TOMFV4.mjs} +1 -1
  17. package/lib/{chunk-XAMMIPZ4.mjs → chunk-4CVUUVGJ.mjs} +1 -1
  18. package/lib/{chunk-6YC2ELCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
  19. package/lib/{chunk-ZB5E7NHU.mjs → chunk-4JE4BYXK.mjs} +1 -1
  20. package/lib/{chunk-JREKJO3D.mjs → chunk-54WZUS7J.mjs} +1 -1
  21. package/lib/{chunk-CGZGL6VT.mjs → chunk-5CRLRHOJ.mjs} +1 -1
  22. package/lib/{chunk-UOHZW2L4.mjs → chunk-5IZTFMJM.mjs} +1 -1
  23. package/lib/{chunk-6VOQFISN.mjs → chunk-5M5FQ7RP.mjs} +1 -1
  24. package/lib/{chunk-U4YFYSF3.mjs → chunk-5SMWFNE7.mjs} +1 -1
  25. package/lib/{chunk-HQZUQXDC.mjs → chunk-5XTUSN72.mjs} +1 -1
  26. package/lib/chunk-6I6TWNV5.mjs +7 -0
  27. package/lib/{chunk-QLRWU3MB.mjs → chunk-6JWWSDM6.mjs} +1 -1
  28. package/lib/chunk-6O222PW6.mjs +7 -0
  29. package/lib/{chunk-J3TIHLWG.mjs → chunk-6PD6K7LP.mjs} +1 -1
  30. package/lib/{chunk-ISAUCWYK.mjs → chunk-6QE6R6RL.mjs} +1 -1
  31. package/lib/{chunk-2KTGDYUH.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
  32. package/lib/{chunk-XAUQXYPW.mjs → chunk-6YL7BNYD.mjs} +1 -1
  33. package/lib/chunk-6ZLKIT3H.mjs +7 -0
  34. package/lib/{chunk-XKFHTBAB.mjs → chunk-7QYHEHMA.mjs} +1 -1
  35. package/lib/chunk-7SQSWVAU.mjs +9 -0
  36. package/lib/{chunk-NNV7IGM7.mjs → chunk-7UVKIWKV.mjs} +1 -1
  37. package/lib/{chunk-RZKJQOOC.mjs → chunk-7WATA4SB.mjs} +1 -1
  38. package/lib/{chunk-DMT5SCO3.mjs → chunk-7YNM6KFZ.mjs} +1 -1
  39. package/lib/{chunk-TMIESDE5.mjs → chunk-A3MYSOOC.mjs} +1 -1
  40. package/lib/chunk-AL4C3GFT.mjs +7 -0
  41. package/lib/chunk-B3FBHVNN.mjs +21 -0
  42. package/lib/{chunk-CDWZGQAJ.mjs → chunk-B63POIPQ.mjs} +1 -1
  43. package/lib/{chunk-YEVB7LVK.mjs → chunk-BAWCOKRW.mjs} +1 -1
  44. package/lib/{chunk-FVLFO2S6.mjs → chunk-BBRWFKS5.mjs} +1 -1
  45. package/lib/chunk-BEA27DLS.mjs +7 -0
  46. package/lib/chunk-BRY3PLIZ.mjs +7 -0
  47. package/lib/chunk-CBH3TOWK.mjs +341 -0
  48. package/lib/{chunk-7V2UYZ6S.mjs → chunk-CPQIZGG5.mjs} +1 -1
  49. package/lib/chunk-CVHNXJH3.mjs +7 -0
  50. package/lib/{chunk-ZOSESZ22.mjs → chunk-D4GF4FAB.mjs} +1 -1
  51. package/lib/chunk-DGDRQRCW.mjs +7 -0
  52. package/lib/{chunk-2N73W63D.mjs → chunk-DPMRIMUC.mjs} +1 -1
  53. package/lib/chunk-DUN2EPRC.mjs +7 -0
  54. package/lib/chunk-E3A3LOCY.mjs +7 -0
  55. package/lib/{chunk-KWAVSZ2B.mjs → chunk-EAC5QCE3.mjs} +1 -1
  56. package/lib/{chunk-JUOQUG7U.mjs → chunk-EC72TIEG.mjs} +1 -1
  57. package/lib/chunk-EPFCERGL.mjs +7 -0
  58. package/lib/{chunk-6KOUYHEY.mjs → chunk-ETDCBLGU.mjs} +1 -1
  59. package/lib/{chunk-2R6GFNKF.mjs → chunk-F3AQW6IU.mjs} +1 -1
  60. package/lib/{chunk-AHUGG3WU.mjs → chunk-FITPY3L4.mjs} +1 -1
  61. package/lib/chunk-FNJ4SGWO.mjs +7 -0
  62. package/lib/{chunk-EOQON3E5.mjs → chunk-FP7CYB2F.mjs} +1 -1
  63. package/lib/{chunk-262TP6UU.mjs → chunk-GKY2JMHY.mjs} +1 -1
  64. package/lib/{chunk-JBWJ6UEZ.mjs → chunk-GMIGWR6U.mjs} +1 -1
  65. package/lib/{chunk-OS5GE52G.mjs → chunk-GNRSF65U.mjs} +1 -1
  66. package/lib/chunk-GOOVPVWX.mjs +7 -0
  67. package/lib/{chunk-DB5RVDC5.mjs → chunk-GWZRR3MM.mjs} +1 -1
  68. package/lib/{chunk-SX6QWYCQ.mjs → chunk-H2BHESDA.mjs} +2 -2
  69. package/lib/chunk-H4CGM6YO.mjs +7 -0
  70. package/lib/{chunk-NFEBX75O.mjs → chunk-HCGXK7G7.mjs} +1 -1
  71. package/lib/{chunk-4X5D3MSV.mjs → chunk-HIDW7FNV.mjs} +1 -1
  72. package/lib/chunk-HSBXRQTI.mjs +7 -0
  73. package/lib/chunk-HUZPBE47.mjs +7 -0
  74. package/lib/{chunk-F5SBGJWW.mjs → chunk-HV7VPEXP.mjs} +1 -1
  75. package/lib/chunk-I6E6T6YY.mjs +7 -0
  76. package/lib/chunk-IUM4NFKI.mjs +10 -0
  77. package/lib/chunk-IVFVNNGB.mjs +37 -0
  78. package/lib/{chunk-L4MSL4U7.mjs → chunk-IZGCEOYO.mjs} +1 -1
  79. package/lib/{chunk-E3RQ575Y.mjs → chunk-J3DND3BC.mjs} +1 -1
  80. package/lib/{chunk-MJD6CPZZ.mjs → chunk-JAEDM4SI.mjs} +1 -1
  81. package/lib/chunk-JCFBFF4Y.mjs +7 -0
  82. package/lib/{chunk-U2CTKIPE.mjs → chunk-JE6SCT6R.mjs} +1 -1
  83. package/lib/{chunk-XJICAOAQ.mjs → chunk-JGZPD4IM.mjs} +1 -1
  84. package/lib/{chunk-XCJUNX63.mjs → chunk-JKJ74BX5.mjs} +1 -1
  85. package/lib/{chunk-WAYQLQAD.mjs → chunk-JLSIWO4Z.mjs} +1 -1
  86. package/lib/{chunk-D7XUNWWU.mjs → chunk-JSAJS3MY.mjs} +1 -1
  87. package/lib/chunk-JTJK2D36.mjs +7 -0
  88. package/lib/{chunk-OTJH6AEA.mjs → chunk-KAZS5Z6W.mjs} +1 -1
  89. package/lib/chunk-KB4ZHM4Q.mjs +10 -0
  90. package/lib/{chunk-N2HYG3BL.mjs → chunk-KGU4SVIT.mjs} +1 -1
  91. package/lib/{chunk-FKCIGJOI.mjs → chunk-KJWFYBMU.mjs} +2 -2
  92. package/lib/{chunk-KXUOHACP.mjs → chunk-KZTZDC7H.mjs} +1 -1
  93. package/lib/{chunk-S4PRKKGC.mjs → chunk-L2E5WBGD.mjs} +1 -1
  94. package/lib/{chunk-X2XZQ434.mjs → chunk-L53JWJ3S.mjs} +1 -1
  95. package/lib/{chunk-CQAFVEKP.mjs → chunk-LA4KIATH.mjs} +6 -6
  96. package/lib/chunk-LC3NDW4N.mjs +7 -0
  97. package/lib/{chunk-4V3QO7HF.mjs → chunk-LKTNQEBS.mjs} +1 -1
  98. package/lib/chunk-M2ABR4JM.mjs +7 -0
  99. package/lib/{chunk-3CM7LAPE.mjs → chunk-M4BLK6HJ.mjs} +1 -1
  100. package/lib/{chunk-Z3MGN42K.mjs → chunk-M6K34KGF.mjs} +1 -1
  101. package/lib/{chunk-TUPZY2QJ.mjs → chunk-MDMPJEV3.mjs} +1 -1
  102. package/lib/{chunk-BVZ5H3N4.mjs → chunk-MJZU3U5O.mjs} +68 -63
  103. package/lib/{chunk-OUU47Y7A.mjs → chunk-MSIEU5MR.mjs} +1 -1
  104. package/lib/{chunk-QQDZQCO2.mjs → chunk-N4WPCWJO.mjs} +1 -1
  105. package/lib/{chunk-MTM4KG3T.mjs → chunk-NCZKWSC7.mjs} +1 -1
  106. package/lib/{chunk-Y7YUNRKK.mjs → chunk-NED4MBIM.mjs} +1 -1
  107. package/lib/{chunk-QKJXIY6L.mjs → chunk-NOBQTEQD.mjs} +1 -1
  108. package/lib/{chunk-WBELLGNE.mjs → chunk-NSQWI7ZY.mjs} +1 -1
  109. package/lib/{chunk-BPHTA6KP.mjs → chunk-O677VOGO.mjs} +1 -1
  110. package/lib/chunk-OFTT7J2M.mjs +7 -0
  111. package/lib/{chunk-JH4ZTVQN.mjs → chunk-OLCVHL7I.mjs} +1 -1
  112. package/lib/chunk-OM5NORJG.mjs +7 -0
  113. package/lib/{chunk-QP3JLFIO.mjs → chunk-OMNMLKDT.mjs} +1 -1
  114. package/lib/{chunk-WABXKL4N.mjs → chunk-OPMO6I45.mjs} +1 -1
  115. package/lib/{chunk-7ZBDACVG.mjs → chunk-OUZQPYT3.mjs} +1 -1
  116. package/lib/chunk-OVNMB6Q2.mjs +7 -0
  117. package/lib/{chunk-DKDKCGXV.mjs → chunk-PAXNWTYK.mjs} +1 -1
  118. package/lib/{chunk-GLN4PI5P.mjs → chunk-PBY2O6OF.mjs} +1 -1
  119. package/lib/chunk-PEDQPM2P.mjs +926 -0
  120. package/lib/chunk-PH7SP4YK.mjs +21 -0
  121. package/lib/{chunk-BT43WSOS.mjs → chunk-PMN4PAC3.mjs} +1 -1
  122. package/lib/chunk-PMWAFDUB.mjs +48 -0
  123. package/lib/chunk-PPLVFX6N.mjs +7 -0
  124. package/lib/{chunk-L3I6DAHX.mjs → chunk-PR3XCSPO.mjs} +1 -1
  125. package/lib/{chunk-WZN36ACK.mjs → chunk-PR42EZSR.mjs} +1 -1
  126. package/lib/{chunk-NDFFIJL5.mjs → chunk-PWRJRL5U.mjs} +1 -1
  127. package/lib/{chunk-NS6ONPWL.mjs → chunk-Q7GIJBCD.mjs} +1 -1
  128. package/lib/chunk-Q7TLC3I2.mjs +7 -0
  129. package/lib/{chunk-ALBY5SOH.mjs → chunk-QAFPQ3YB.mjs} +1 -1
  130. package/lib/{chunk-KKS2KFBT.mjs → chunk-QKEKG2LD.mjs} +1 -1
  131. package/lib/{chunk-OOIDCHBQ.mjs → chunk-QO53K5W2.mjs} +2 -2
  132. package/lib/{chunk-HVX2AFYW.mjs → chunk-QTG6LUZT.mjs} +1 -1
  133. package/lib/{chunk-K7G3W7XH.mjs → chunk-RE7RYF3B.mjs} +1 -1
  134. package/lib/{chunk-JIPT5FUD.mjs → chunk-RGBGUCJA.mjs} +1 -1
  135. package/lib/{chunk-GT5ZKU6V.mjs → chunk-RGUQOSBU.mjs} +1 -1
  136. package/lib/{chunk-VXZ5PTOM.mjs → chunk-RHNTHGNU.mjs} +1 -1
  137. package/lib/chunk-RKTFFCNS.mjs +7 -0
  138. package/lib/chunk-RMFU4BAL.mjs +28 -0
  139. package/lib/{chunk-DNQKVCUV.mjs → chunk-ROV3QXEF.mjs} +11 -11
  140. package/lib/chunk-RT47RKLY.mjs +7 -0
  141. package/lib/{chunk-ISOSTAJR.mjs → chunk-S42RBRH2.mjs} +1 -1
  142. package/lib/{chunk-27BBEGUD.mjs → chunk-SI267LYR.mjs} +1 -1
  143. package/lib/chunk-T3G6VZNS.mjs +7 -0
  144. package/lib/chunk-TNT27RBG.mjs +7 -0
  145. package/lib/chunk-UBIKR5VO.mjs +7 -0
  146. package/lib/chunk-UI3JQVRU.mjs +8 -0
  147. package/lib/{chunk-RVCPQVKM.mjs → chunk-UIOMAX56.mjs} +1 -1
  148. package/lib/chunk-UX3BVH2Y.mjs +7 -0
  149. package/lib/{chunk-L4RJX7DG.mjs → chunk-VCUXCK36.mjs} +1 -1
  150. package/lib/chunk-VINGECAJ.mjs +10 -0
  151. package/lib/chunk-VOXJHJIE.mjs +7 -0
  152. package/lib/chunk-W6PN6TJG.mjs +7 -0
  153. package/lib/{chunk-D6JT4PAB.mjs → chunk-WAPSSYMT.mjs} +1 -1
  154. package/lib/{chunk-7BQMBXKX.mjs → chunk-WUUKFE2U.mjs} +1 -1
  155. package/lib/chunk-WWTCWWZI.mjs +7 -0
  156. package/lib/chunk-WXDLQT2O.mjs +10 -0
  157. package/lib/{chunk-TCEXCHXR.mjs → chunk-WY5V5PR3.mjs} +1 -1
  158. package/lib/chunk-X4BXESMQ.mjs +7 -0
  159. package/lib/chunk-XBQGZGWR.mjs +7 -0
  160. package/lib/{chunk-AXFD2OH6.mjs → chunk-XGGOUNPP.mjs} +1 -1
  161. package/lib/chunk-XKWW3GKF.mjs +7 -0
  162. package/lib/{chunk-PDRXM5WN.mjs → chunk-Y2DRK37K.mjs} +1 -1
  163. package/lib/{chunk-ZXOUWHYE.mjs → chunk-YA6ATMTB.mjs} +1 -1
  164. package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
  165. package/lib/chunk-YHR4WQPR.mjs +7 -0
  166. package/lib/{chunk-LWES2KZE.mjs → chunk-YTLUYSMF.mjs} +1 -1
  167. package/lib/{chunk-2K5BYZQM.mjs → chunk-YWEQQL3C.mjs} +1 -1
  168. package/lib/{chunk-C6RKM4BB.mjs → chunk-Z4LKKOFY.mjs} +1 -1
  169. package/lib/chunk-ZBAWJUG2.mjs +7 -0
  170. package/lib/{chunk-446GBKAC.mjs → chunk-ZJW6YOMV.mjs} +1 -1
  171. package/lib/chunk-ZQQXSCVI.mjs +7 -0
  172. package/lib/{chunk-L6CLN664.mjs → chunk-ZQWIVYVM.mjs} +1 -1
  173. package/lib/{chunk-CXKZ6TYV.mjs → chunk-ZV7ZFQQC.mjs} +1 -1
  174. package/lib/sandforge-autopilot.mjs +25 -25
  175. package/lib/sandforge-backup.mjs +1 -1
  176. package/lib/sandforge-checkpoint.mjs +1 -1
  177. package/lib/sandforge-cleanup.mjs +1 -1
  178. package/lib/sandforge-clone.mjs +1 -1
  179. package/lib/sandforge-compare.mjs +52 -21
  180. package/lib/sandforge-dataops.mjs +1 -1
  181. package/lib/sandforge-empty.mjs +1 -1
  182. package/lib/sandforge-env.mjs +95 -95
  183. package/lib/sandforge-frozen.mjs +1 -1
  184. package/lib/sandforge-mcp.mjs +12 -12
  185. package/lib/sandforge-monitor.mjs +1 -1
  186. package/lib/sandforge-pipeline.mjs +1 -1
  187. package/lib/sandforge-seed.mjs +1 -1
  188. package/lib/sandforge-sync.mjs +1 -1
  189. package/lib/sandforge-users.mjs +1 -1
  190. package/lib/sandforge.mjs +1 -1
  191. package/lib/sf/sandforge/compare.mjs +2 -2
  192. package/lib/sfPlugin.mjs +1 -1
  193. package/oclif.manifest.json +1 -1
  194. package/package.json +1 -1
  195. package/lib/chunk-2ADSD5WK.mjs +0 -7
  196. package/lib/chunk-2GSMHGIV.mjs +0 -7
  197. package/lib/chunk-36Y225OM.mjs +0 -7
  198. package/lib/chunk-3OVTKRS4.mjs +0 -7
  199. package/lib/chunk-4GCYGQXD.mjs +0 -7
  200. package/lib/chunk-4JKR4PTZ.mjs +0 -8
  201. package/lib/chunk-5OGNK3JP.mjs +0 -37
  202. package/lib/chunk-6QSHWIZI.mjs +0 -48
  203. package/lib/chunk-77IVKH7R.mjs +0 -7
  204. package/lib/chunk-77MZRBWX.mjs +0 -7
  205. package/lib/chunk-7WSQ65WG.mjs +0 -9
  206. package/lib/chunk-A32ISQ6M.mjs +0 -28
  207. package/lib/chunk-AG24QMSY.mjs +0 -7
  208. package/lib/chunk-BH76USTQ.mjs +0 -11
  209. package/lib/chunk-BZ24IAP5.mjs +0 -7
  210. package/lib/chunk-CN5HGFG4.mjs +0 -7
  211. package/lib/chunk-CTPLYUXA.mjs +0 -7
  212. package/lib/chunk-DIGUC7S4.mjs +0 -341
  213. package/lib/chunk-DSR2MSBH.mjs +0 -7
  214. package/lib/chunk-ETNQHIDI.mjs +0 -9
  215. package/lib/chunk-FBXH4VRQ.mjs +0 -7
  216. package/lib/chunk-FYWNSMOZ.mjs +0 -10
  217. package/lib/chunk-GEEWPTV5.mjs +0 -7
  218. package/lib/chunk-GTRU5AV5.mjs +0 -7
  219. package/lib/chunk-I3ZO76LL.mjs +0 -21
  220. package/lib/chunk-ISA2NYJV.mjs +0 -7
  221. package/lib/chunk-IXIY6Q4M.mjs +0 -7
  222. package/lib/chunk-JAV6F6OA.mjs +0 -7
  223. package/lib/chunk-JYUMD357.mjs +0 -7
  224. package/lib/chunk-L47JCNP3.mjs +0 -7
  225. package/lib/chunk-LI2XNV7F.mjs +0 -7
  226. package/lib/chunk-LP2D3JJP.mjs +0 -7
  227. package/lib/chunk-LYOGCIYD.mjs +0 -925
  228. package/lib/chunk-N5UIE4IR.mjs +0 -7
  229. package/lib/chunk-O7GCCRPW.mjs +0 -7
  230. package/lib/chunk-OO24ZYYJ.mjs +0 -7
  231. package/lib/chunk-OS6HFJ7L.mjs +0 -7
  232. package/lib/chunk-P6WRYJN3.mjs +0 -7
  233. package/lib/chunk-PGRY365W.mjs +0 -7
  234. package/lib/chunk-PPGDAUEQ.mjs +0 -7
  235. package/lib/chunk-Q4PPI3KG.mjs +0 -7
  236. package/lib/chunk-QFTF2PGS.mjs +0 -21
  237. package/lib/chunk-QO4MPHZD.mjs +0 -7
  238. package/lib/chunk-QXB6U3ZP.mjs +0 -7
  239. package/lib/chunk-R3OM3X4L.mjs +0 -8
  240. package/lib/chunk-R7GKMAT4.mjs +0 -7
  241. package/lib/chunk-SCKUIE3R.mjs +0 -7
  242. package/lib/chunk-SU65Z2BA.mjs +0 -7
  243. package/lib/chunk-T7DDS4UQ.mjs +0 -7
  244. package/lib/chunk-TQJ5NPRC.mjs +0 -7
  245. package/lib/chunk-VZLJZEV2.mjs +0 -7
  246. package/lib/chunk-W3BQGMTR.mjs +0 -7
  247. package/lib/chunk-WXU6ZJIV.mjs +0 -7
  248. package/lib/chunk-X4HZD5U2.mjs +0 -7
  249. package/lib/chunk-X6XNTOGO.mjs +0 -7
  250. package/lib/chunk-XMQ5R6TC.mjs +0 -10
  251. package/lib/chunk-XPXEQKLR.mjs +0 -7
  252. package/lib/chunk-YBZIDW6W.mjs +0 -7
  253. package/lib/chunk-ZCOSME6P.mjs +0 -7
  254. package/lib/chunk-ZTHC42X6.mjs +0 -7
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{c as u}from"./chunk-27BBEGUD.mjs";import{Ka as d,cc as f}from"./chunk-6QSHWIZI.mjs";import{mkdir as h,readdir as g,readFile as m,rename as w,writeFile as S}from"node:fs/promises";import*as c from"node:path";var k=".sandforge-scenario.json",P={depth:3,files:50},y=new Set(["node_modules","dist","out","coverage"]),E=10;function O(){return{list:async r=>{try{return(await g(r,{withFileTypes:!0})).map(e=>({name:e.name,folder:e.isDirectory()}))}catch(t){let e=t.code;if(e==="ENOENT"||e==="ENOTDIR"||e==="EACCES")return[];throw t}},readFile:r=>m(r,"utf8"),writeNew:async(r,t)=>{await h(c.dirname(r),{recursive:!0});try{return await S(r,t,{encoding:"utf8",flag:"wx"}),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}},replace:async(r,t)=>{let e=`${r}.${process.pid}.tmp`;await S(e,t,"utf8"),await w(e,r)}}}function x(r){let t;try{t=JSON.parse(r)}catch{return{issues:["The file is not JSON"]}}let e=d.safeParse(t);return e.success?{pack:e.data}:{issues:e.error.issues.slice(0,E).map(n=>`${n.path.join(".")||"the file"}: ${n.message}`)}}async function F(r,t){let e=[],n=async(a,o,i)=>{let p=[...await r.list(o)].sort((s,l)=>s.name.localeCompare(l.name));for(let s of p){if(e.length>=P.files)return;let l=c.join(o,s.name);s.folder?i<P.depth&&!v(s.name)&&await n(a,l,i+1):s.name.endsWith(k)&&e.push({path:l,relativePath:c.relative(a,l).split(c.sep).join("/")})}};for(let a of t)await n(a,a,0);return e}function v(r){return r.startsWith(".")||y.has(r)}async function N(r,t){let e=f.map(n=>({source:"built-in",pack:n}));for(let n of await F(r,t)){let a;try{a=await r.readFile(n.path)}catch{e.push({source:"workspace",...n,issues:["The file could not be read"]});continue}let o=x(a);e.push({source:"workspace",...n,...o})}return e}function A(r){return`${JSON.stringify(r,null,2)}
7
+ import{c as u}from"./chunk-SI267LYR.mjs";import{Ka as d,cc as f}from"./chunk-PMWAFDUB.mjs";import{mkdir as h,readdir as g,readFile as m,rename as w,writeFile as S}from"node:fs/promises";import*as c from"node:path";var k=".sandforge-scenario.json",P={depth:3,files:50},y=new Set(["node_modules","dist","out","coverage"]),E=10;function O(){return{list:async r=>{try{return(await g(r,{withFileTypes:!0})).map(e=>({name:e.name,folder:e.isDirectory()}))}catch(t){let e=t.code;if(e==="ENOENT"||e==="ENOTDIR"||e==="EACCES")return[];throw t}},readFile:r=>m(r,"utf8"),writeNew:async(r,t)=>{await h(c.dirname(r),{recursive:!0});try{return await S(r,t,{encoding:"utf8",flag:"wx"}),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}},replace:async(r,t)=>{let e=`${r}.${process.pid}.tmp`;await S(e,t,"utf8"),await w(e,r)}}}function x(r){let t;try{t=JSON.parse(r)}catch{return{issues:["The file is not JSON"]}}let e=d.safeParse(t);return e.success?{pack:e.data}:{issues:e.error.issues.slice(0,E).map(n=>`${n.path.join(".")||"the file"}: ${n.message}`)}}async function F(r,t){let e=[],n=async(a,o,i)=>{let p=[...await r.list(o)].sort((s,l)=>s.name.localeCompare(l.name));for(let s of p){if(e.length>=P.files)return;let l=c.join(o,s.name);s.folder?i<P.depth&&!v(s.name)&&await n(a,l,i+1):s.name.endsWith(k)&&e.push({path:l,relativePath:c.relative(a,l).split(c.sep).join("/")})}};for(let a of t)await n(a,a,0);return e}function v(r){return r.startsWith(".")||y.has(r)}async function N(r,t){let e=f.map(n=>({source:"built-in",pack:n}));for(let n of await F(r,t)){let a;try{a=await r.readFile(n.path)}catch{e.push({source:"workspace",...n,issues:["The file could not be read"]});continue}let o=x(a);e.push({source:"workspace",...n,...o})}return e}function A(r){return`${JSON.stringify(r,null,2)}
8
8
  `}async function T(r,t,e,n=!1){let a=t[0];if(a===void 0)return{kind:"no-workspace"};let o=d.parse(e),i=`${o.id}${k}`,p=c.join(a,i),s=A(o);if(n)await r.replace(p,s);else if(!await r.writeNew(p,s))return{kind:"exists",path:p,relativePath:i};return{kind:"saved",path:p,relativePath:i}}async function b(r,t,e,n){let a=i=>i.id===e&&u(i)===n,o=f.find(a);if(o)return o;for(let i of await N(r,t))if(i.source==="workspace"&&"pack"in i&&a(i.pack))return i.pack}export{k as a,P as b,O as c,x as d,F as e,N as f,A as g,T as h,b as i};
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{k as f}from"./chunk-N2HYG3BL.mjs";import{Ua as l}from"./chunk-6QSHWIZI.mjs";import{b as c,k as h,m,v,z as A}from"./chunk-WZQEK4WT.mjs";import{randomBytes as S}from"node:crypto";import{mkdir as k,open as O,readFile as E,readdir as $,rename as D,rm as F}from"node:fs/promises";import{join as u,resolve as N}from"node:path";var T=448,b=384,_=1e4,I=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/,J=/^\d{8}T\d{9}Z-00D[A-Za-z0-9]{15}\.json$/,y=A.datetime({offset:!0}),j=m({name:c().min(1).max(255),type:c().min(1).max(80),cronExpression:c().min(1).max(255).optional(),state:c().min(1).max(40),nextFireTime:y.optional(),previousFireTime:y.optional(),owner:c().min(1).max(255).optional()}),x=m({version:v(1),savedAt:y,organizationId:l,host:c().regex(I),jobs:h(j).max(_)});function z(e){return u(N(e),"audits")}function w(e){let n=e.trim().toLowerCase().replace(/\.$/,"");return I.test(n)?n:void 0}function K(e,n){let r=w(n);if(r===void 0)throw new Error(`Not a host name: "${n}"`);return u(z(e),r)}function R(e){return`${new Date(e.savedAt).toISOString().replace(/[-:.]/g,"")}-${f(e.organizationId)}.json`}async function Z(e,n){let r=x.parse(n),i=K(e,r.host);await k(i,{recursive:!0,mode:T});let s=u(i,R(r)),a=`${s}.${process.pid}-${S(4).toString("hex")}.tmp`,d=await O(a,"wx",b);try{try{await d.writeFile(`${JSON.stringify(r,null,2)}
7
+ import{k as f}from"./chunk-KGU4SVIT.mjs";import{Ua as l}from"./chunk-PMWAFDUB.mjs";import{b as c,k as h,m,v,z as A}from"./chunk-WZQEK4WT.mjs";import{randomBytes as S}from"node:crypto";import{mkdir as k,open as O,readFile as E,readdir as $,rename as D,rm as F}from"node:fs/promises";import{join as u,resolve as N}from"node:path";var T=448,b=384,_=1e4,I=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/,J=/^\d{8}T\d{9}Z-00D[A-Za-z0-9]{15}\.json$/,y=A.datetime({offset:!0}),j=m({name:c().min(1).max(255),type:c().min(1).max(80),cronExpression:c().min(1).max(255).optional(),state:c().min(1).max(40),nextFireTime:y.optional(),previousFireTime:y.optional(),owner:c().min(1).max(255).optional()}),x=m({version:v(1),savedAt:y,organizationId:l,host:c().regex(I),jobs:h(j).max(_)});function z(e){return u(N(e),"audits")}function w(e){let n=e.trim().toLowerCase().replace(/\.$/,"");return I.test(n)?n:void 0}function K(e,n){let r=w(n);if(r===void 0)throw new Error(`Not a host name: "${n}"`);return u(z(e),r)}function R(e){return`${new Date(e.savedAt).toISOString().replace(/[-:.]/g,"")}-${f(e.organizationId)}.json`}async function Z(e,n){let r=x.parse(n),i=K(e,r.host);await k(i,{recursive:!0,mode:T});let s=u(i,R(r)),a=`${s}.${process.pid}-${S(4).toString("hex")}.tmp`,d=await O(a,"wx",b);try{try{await d.writeFile(`${JSON.stringify(r,null,2)}
8
8
  `,"utf8"),await d.sync()}finally{await d.close()}await D(a,s)}catch(t){throw await F(a,{force:!0}),t}return s}async function C(e,n){let r=w(n);if(r===void 0)return{kept:[],setAside:[],unread:`${n} is not a host name`};let i=u(z(e),r),s;try{s=(await $(i,{withFileTypes:!0})).filter(t=>t.isFile()&&t.name.endsWith(".json")).map(t=>t.name).sort()}catch(t){let o=t?.code;return o==="ENOENT"||o==="ENOTDIR"?{kept:[],setAside:[]}:{kept:[],setAside:[],unread:`${i} could not be read: ${t instanceof Error?t.message:String(t)}`}}let a=[],d=[];for(let t of s){let o=u(i,t);if(!J.test(t)){d.push({path:o,why:"its name is not one --save gives"});continue}let g;try{g=JSON.parse(await E(o,"utf8"))}catch{d.push({path:o,why:"it does not read as JSON"});continue}let p=x.safeParse(g);if(!p.success){d.push({path:o,why:"it does not read as an inventory of this SandForge"});continue}if(p.data.host!==r){d.push({path:o,why:`it is of ${p.data.host}, not of the host its folder names`});continue}a.push({inventory:p.data,path:o})}return a.sort((t,o)=>Date.parse(o.inventory.savedAt)-Date.parse(t.inventory.savedAt)),{kept:a,setAside:d}}function V(e,n){let r=f(n),i=e.find(a=>f(a.inventory.organizationId)!==r);if(i!==void 0)return{kept:i,refreshed:!0};let s=e[0];return s!==void 0?{kept:s,refreshed:!1}:void 0}export{Z as a,C as b,V as c};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{I as H}from"./chunk-IXIY6Q4M.mjs";import{b as R,c as de,d as _}from"./chunk-MJD6CPZZ.mjs";import{i as ae}from"./chunk-INIT2UKJ.mjs";import{h as Y}from"./chunk-TZE3Y7IQ.mjs";import{b as F}from"./chunk-CA5NAXSU.mjs";var ke=5,Ie=100;function m(n){return n.slice(0,15)}function N(n){return n==null||n===""}var ce=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Re(n,e){if(N(n)||N(e))return N(n)&&N(e);if(typeof n=="number"||typeof e=="number")return Number(n)===Number(e);if(typeof n=="string"&&typeof e=="string"){if(n===e)return!0;if(ce.test(n)&&ce.test(e)){let s=Date.parse(n);return Number.isFinite(s)&&s===Date.parse(e)}return!1}return JSON.stringify(n)===JSON.stringify(e)}function Ae(n){let e;return()=>(e??=(async()=>{try{let s=await n.userId?.();return typeof s=="string"&&s!==""?m(s):void 0}catch{return}})(),e)}async function fe(n){let e=Date.now();try{let s=Date.parse(await n.serverTime());return Number.isFinite(s)?s-(e+Date.now())/2:0}catch{return 0}}async function Oe(n,e){let s=Date.parse(e??"");return Number.isFinite(s)?s+await fe(n)+H:Number.NEGATIVE_INFINITY}var ve=1e3;function Se(n){let e=Date.parse(n);return Number.isFinite(e)?e-ve:Number.NEGATIVE_INFINITY}function Pe(n,e){let s=Object.hasOwn(n,e)?n[e]:[];return new Map(s.filter(o=>o.toLowerCase()!=="id").map(o=>[o.toLowerCase(),o]))}var Ee={INACTIVE_OWNER_OR_USER:"OwnerId"};function je(n,e){let s=new Set;for(let r of n.errors??[]){if(typeof r=="string")continue;if(Array.isArray(r.fields))for(let g of r.fields)typeof g=="string"&&s.add(g);let c=r.statusCode!==void 0?Ee[r.statusCode]:void 0;c!==void 0&&(!Array.isArray(r.fields)||r.fields.length===0)&&s.add(c)}let o=new Map(Object.keys(e).map(r=>[r.toLowerCase(),r]));return[...s].flatMap(r=>{let c=o.get(r.toLowerCase());return c!==void 0&&c!=="Id"?[c]:[]})}function Fe(n,e){let s=Array.isArray(n)?n:[n];return Array.from({length:e},(o,r)=>s[r]??{success:!1})}function Q(n){let e=n.errors?.[0];if(e===void 0)return{words:"The org gave no reason."};if(typeof e=="string")return{words:e};let s=e.statusCode,o=e.message??"";return{...s?{code:s}:{},words:s&&o?`${s}: ${o}`:s||o}}function C(n,{fields:e,why:s}){return`${e.map(o=>`${n}.${o}`).join(", ")}: the value from before is no longer taken (${s}) \u2014 left as the run wrote it`}async function Le(n,e,s){let o=new Set;try{for(let r of _(s)){let c=await n.query(`SELECT Id FROM ${e} WHERE Id IN (${r})`);for(let g of c.records)typeof g.Id=="string"&&o.add(m(g.Id))}}catch(r){return{unread:F(r)}}return{live:o}}var Z=class{result;said=new Set;constructor(e,s){this.result={objectApiName:e,planned:s,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}without(){this.result.restoredWithout=(this.result.restoredWithout??0)+1}reason(e){this.said.has(e)||this.said.size>=ke||(this.said.add(e),this.result.reasons.push(e))}};async function Qe(n){let{org:e,plan:s}=n,o=[],r=[],c={},g=!1,u=!1;if(s.length===0)return{objects:o,left:r,wrote:g,cancelled:u,stamps:c};let A=n.changedAfter!==void 0?Se(n.changedAfter):await Oe(e,n.lastWriteAt),w=new Map(Object.entries(n.stamps??{}).map(([b,x])=>[m(b),Date.parse(x)])),L=n.ownWriters&&n.ownWriters.length>0?new Set(n.ownWriters.map(m)):void 0,T=n.stampsFor,he=Ae(e);for(let{objectApiName:b,backup:x,ids:D}of s){let l=new Z(b,D.length);o.push(l.result);let W=n.unkept?.find(t=>t.objectApiName===b);if(W&&W.fields.length>0&&l.reason(`${W.fields.map(t=>`${b}.${t}`).join(", ")}: not kept, encrypted \u2014 the run's user cannot view encrypted data, and read their values from before masked; left as the run wrote them`),u||n.signal?.aborted){u=!0,l.result.notReached=D.length,r.push(...D);continue}let G=Y(b),k=new Map(D.map(t=>[m(t),t])),U=n.fields?Pe(n.fields,b):void 0,v=new Map,q=new Set;try{let t=await n.backups.batches(x,b,R);for await(let i of t??[])for(let a of i){if(typeof a.Id!="string"||!k.has(m(a.Id)))continue;let d=v.get(m(a.Id))??{};for(let[h,f]of Object.entries(a)){if(h==="Id")continue;let p=U?U.get(h.toLowerCase()):h;p!==void 0&&!(p in d)&&(d[p]=f)}if(U&&Object.keys(d).length===0){q.add(m(a.Id));continue}v.set(m(a.Id),d)}}catch(t){l.reason(`The values from before the run could not be read: ${F(t)}`),v.clear(),q.clear()}let ee=[...q].filter(t=>!v.has(t)).length;ee>0&&l.reason(`${ee} ${b} record(s) hold no value of a field that may be written back now: left as they are`);for(let t of[...k.keys()])v.has(t)||(l.result.notKept++,k.delete(t));if(k.size===0)continue;let te=new Set;for(let t of v.values())for(let i of Object.keys(t))te.add(Y(i));let ne=["Id","LastModifiedDate",...L?["LastModifiedById"]:[],...te],pe=ne.length>Ie?R/4:R,J=new Map,ye=async t=>{if(n.signal?.aborted)throw new B;return(await e.query(t)).records};try{for(let t of _([...k.values()],pe)){let i=await ae(`SELECT ${ne.join(", ")} FROM ${G} WHERE Id IN (${t})`,ye,{stamp:"LastModifiedDate"});for(let a of i)typeof a.Id=="string"&&J.set(m(a.Id),a)}}catch(t){if(t instanceof B){u=!0,l.result.notReached=k.size,r.push(...k.values());continue}l.result.refused+=k.size,l.reason(F(t)),r.push(...k.values());continue}let $=[],re=new Set,me=T?Date.now()+await fe(e)-H:0;for(let[t,i]of k){let a=J.get(t);if(!a){l.result.alreadyGone++,n.counted?.(i,"alreadyGone");continue}let d=Date.parse(String(a.LastModifiedDate??"")),h=a.LastModifiedById,f=d<=A||d<=(w.get(t)??Number.NaN)||L!==void 0&&typeof h=="string"&&L.has(m(h));if(!f&&!n.includeChanged){l.result.keptChanged++,r.push(i);continue}let p=v.get(t)??{},y={Id:a.Id};for(let[I,O]of Object.entries(p))Re(O,a[I])||(y[I]=N(O)?null:O);if(Object.keys(y).length===1){l.result.restored++,n.counted?.(i,"restored"),f&&T?.(i)&&typeof a.LastModifiedDate=="string"&&(c[a.Id]=a.LastModifiedDate);continue}$.push(y),f&&T?.(i)&&re.add(i)}let P=[],S=[],E=(t,i)=>{l.result.refused++,l.reason(i),r.push(k.get(m(t.Id))??t.Id)},K=t=>{l.result.restored++,n.counted?.(k.get(m(t.Id))??t.Id,"restored")},we=t=>{l.result.alreadyGone++,n.counted?.(k.get(m(t.Id))??t.Id,"alreadyGone")},se=t=>{u=!0,l.result.notReached=(l.result.notReached??0)+t.length,r.push(...t.map(i=>k.get(m(i.Id))??i.Id))},oe=(t,i,a,d)=>{let h=Object.keys(t).filter(y=>y!=="Id"&&!i.includes(y));if(h.length>0){let y={Id:t.Id};for(let I of h)y[I]=t[I];P.push({record:y,leftOut:a});return}if(a.length===0){K(t);return}let[f,...p]=a;d?(l.without(),l.reason(C(b,f))):E(t,C(b,f));for(let y of p)l.reason(C(b,y))},z=async t=>{try{return g=!0,Fe(await e.update(b,[...t]),t.length)}catch(i){let a=F(i);return t.map(()=>({success:!1,errors:[a]}))}},be=async t=>{let i=n.keep;if(!i)return!0;let a=t.map(d=>{let h=J.get(m(d.Id))??{},f={Id:d.Id};for(let p of Object.keys(d))p!=="Id"&&(f[p]=h[p]??null);return f});try{return await i(b,a),!0}catch(d){let h=`What these ${t.length} ${b} record(s) hold now could not be kept before they were written (${F(d)}), so none of them was written: nothing is written over that cannot be put back.`;for(let f of t)E(f,h);return!1}};for(let t=0;t<$.length;t+=R){let i=$.slice(t,t+R);if(n.signal?.aborted){u=!0;let d=$.slice(t);l.result.notReached=(l.result.notReached??0)+d.length,r.push(...d.map(h=>k.get(m(h.Id))??h.Id));break}if(!await be(i))continue;(await z(i)).forEach((d,h)=>{let f=i[h];if(d.success===!0){K(f);return}let p=Q(d),y=je(d,f);if(p.code==="ENTITY_IS_DELETED"&&y.length===0){S.push({record:f,why:p.words});return}let I=Object.keys(f).filter(O=>O!=="Id"&&!y.includes(O));if(y.length>0&&I.length>0){let O={Id:f.Id};for(let ie of I)O[ie]=f[ie];P.push({record:O,leftOut:[{fields:y,why:p.words}]});return}E(f,p.words)})}let j=[];if(S.length>0&&n.signal?.aborted)se(S.map(({record:t})=>t));else if(S.length>0){let t=await Le(e,G,S.map(({record:i})=>i.Id));t.unread!==void 0&&l.reason(`Whether ${S.length} ${b} record(s) refused as deleted are still in the org could not be read (${t.unread}): left to be given back again`);for(let{record:i,why:a}of S){if(t.unread!==void 0){E(i,a);continue}if(!t.live.has(m(i.Id))){we(i);continue}let d=Object.keys(i).filter(h=>h!=="Id"&&de(i[h]));d.length===0?E(i,a):d.length===1?oe(i,d,[{fields:d,why:a}],!1):j.push({record:i,lookups:d,given:[],refusedAlone:[]})}}let V=j.length>0;for(let t=0;V&&j.some(({lookups:i})=>i.length>t);t++){let i=j.filter(({lookups:a})=>a.length>t);for(let a=0;a<i.length;a+=R){if(n.signal?.aborted){se(j.map(({record:f})=>f)),V=!1;break}let d=i.slice(a,a+R);(await z(d.map(({record:f,lookups:p})=>({Id:f.Id,[p[t]]:f[p[t]]})))).forEach((f,p)=>{let y=d[p],I=y.lookups[t];f.success===!0?y.given.push(I):y.refusedAlone.push({field:I,why:Q(f).words})})}}for(let t of V?j:[]){let i=new Map;for(let{field:a,why:d}of t.refusedAlone)i.set(d,[...i.get(d)??[],a]);oe(t.record,t.lookups,[...i].map(([a,d])=>({fields:d,why:a})),t.given.length>0)}for(let t=0;t<P.length;t+=R){let i=P.slice(t,t+R);if(n.signal?.aborted){u=!0,l.result.notReached=(l.result.notReached??0)+P.length-t,r.push(...P.slice(t).map(({record:d})=>k.get(m(d.Id))??d.Id));break}(await z(i.map(({record:d})=>d))).forEach((d,h)=>{let{record:f,leftOut:p}=i[h];if(d.success===!0){if(p.length===0){K(f);return}l.without();for(let y of p)l.reason(C(b,y));return}E(f,Q(d).words)})}Object.assign(c,await Ne(e,G,[...re],me,he))}return{objects:o,left:r,wrote:g,cancelled:u,stamps:c}}async function Ne(n,e,s,o,r){let c={};if(s.length===0)return c;let g=await r();if(g===void 0)return c;for(let u of _(s)){let A;try{A=(await n.query(`SELECT Id, LastModifiedDate, LastModifiedById FROM ${e} WHERE Id IN (${u})`)).records}catch{continue}for(let w of A)typeof w.Id=="string"&&typeof w.LastModifiedDate=="string"&&typeof w.LastModifiedById=="string"&&m(w.LastModifiedById)===g&&Date.parse(w.LastModifiedDate)>=o&&(c[w.Id]=w.LastModifiedDate)}return c}var B=class extends Error{};function Ze(n,e,s=[]){let o=n.map(r=>({...r}));for(let r of s){if(r.undeleted+r.refused===0)continue;let c=o.find(g=>g.objectApiName===r.objectApiName);c?(c.created+=r.undeleted,c.failed+=r.refused):o.push({objectApiName:r.objectApiName,created:r.undeleted,updated:0,deleted:0,failed:r.refused})}for(let r of e){let c=r.restored+(r.restoredWithout??0);if(c+r.refused===0)continue;let g=o.find(u=>u.objectApiName===r.objectApiName);g?(g.updated+=c,g.failed+=r.refused):o.push({objectApiName:r.objectApiName,created:0,updated:c,deleted:0,failed:r.refused})}return o}import{createReadStream as Me}from"node:fs";import{access as De,appendFile as $e,mkdir as _e,readFile as Ce,readdir as Be,rm as Te,stat as xe,writeFile as We}from"node:fs/promises";import*as M from"node:path";import{createInterface as Ge}from"node:readline";var ue=384,Ue=448;function rt(n){return{storagePath:n,readFile:e=>Ce(e,"utf8"),writeFile:(e,s)=>We(e,s,{encoding:"utf8",mode:ue}),appendFile:(e,s)=>$e(e,s,{encoding:"utf8",mode:ue}),exists:e=>De(e).then(()=>!0,()=>!1),readLines:e=>Je(e),mkdir:async e=>{await _e(e,{recursive:!0,mode:Ue})},rm:e=>Te(e,{force:!0}),listFiles:e=>qe(e)}}async function qe(n){let e;try{e=await Be(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}let s=[];for(let o of e){if(!o.isFile())continue;let r=await xe(M.join(n,o.name)).catch(()=>{});r&&s.push({name:o.name,modifiedMs:r.mtimeMs})}return s}async function*Je(n){let e=Me(n,{encoding:"utf8"}),s=Ge({input:e,crlfDelay:1/0});try{for await(let o of s)yield o}finally{s.close(),e.destroy()}}function X(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}function le(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var ge=class{constructor(e){this.deps=e;this.dir=M.join(e.storagePath,"backups")}deps;dir;get directory(){return this.dir}filePath(e,s,o="lines"){let r=`${X(e)}__${X(s)}`;return M.join(this.dir,`${r}.${o==="lines"?"ndjson":"json"}`)}async begin(e,s){await this.deps.mkdir(this.dir).catch(()=>{}),await this.deps.writeFile(this.filePath(e,s),"")}async append(e,s,o){if(o.length===0)return;let r=o.map(c=>JSON.stringify(c)).join(`
7
+ import{I as H}from"./chunk-H4CGM6YO.mjs";import{b as R,c as de,d as _}from"./chunk-JAEDM4SI.mjs";import{i as ae}from"./chunk-INIT2UKJ.mjs";import{h as Y}from"./chunk-TZE3Y7IQ.mjs";import{b as F}from"./chunk-CA5NAXSU.mjs";var ke=5,Ie=100;function m(n){return n.slice(0,15)}function N(n){return n==null||n===""}var ce=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Re(n,e){if(N(n)||N(e))return N(n)&&N(e);if(typeof n=="number"||typeof e=="number")return Number(n)===Number(e);if(typeof n=="string"&&typeof e=="string"){if(n===e)return!0;if(ce.test(n)&&ce.test(e)){let s=Date.parse(n);return Number.isFinite(s)&&s===Date.parse(e)}return!1}return JSON.stringify(n)===JSON.stringify(e)}function Ae(n){let e;return()=>(e??=(async()=>{try{let s=await n.userId?.();return typeof s=="string"&&s!==""?m(s):void 0}catch{return}})(),e)}async function fe(n){let e=Date.now();try{let s=Date.parse(await n.serverTime());return Number.isFinite(s)?s-(e+Date.now())/2:0}catch{return 0}}async function Oe(n,e){let s=Date.parse(e??"");return Number.isFinite(s)?s+await fe(n)+H:Number.NEGATIVE_INFINITY}var ve=1e3;function Se(n){let e=Date.parse(n);return Number.isFinite(e)?e-ve:Number.NEGATIVE_INFINITY}function Pe(n,e){let s=Object.hasOwn(n,e)?n[e]:[];return new Map(s.filter(o=>o.toLowerCase()!=="id").map(o=>[o.toLowerCase(),o]))}var Ee={INACTIVE_OWNER_OR_USER:"OwnerId"};function je(n,e){let s=new Set;for(let r of n.errors??[]){if(typeof r=="string")continue;if(Array.isArray(r.fields))for(let g of r.fields)typeof g=="string"&&s.add(g);let c=r.statusCode!==void 0?Ee[r.statusCode]:void 0;c!==void 0&&(!Array.isArray(r.fields)||r.fields.length===0)&&s.add(c)}let o=new Map(Object.keys(e).map(r=>[r.toLowerCase(),r]));return[...s].flatMap(r=>{let c=o.get(r.toLowerCase());return c!==void 0&&c!=="Id"?[c]:[]})}function Fe(n,e){let s=Array.isArray(n)?n:[n];return Array.from({length:e},(o,r)=>s[r]??{success:!1})}function Q(n){let e=n.errors?.[0];if(e===void 0)return{words:"The org gave no reason."};if(typeof e=="string")return{words:e};let s=e.statusCode,o=e.message??"";return{...s?{code:s}:{},words:s&&o?`${s}: ${o}`:s||o}}function C(n,{fields:e,why:s}){return`${e.map(o=>`${n}.${o}`).join(", ")}: the value from before is no longer taken (${s}) \u2014 left as the run wrote it`}async function Le(n,e,s){let o=new Set;try{for(let r of _(s)){let c=await n.query(`SELECT Id FROM ${e} WHERE Id IN (${r})`);for(let g of c.records)typeof g.Id=="string"&&o.add(m(g.Id))}}catch(r){return{unread:F(r)}}return{live:o}}var Z=class{result;said=new Set;constructor(e,s){this.result={objectApiName:e,planned:s,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}without(){this.result.restoredWithout=(this.result.restoredWithout??0)+1}reason(e){this.said.has(e)||this.said.size>=ke||(this.said.add(e),this.result.reasons.push(e))}};async function Qe(n){let{org:e,plan:s}=n,o=[],r=[],c={},g=!1,u=!1;if(s.length===0)return{objects:o,left:r,wrote:g,cancelled:u,stamps:c};let A=n.changedAfter!==void 0?Se(n.changedAfter):await Oe(e,n.lastWriteAt),w=new Map(Object.entries(n.stamps??{}).map(([b,x])=>[m(b),Date.parse(x)])),L=n.ownWriters&&n.ownWriters.length>0?new Set(n.ownWriters.map(m)):void 0,T=n.stampsFor,he=Ae(e);for(let{objectApiName:b,backup:x,ids:D}of s){let l=new Z(b,D.length);o.push(l.result);let W=n.unkept?.find(t=>t.objectApiName===b);if(W&&W.fields.length>0&&l.reason(`${W.fields.map(t=>`${b}.${t}`).join(", ")}: not kept, encrypted \u2014 the run's user cannot view encrypted data, and read their values from before masked; left as the run wrote them`),u||n.signal?.aborted){u=!0,l.result.notReached=D.length,r.push(...D);continue}let G=Y(b),k=new Map(D.map(t=>[m(t),t])),U=n.fields?Pe(n.fields,b):void 0,v=new Map,q=new Set;try{let t=await n.backups.batches(x,b,R);for await(let i of t??[])for(let a of i){if(typeof a.Id!="string"||!k.has(m(a.Id)))continue;let d=v.get(m(a.Id))??{};for(let[h,f]of Object.entries(a)){if(h==="Id")continue;let p=U?U.get(h.toLowerCase()):h;p!==void 0&&!(p in d)&&(d[p]=f)}if(U&&Object.keys(d).length===0){q.add(m(a.Id));continue}v.set(m(a.Id),d)}}catch(t){l.reason(`The values from before the run could not be read: ${F(t)}`),v.clear(),q.clear()}let ee=[...q].filter(t=>!v.has(t)).length;ee>0&&l.reason(`${ee} ${b} record(s) hold no value of a field that may be written back now: left as they are`);for(let t of[...k.keys()])v.has(t)||(l.result.notKept++,k.delete(t));if(k.size===0)continue;let te=new Set;for(let t of v.values())for(let i of Object.keys(t))te.add(Y(i));let ne=["Id","LastModifiedDate",...L?["LastModifiedById"]:[],...te],pe=ne.length>Ie?R/4:R,J=new Map,ye=async t=>{if(n.signal?.aborted)throw new B;return(await e.query(t)).records};try{for(let t of _([...k.values()],pe)){let i=await ae(`SELECT ${ne.join(", ")} FROM ${G} WHERE Id IN (${t})`,ye,{stamp:"LastModifiedDate"});for(let a of i)typeof a.Id=="string"&&J.set(m(a.Id),a)}}catch(t){if(t instanceof B){u=!0,l.result.notReached=k.size,r.push(...k.values());continue}l.result.refused+=k.size,l.reason(F(t)),r.push(...k.values());continue}let $=[],re=new Set,me=T?Date.now()+await fe(e)-H:0;for(let[t,i]of k){let a=J.get(t);if(!a){l.result.alreadyGone++,n.counted?.(i,"alreadyGone");continue}let d=Date.parse(String(a.LastModifiedDate??"")),h=a.LastModifiedById,f=d<=A||d<=(w.get(t)??Number.NaN)||L!==void 0&&typeof h=="string"&&L.has(m(h));if(!f&&!n.includeChanged){l.result.keptChanged++,r.push(i);continue}let p=v.get(t)??{},y={Id:a.Id};for(let[I,O]of Object.entries(p))Re(O,a[I])||(y[I]=N(O)?null:O);if(Object.keys(y).length===1){l.result.restored++,n.counted?.(i,"restored"),f&&T?.(i)&&typeof a.LastModifiedDate=="string"&&(c[a.Id]=a.LastModifiedDate);continue}$.push(y),f&&T?.(i)&&re.add(i)}let P=[],S=[],E=(t,i)=>{l.result.refused++,l.reason(i),r.push(k.get(m(t.Id))??t.Id)},K=t=>{l.result.restored++,n.counted?.(k.get(m(t.Id))??t.Id,"restored")},we=t=>{l.result.alreadyGone++,n.counted?.(k.get(m(t.Id))??t.Id,"alreadyGone")},se=t=>{u=!0,l.result.notReached=(l.result.notReached??0)+t.length,r.push(...t.map(i=>k.get(m(i.Id))??i.Id))},oe=(t,i,a,d)=>{let h=Object.keys(t).filter(y=>y!=="Id"&&!i.includes(y));if(h.length>0){let y={Id:t.Id};for(let I of h)y[I]=t[I];P.push({record:y,leftOut:a});return}if(a.length===0){K(t);return}let[f,...p]=a;d?(l.without(),l.reason(C(b,f))):E(t,C(b,f));for(let y of p)l.reason(C(b,y))},z=async t=>{try{return g=!0,Fe(await e.update(b,[...t]),t.length)}catch(i){let a=F(i);return t.map(()=>({success:!1,errors:[a]}))}},be=async t=>{let i=n.keep;if(!i)return!0;let a=t.map(d=>{let h=J.get(m(d.Id))??{},f={Id:d.Id};for(let p of Object.keys(d))p!=="Id"&&(f[p]=h[p]??null);return f});try{return await i(b,a),!0}catch(d){let h=`What these ${t.length} ${b} record(s) hold now could not be kept before they were written (${F(d)}), so none of them was written: nothing is written over that cannot be put back.`;for(let f of t)E(f,h);return!1}};for(let t=0;t<$.length;t+=R){let i=$.slice(t,t+R);if(n.signal?.aborted){u=!0;let d=$.slice(t);l.result.notReached=(l.result.notReached??0)+d.length,r.push(...d.map(h=>k.get(m(h.Id))??h.Id));break}if(!await be(i))continue;(await z(i)).forEach((d,h)=>{let f=i[h];if(d.success===!0){K(f);return}let p=Q(d),y=je(d,f);if(p.code==="ENTITY_IS_DELETED"&&y.length===0){S.push({record:f,why:p.words});return}let I=Object.keys(f).filter(O=>O!=="Id"&&!y.includes(O));if(y.length>0&&I.length>0){let O={Id:f.Id};for(let ie of I)O[ie]=f[ie];P.push({record:O,leftOut:[{fields:y,why:p.words}]});return}E(f,p.words)})}let j=[];if(S.length>0&&n.signal?.aborted)se(S.map(({record:t})=>t));else if(S.length>0){let t=await Le(e,G,S.map(({record:i})=>i.Id));t.unread!==void 0&&l.reason(`Whether ${S.length} ${b} record(s) refused as deleted are still in the org could not be read (${t.unread}): left to be given back again`);for(let{record:i,why:a}of S){if(t.unread!==void 0){E(i,a);continue}if(!t.live.has(m(i.Id))){we(i);continue}let d=Object.keys(i).filter(h=>h!=="Id"&&de(i[h]));d.length===0?E(i,a):d.length===1?oe(i,d,[{fields:d,why:a}],!1):j.push({record:i,lookups:d,given:[],refusedAlone:[]})}}let V=j.length>0;for(let t=0;V&&j.some(({lookups:i})=>i.length>t);t++){let i=j.filter(({lookups:a})=>a.length>t);for(let a=0;a<i.length;a+=R){if(n.signal?.aborted){se(j.map(({record:f})=>f)),V=!1;break}let d=i.slice(a,a+R);(await z(d.map(({record:f,lookups:p})=>({Id:f.Id,[p[t]]:f[p[t]]})))).forEach((f,p)=>{let y=d[p],I=y.lookups[t];f.success===!0?y.given.push(I):y.refusedAlone.push({field:I,why:Q(f).words})})}}for(let t of V?j:[]){let i=new Map;for(let{field:a,why:d}of t.refusedAlone)i.set(d,[...i.get(d)??[],a]);oe(t.record,t.lookups,[...i].map(([a,d])=>({fields:d,why:a})),t.given.length>0)}for(let t=0;t<P.length;t+=R){let i=P.slice(t,t+R);if(n.signal?.aborted){u=!0,l.result.notReached=(l.result.notReached??0)+P.length-t,r.push(...P.slice(t).map(({record:d})=>k.get(m(d.Id))??d.Id));break}(await z(i.map(({record:d})=>d))).forEach((d,h)=>{let{record:f,leftOut:p}=i[h];if(d.success===!0){if(p.length===0){K(f);return}l.without();for(let y of p)l.reason(C(b,y));return}E(f,Q(d).words)})}Object.assign(c,await Ne(e,G,[...re],me,he))}return{objects:o,left:r,wrote:g,cancelled:u,stamps:c}}async function Ne(n,e,s,o,r){let c={};if(s.length===0)return c;let g=await r();if(g===void 0)return c;for(let u of _(s)){let A;try{A=(await n.query(`SELECT Id, LastModifiedDate, LastModifiedById FROM ${e} WHERE Id IN (${u})`)).records}catch{continue}for(let w of A)typeof w.Id=="string"&&typeof w.LastModifiedDate=="string"&&typeof w.LastModifiedById=="string"&&m(w.LastModifiedById)===g&&Date.parse(w.LastModifiedDate)>=o&&(c[w.Id]=w.LastModifiedDate)}return c}var B=class extends Error{};function Ze(n,e,s=[]){let o=n.map(r=>({...r}));for(let r of s){if(r.undeleted+r.refused===0)continue;let c=o.find(g=>g.objectApiName===r.objectApiName);c?(c.created+=r.undeleted,c.failed+=r.refused):o.push({objectApiName:r.objectApiName,created:r.undeleted,updated:0,deleted:0,failed:r.refused})}for(let r of e){let c=r.restored+(r.restoredWithout??0);if(c+r.refused===0)continue;let g=o.find(u=>u.objectApiName===r.objectApiName);g?(g.updated+=c,g.failed+=r.refused):o.push({objectApiName:r.objectApiName,created:0,updated:c,deleted:0,failed:r.refused})}return o}import{createReadStream as Me}from"node:fs";import{access as De,appendFile as $e,mkdir as _e,readFile as Ce,readdir as Be,rm as Te,stat as xe,writeFile as We}from"node:fs/promises";import*as M from"node:path";import{createInterface as Ge}from"node:readline";var ue=384,Ue=448;function rt(n){return{storagePath:n,readFile:e=>Ce(e,"utf8"),writeFile:(e,s)=>We(e,s,{encoding:"utf8",mode:ue}),appendFile:(e,s)=>$e(e,s,{encoding:"utf8",mode:ue}),exists:e=>De(e).then(()=>!0,()=>!1),readLines:e=>Je(e),mkdir:async e=>{await _e(e,{recursive:!0,mode:Ue})},rm:e=>Te(e,{force:!0}),listFiles:e=>qe(e)}}async function qe(n){let e;try{e=await Be(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}let s=[];for(let o of e){if(!o.isFile())continue;let r=await xe(M.join(n,o.name)).catch(()=>{});r&&s.push({name:o.name,modifiedMs:r.mtimeMs})}return s}async function*Je(n){let e=Me(n,{encoding:"utf8"}),s=Ge({input:e,crlfDelay:1/0});try{for await(let o of s)yield o}finally{s.close(),e.destroy()}}function X(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}function le(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var ge=class{constructor(e){this.deps=e;this.dir=M.join(e.storagePath,"backups")}deps;dir;get directory(){return this.dir}filePath(e,s,o="lines"){let r=`${X(e)}__${X(s)}`;return M.join(this.dir,`${r}.${o==="lines"?"ndjson":"json"}`)}async begin(e,s){await this.deps.mkdir(this.dir).catch(()=>{}),await this.deps.writeFile(this.filePath(e,s),"")}async append(e,s,o){if(o.length===0)return;let r=o.map(c=>JSON.stringify(c)).join(`
8
8
  `);await this.deps.appendFile(this.filePath(e,s),`${r}
9
9
  `)}async batches(e,s,o){let r=this.filePath(e,s);if(await this.deps.exists(r))return{[Symbol.asyncIterator]:()=>this.readLineBatches(r,s,o)};let c=this.filePath(e,s,"array");return await this.deps.exists(c)?{[Symbol.asyncIterator]:()=>this.readArrayBatches(c,s,o)}:null}async*readLineBatches(e,s,o){let r=[],c=0;for await(let g of this.deps.readLines(e)){if(c+=1,g.trim()==="")continue;let u;try{u=JSON.parse(g)}catch{u=void 0}if(!le(u))throw new Error(`The backup of ${s} is damaged at line ${c} of its file: it holds no record there.`);r.push(u),r.length===o&&(yield r,r=[])}r.length>0&&(yield r)}async*readArrayBatches(e,s,o){let r=JSON.parse(await this.deps.readFile(e));if(!Array.isArray(r)||!r.every(le))throw new Error(`The backup of ${s} is damaged: its file holds no records.`);for(let c=0;c<r.length;c+=o)yield r.slice(c,c+o)}async delete(e,s){await this.deps.rm(this.filePath(e,s)).catch(()=>{}),await this.deps.rm(this.filePath(e,s,"array")).catch(()=>{})}async sweep(e,s,o){let r=[...e].map(u=>`${X(u)}__`),c=new Map;for(let u of await this.deps.listFiles(this.dir)){if(!/\.(?:ndjson|json)$/.test(u.name))continue;let A=u.name.indexOf("__");if(A<=0||r.some(L=>u.name.startsWith(L)))continue;let w=u.name.slice(0,A);c.set(w,[...c.get(w)??[],u])}let g=[];for(let u of c.values()){let A=Math.max(...u.map(w=>w.modifiedMs));if(!(o-A<s))for(let w of u)await this.deps.rm(M.join(this.dir,w.name)).then(()=>g.push(w.name),()=>{})}return g}};export{Re as a,Ae as b,fe as c,Oe as d,Qe as e,Ne as f,Ze as g,rt as h,ge as i};
@@ -4,10 +4,10 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{d as ae}from"./chunk-PDRXM5WN.mjs";import{b as F,d as B}from"./chunk-UV74P4H2.mjs";import{H as ne,d as te,k as E,z as re}from"./chunk-N2HYG3BL.mjs";import{Ra as J,Ua as Z,cb as q}from"./chunk-6QSHWIZI.mjs";import{b as l,e as h,i as X,k as I,l as f,r as Q,s as T,u as _,v as x,z as ee}from"./chunk-WZQEK4WT.mjs";import{randomBytes as _e}from"node:crypto";import{open as Je,readFile as Be,readdir as De,rename as $e,rm as Ue,stat as Ge}from"node:fs/promises";import{homedir as We}from"node:os";import{join as k,resolve as Ze}from"node:path";import*as L from"node:fs";import*as D from"node:path";function Ie(n){return`counting-contract.${F(n)}.json`}function K(n,e,t){return n.assertOutsideRepo(D.join(e,Ie(t)))}function Qe(n,e,t){let r=K(n,e,t.orgId);return L.mkdirSync(D.dirname(r),{recursive:!0}),L.writeFileSync(r,`${JSON.stringify(t,null,2)}
8
- `,"utf8"),r}function et(n,e){let t=n.assertOutsideRepo(e),r=JSON.parse(L.readFileSync(t,"utf8"));if(r.version!==1||typeof r.objects!="object"||r.objects===null)throw new Error(`Invalid counting contract at ${t}: version 1 with objects expected`);return r}function tt(n,e){if(n.loadStartedAt!==void 0)return n.loadStartedAt===e.startedAt;let t=Date.parse(n.writtenAt),r=Date.parse(e.endedAt);return Number.isFinite(t)&&Number.isFinite(r)&&t>=r}import*as w from"node:fs/promises";import*as O from"node:path";var it=4*1024*1024,ot=64*1024*1024;var oe=1e4,M=l().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),b=l().min(1).max(40),st=f({forgeId:l().min(1).max(200),targetOrgId:l().min(1).max(128),timestamp:b,duration:h().nonnegative(),status:_(["success","partial","failure"]),cancelled:x(!0).optional(),writtenBetween:f({first:b,last:b}).optional(),retryOf:l().min(1).max(200).optional(),objects:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:I(M)})),linked:h().int().nonnegative(),mayHaveBeenWritten:h().int().nonnegative().optional(),undo:f({removedAt:b,deleted:h().int().nonnegative(),alreadyGone:h().int().nonnegative(),kept:h().int().nonnegative(),refused:h().int().nonnegative(),notReached:h().int().nonnegative().optional(),notVisible:h().int().nonnegative().optional()}).optional(),removalStamps:T(M,b).optional(),removalSpans:I(f({first:b,last:b,userId:M})).optional(),removalLeft:I(M).optional(),sweep:f({sweptAt:b,deleted:h().int().nonnegative(),keptChanged:h().int().nonnegative(),refused:h().int().nonnegative()}).optional(),inJournal:f({journalId:l().min(1).max(200),part:h().int().nonnegative(),left:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:h().int().nonnegative()}))}).optional()}),dt=f({version:x(1),plans:I(X())}),ct=f({version:x(1),runs:I(f({forgeId:l().min(1).max(300),ids:I(M),late:I(M).optional()}))});var U="referenceid-mapping.json",ze=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,Re=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,N=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,V=new Set;function ve(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Se=f({at:l().min(1).max(40),object:l().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:I(Q([l().min(1).max(400),l().regex(N)])).max(1e4)}),Oe=f({journal:f({startedAt:l().min(1).max(40),pid:h().int().positive(),runUserId:l().regex(N).optional()})});function be(n){let e,t={},r=new Map,o;for(let a of n.split(`
9
- `)){if(a.trim()==="")continue;let s;try{s=JSON.parse(a)}catch{continue}if(!e){let c=Oe.safeParse(s);c.success&&(e=c.data.journal);continue}let i=Se.safeParse(s);if(!i.success)continue;let d=r.get(i.data.object)??[];for(let[c,u]of i.data.created)Object.prototype.hasOwnProperty.call(t,c)||d.push(c),t[c]=u;r.set(i.data.object,d),o=i.data.at}if(!(!e||o===void 0||Object.keys(t).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:o,mapping:t,created:[...r].filter(([,a])=>a.length>0).map(([a,s])=>({objectApiName:a,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:o},...e.runUserId?{runUserId:e.runUserId}:{}}}}function je(n){return`referenceid-mapping.${F(n)}.json`}async function $(n){let e;try{e=await w.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}return JSON.parse(e)}async function pe(n,e){let t=e.assertOutsideRepo(n),r;try{r=await w.readdir(t)}catch(a){if(a.code==="ENOENT")return[];throw a}let o=new Set(r.flatMap(a=>ze.exec(a)?.[1]??Re.exec(a)?.[1]??[]));if(r.includes(U)){let s=(await $(e.assertOutsideRepo(O.join(t,U))))?.orgId;typeof s=="string"&&Ae(s)&&o.add(s)}return[...o].sort()}function Ae(n){try{return F(n),!0}catch{return!1}}var Ee=I(f({objectApiName:l(),referenceIds:I(l())})),ke=f({startedAt:l(),endedAt:l()}),xe=f({first:l(),last:l()}),Fe=f({removedAt:l(),deleted:h(),alreadyGone:h(),kept:h(),refused:h(),notReached:h().optional()}),Le=T(l(),l()),Me=I(f({first:l(),last:l(),userId:l()})),se=T(l(),l()),Y=l().regex(N);function R(n,e){let t=n.safeParse(e);return t.success?t.data:void 0}function S(n){if(typeof n!="object"||n===null)return;let e=n,t=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(m=>typeof m[1]=="string")):{},r=R(Ee,e.created),o=R(ke,e.load),a=R(xe,e.writtenBetween),s=R(Fe,e.removal),i=R(Le,e.removalStamps),d=R(Me,e.removalSpans),c=R(se,e.personContacts),u=R(se,e.withTheirRecord),g=R(Y,e.runUserId),p=R(I(Y),e.madeEarlier),P=R(I(Y),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:t,...r?{created:r}:{},...o?{load:o}:{},...a?{writtenBetween:a}:{},...s?{removal:s}:{},...i?{removalStamps:i}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...u?{withTheirRecord:u}:{},...g?{runUserId:g}:{},...p?{madeEarlier:p}:{},...P?{lateEarlier:P}:{}}}function j(n){return Array.isArray(n.earlier)?n.earlier.flatMap(e=>S(e)??[]):[]}function A(n){return n.load?.endedAt??n.updatedAt}function Ne(n,e){return n.slice(0,15)===e.slice(0,15)}function v(n){return n.slice(0,15)}function de(n,e){let t={};for(let[r,o]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(e,o)?Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=o):delete e[r];return t}function ce(n,e){if(e.size===0)return n;let t=Object.fromEntries(Object.entries(n.mapping).filter(([,d])=>!e.has(v(d)))),r=de(n.personContacts,t),o=de(n.withTheirRecord,t),a=n.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(u=>Object.prototype.hasOwnProperty.call(t,u))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([d])=>!e.has(v(d)))),i={...n,mapping:t};return delete i.removalStamps,delete i.personContacts,delete i.withTheirRecord,{...i,...a?{created:a}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(r).length>0?{personContacts:r}:{},...Object.keys(o).length>0?{withTheirRecord:o}:{}}}function le(n){return n.created?n.created.some(e=>e.referenceIds.length>0):Object.keys(n.mapping).length>0}var G=class{constructor(e,t){this.sasDir=e;this.guard=t?.guard??new B,this.orgId=t?.orgId??"";let r=t?.organizationId;this.askOrganizationId=typeof r=="function"?r:async()=>r,this.now=t?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(O.join(this.sasDir,this.orgId===""?U:je(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(O.join(this.sasDir,U))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${F(this.orgId)}`}journalPath(e){let t=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(O.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(t))}.ndjson`))}retiring=new Map;journal(e){let t=this.journalPath(e),r=!1,o=!1,a=!1,s,i=Promise.resolve(),d;V.add(t);let c=g=>{i=i.then(async()=>{if(!(d!==void 0||o))try{if(!r){r=!0,await w.mkdir(O.dirname(t),{recursive:!0});let p={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await w.appendFile(t,`${JSON.stringify(p)}
7
+ import{c as ae,d as ie}from"./chunk-Y2DRK37K.mjs";import{b as F,d as B}from"./chunk-UV74P4H2.mjs";import{H as ne,d as te,k as E,z as re}from"./chunk-KGU4SVIT.mjs";import{Ra as J,Ua as Z,cb as q}from"./chunk-PMWAFDUB.mjs";import{b as l,e as h,i as X,k as I,l as f,r as Q,s as T,u as _,v as x,z as ee}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Je}from"node:crypto";import{open as Be,readFile as De,readdir as $e,rename as Ue,rm as Ge,stat as We}from"node:fs/promises";import{homedir as Ze}from"node:os";import{join as k,resolve as qe}from"node:path";import*as L from"node:fs";import*as D from"node:path";function Pe(n){return`counting-contract.${F(n)}.json`}function K(n,e,t){return n.assertOutsideRepo(D.join(e,Pe(t)))}function et(n,e,t){let r=K(n,e,t.orgId);return L.mkdirSync(D.dirname(r),{recursive:!0}),L.writeFileSync(r,`${JSON.stringify(t,null,2)}
8
+ `,"utf8"),r}function tt(n,e){let t=n.assertOutsideRepo(e),r=JSON.parse(L.readFileSync(t,"utf8"));if(r.version!==1||typeof r.objects!="object"||r.objects===null)throw new Error(`Invalid counting contract at ${t}: version 1 with objects expected`);return r}function rt(n,e){if(n.loadStartedAt!==void 0)return n.loadStartedAt===e.startedAt;let t=Date.parse(n.writtenAt),r=Date.parse(e.endedAt);return Number.isFinite(t)&&Number.isFinite(r)&&t>=r}import*as w from"node:fs/promises";import*as O from"node:path";var ot=4*1024*1024,st=64*1024*1024;var se=1e4,M=l().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),b=l().min(1).max(40),dt=f({forgeId:l().min(1).max(200),targetOrgId:l().min(1).max(128),timestamp:b,duration:h().nonnegative(),status:_(["success","partial","failure"]),cancelled:x(!0).optional(),writtenBetween:f({first:b,last:b}).optional(),retryOf:l().min(1).max(200).optional(),objects:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:I(M)})),linked:h().int().nonnegative(),mayHaveBeenWritten:h().int().nonnegative().optional(),undo:f({removedAt:b,deleted:h().int().nonnegative(),alreadyGone:h().int().nonnegative(),kept:h().int().nonnegative(),refused:h().int().nonnegative(),notReached:h().int().nonnegative().optional(),notVisible:h().int().nonnegative().optional()}).optional(),removalStamps:T(M,b).optional(),removalSpans:I(f({first:b,last:b,userId:M})).optional(),removalLeft:I(M).optional(),sweep:f({sweptAt:b,deleted:h().int().nonnegative(),keptChanged:h().int().nonnegative(),refused:h().int().nonnegative()}).optional(),inJournal:f({journalId:l().min(1).max(200),part:h().int().nonnegative(),left:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:h().int().nonnegative()}))}).optional()}),ct=f({version:x(1),plans:I(X())}),lt=f({version:x(1),runs:I(f({forgeId:l().min(1).max(300),ids:I(M),late:I(M).optional()}))});var U="referenceid-mapping.json",Re=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,ve=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,N=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,V=new Set;function Se(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Oe=f({at:l().min(1).max(40),object:l().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:I(Q([l().min(1).max(400),l().regex(N)])).max(1e4)}),be=f({journal:f({startedAt:l().min(1).max(40),pid:h().int().positive(),runUserId:l().regex(N).optional()})});function je(n){let e,t={},r=new Map,o;for(let a of n.split(`
9
+ `)){if(a.trim()==="")continue;let s;try{s=JSON.parse(a)}catch{continue}if(!e){let c=be.safeParse(s);c.success&&(e=c.data.journal);continue}let i=Oe.safeParse(s);if(!i.success)continue;let d=r.get(i.data.object)??[];for(let[c,u]of i.data.created)Object.prototype.hasOwnProperty.call(t,c)||d.push(c),t[c]=u;r.set(i.data.object,d),o=i.data.at}if(!(!e||o===void 0||Object.keys(t).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:o,mapping:t,created:[...r].filter(([,a])=>a.length>0).map(([a,s])=>({objectApiName:a,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:o},...e.runUserId?{runUserId:e.runUserId}:{}}}}function Ae(n){return`referenceid-mapping.${F(n)}.json`}async function $(n){let e;try{e=await w.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}return JSON.parse(e)}async function ue(n,e){let t=e.assertOutsideRepo(n),r;try{r=await w.readdir(t)}catch(a){if(a.code==="ENOENT")return[];throw a}let o=new Set(r.flatMap(a=>Re.exec(a)?.[1]??ve.exec(a)?.[1]??[]));if(r.includes(U)){let s=(await $(e.assertOutsideRepo(O.join(t,U))))?.orgId;typeof s=="string"&&Ee(s)&&o.add(s)}return[...o].sort()}function Ee(n){try{return F(n),!0}catch{return!1}}var ke=I(f({objectApiName:l(),referenceIds:I(l())})),xe=f({startedAt:l(),endedAt:l()}),Fe=f({first:l(),last:l()}),Le=f({removedAt:l(),deleted:h(),alreadyGone:h(),kept:h(),refused:h(),notReached:h().optional()}),Me=T(l(),l()),Ne=I(f({first:l(),last:l(),userId:l()})),de=T(l(),l()),Y=l().regex(N);function R(n,e){let t=n.safeParse(e);return t.success?t.data:void 0}function S(n){if(typeof n!="object"||n===null)return;let e=n,t=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(m=>typeof m[1]=="string")):{},r=R(ke,e.created),o=R(xe,e.load),a=R(Fe,e.writtenBetween),s=R(Le,e.removal),i=R(Me,e.removalStamps),d=R(Ne,e.removalSpans),c=R(de,e.personContacts),u=R(de,e.withTheirRecord),g=R(Y,e.runUserId),p=R(I(Y),e.madeEarlier),P=R(I(Y),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:t,...r?{created:r}:{},...o?{load:o}:{},...a?{writtenBetween:a}:{},...s?{removal:s}:{},...i?{removalStamps:i}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...u?{withTheirRecord:u}:{},...g?{runUserId:g}:{},...p?{madeEarlier:p}:{},...P?{lateEarlier:P}:{}}}function j(n){return Array.isArray(n.earlier)?n.earlier.flatMap(e=>S(e)??[]):[]}function A(n){return n.load?.endedAt??n.updatedAt}function Ce(n,e){return n.slice(0,15)===e.slice(0,15)}function v(n){return n.slice(0,15)}function ce(n,e){let t={};for(let[r,o]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(e,o)?Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=o):delete e[r];return t}function le(n,e){if(e.size===0)return n;let t=Object.fromEntries(Object.entries(n.mapping).filter(([,d])=>!e.has(v(d)))),r=ce(n.personContacts,t),o=ce(n.withTheirRecord,t),a=n.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(u=>Object.prototype.hasOwnProperty.call(t,u))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([d])=>!e.has(v(d)))),i={...n,mapping:t};return delete i.removalStamps,delete i.personContacts,delete i.withTheirRecord,{...i,...a?{created:a}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(r).length>0?{personContacts:r}:{},...Object.keys(o).length>0?{withTheirRecord:o}:{}}}function ge(n){return n.created?n.created.some(e=>e.referenceIds.length>0):Object.keys(n.mapping).length>0}var G=class{constructor(e,t){this.sasDir=e;this.guard=t?.guard??new B,this.orgId=t?.orgId??"";let r=t?.organizationId;this.askOrganizationId=typeof r=="function"?r:async()=>r,this.now=t?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(O.join(this.sasDir,this.orgId===""?U:Ae(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(O.join(this.sasDir,U))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${F(this.orgId)}`}journalPath(e){let t=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(O.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(t))}.ndjson`))}retiring=new Map;journal(e){let t=this.journalPath(e),r=!1,o=!1,a=!1,s,i=Promise.resolve(),d;V.add(t);let c=g=>{i=i.then(async()=>{if(!(d!==void 0||o))try{if(!r){r=!0,await w.mkdir(O.dirname(t),{recursive:!0});let p={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await w.appendFile(t,`${JSON.stringify(p)}
10
10
  `,"utf8")}await w.appendFile(t,`${JSON.stringify(g)}
11
- `,"utf8")}catch(p){d=p instanceof Error?p.message:String(p)}})},u=async()=>{await i,o=!0,await w.rm(t,{force:!0})};return this.retiring.set(t,u),{writtenAs:g=>{N.test(g)&&(s=g)},created:(g,p)=>{let P=p.filter(([m,y])=>m!==""&&N.test(y));if(P.length!==0){a=!0;for(let m=0;m<P.length;m+=1e4)c({at:this.now().toISOString(),object:g,created:P.slice(m,m+1e4)})}},flush:async()=>(await i,d),close:async()=>{await i,this.retiring.delete(t),(o||!a)&&await w.rm(t,{force:!0}),o=!0,V.delete(t)}}}async stoppedLoads(e){let t;try{t=await w.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=`${this.journalStem}.load-`,o=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),a=[];for(let s of t){if(!s.startsWith(r)||!/^\d{1,16}\.ndjson$/.test(s.slice(r.length)))continue;let i=this.guard.assertOutsideRepo(O.join(this.sasDir,s));if(V.has(i))continue;let d;try{d=await w.readFile(i,"utf8")}catch{continue}let c=be(d);!c||o.has(c.startedAt)||c.pid!==process.pid&&ve(c.pid)||a.push({file:i,load:c.load})}return a}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let t=S(e);return[...t?[t]:[],...j(e)].map(r=>({mapping:new Map(Object.entries(r.mapping)),...r.created?{created:r.created}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},endedAt:A(r),...r.removalStamps?{removalStamps:r.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let t=typeof e.orgId=="string"?e.orgId:"",r=S(e);return[...r?[this.recordedOf(r,t)]:[],...j(e).map(o=>({...this.recordedOf(o,t),earlier:!0}))]}recordedOf(e,t){return{orgId:t,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:A(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let t=e.organizationId;if(t===void 0)return!1;let r=await this.currentOrganizationId();return r!==void 0&&!Ne(t,r)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await $(this.filePath);if(e!==void 0)return e;let t=this.singleFilePath;if(t===void 0)return;let r=await $(t);return r?.orgId===this.orgId?r:void 0}async readWithJournals(){let e=await this.readFile(),t=e?[S(e),...j(e)]:[],r=await this.stoppedLoads(t.filter(i=>i!==void 0));if(r.length===0)return{payload:e,journals:[]};let o=[...t.filter(i=>i!==void 0),...r.map(({load:i})=>i)].sort((i,d)=>Date.parse(A(d))-Date.parse(A(i))),[a,...s]=o;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...a,...s.length>0?{earlier:s}:{}},journals:r.map(({file:i})=>i)}}async dropJournals(e){for(let t of e)await w.rm(t,{force:!0}).catch(()=>{})}async write(e){let t=this.filePath;await w.mkdir(O.dirname(t),{recursive:!0}),await w.writeFile(t,`${JSON.stringify(e,null,2)}
12
- `,"utf8");let r=this.singleFilePath;if(r!==void 0)try{(await $(r))?.orgId===this.orgId&&await w.rm(r)}catch{}}async keptLoads(e,t,r=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let o=new Set(t.map(v)),a=new Set(r),s=S(e);return[...s?[s]:[],...j(e)].map(i=>ce(i,o)).filter(i=>le(i)||a.has(A(i)))}async persist(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=t?.earlier?await this.keptLoads(r,t.earlier.settled,t.earlier.stillToSweep):[],s=await this.currentOrganizationId(),i=this.now().toISOString(),d=g=>Object.fromEntries(Object.entries(g??{}).filter(([p,P])=>e.has(p)&&e.has(P))),c=d(t?.personContacts),u=d(t?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:i,mapping:Object.fromEntries([...e.entries()].sort(([g],[p])=>g.localeCompare(p))),...t?{created:t.created.map(({objectApiName:g,referenceIds:p})=>({objectApiName:g,referenceIds:p.filter(P=>e.has(P))})).filter(g=>g.referenceIds.length>0),load:{startedAt:t.startedAt.toISOString(),endedAt:i},...t.writtenBetween?{writtenBetween:{...t.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(u).length>0?{withTheirRecord:u}:{},...t.runUserId?{runUserId:t.runUserId}:{}}:{},...a.length>0?{earlier:a}:{}}),t?.earlier&&await this.dropJournals(o),t){let g=this.journalPath(t.startedAt),p=this.retiring.get(g);p?await p():await w.rm(g,{force:!0}).catch(()=>{})}}async recordRemoval(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=S(r);if(r===void 0||a===void 0)return!1;let s=[a,...j(r)],i=s.findIndex(g=>A(g)===e);if(i<0)return!1;let d=new Set(t.gone.map(v)),[c,...u]=s.map((g,p)=>ce(p===i?Te(g,t):g,d));return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...c,updatedAt:this.now().toISOString(),...u.length>0?{earlier:u}:{}}),await this.dropJournals(o),!0}async recordMade(e,t,r=[],o=[]){let{payload:a,journals:s}=await this.readWithJournals(),i=S(a);if(a===void 0||i===void 0)return!1;let d=[i,...j(a)],c=d.findIndex(m=>A(m)===e);if(c<0)return!1;let u=[...o],g=m=>{let y=ge(m.madeEarlier,t,u),z=ge(m.lateEarlier,r,u),C={...m};return delete C.madeEarlier,delete C.lateEarlier,{...C,...y.length>0?{madeEarlier:y}:{},...z.length>0?{lateEarlier:z}:{}}},[p,...P]=d.map((m,y)=>y===c?g(m):m);return await this.write({version:1,orgId:typeof a.orgId=="string"?a.orgId:"",...a.organizationId!==void 0?{organizationId:a.organizationId}:{},...p,...P.length>0?{earlier:P}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=new Set(e),s=j(t),i=s.filter(d=>le(d)||!a.has(A(d)));return i.length===s.length?!1:(await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...o,...i.length>0?{earlier:i}:{}}),await this.dropJournals(r),!0)}async recordStamps(e){let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=[o,...j(t)],s=a.map(c=>Ce(c,e));if(s.every((c,u)=>c===a[u]))return!1;let[i,...d]=s;return await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...i,...d.length>0?{earlier:d}:{}}),await this.dropJournals(r),!0}};function ge(n,e,t=[]){let r=new Map,o=new Set(t.map(v)),a=[];for(let s of[...n??[],...e]){let i=v(s),d=i.slice(0,3),c=r.get(d)??0;!N.test(s)||o.has(i)||c>=oe||(o.add(i),r.set(d,c+1),a.push(s))}return a}function Ce(n,e){let t=new Set(Object.values(n.mapping).map(v)),r=Object.entries(e).filter(([a])=>t.has(v(a)));if(r.length===0)return n;let o=new Set(r.map(([a])=>v(a)));return{...n,removalStamps:{...Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([a])=>!o.has(v(a)))),...Object.fromEntries(r)}}}function Te(n,e){let t={...n.removalStamps,...e.stamps},r=[...n.removalSpans??[],...e.span?[e.span]:[]],o=e.mark??n.removal;return{...n,...o?{removal:o}:{},...Object.keys(t).length>0?{removalStamps:t}:{},...r.length>0?{removalSpans:r}:{}}}var qe="replays",ue="replay.json";function St(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Ze(e):k(We(),".sandforge");return k(t,qe)}var H=ee.datetime({offset:!0}),Ke=f({organizationId:Z,name:l().min(1).max(255),choices:q,firstAt:H,lastAt:H}),we=f({version:x(1),checkpoint:f({checkpointId:J,name:l().min(1).max(255),organizationId:Z,alias:l().min(1).max(255).optional(),tier:_(["sandbox","scratch","developer"]),takenAt:H}),targets:I(Ke).max(1e4)}),fe=/^00D[A-Za-z0-9]{15}$/,me=class{root;guard;now;writes=new Map;constructor(e){this.guard=e.guard??new B,this.root=this.guard.assertOutsideRepo(e.root),this.now=e.now??(()=>new Date)}folderOf(e,t){let r=E(e),o=J.safeParse(t);if(!o.success)throw new ne("invalid","Not a checkpoint\u2019s id");return{dir:this.guard.assertOutsideRepo(k(this.root,r,o.data)),sourceOrganizationId:r,checkpointId:o.data}}async record(e,t,r){let o=this.folderOf(e.org.organizationId,e.checkpointId),a=E(t.organizationId),s=q.parse(r);await re(o.dir);let i=k(o.dir,ue),d=async()=>{let g=this.now().toISOString(),p=await he(i),P=p?.targets.find(y=>y.organizationId===a),m={version:1,checkpoint:{checkpointId:o.checkpointId,name:e.name,organizationId:o.sourceOrganizationId,...e.org.alias!==void 0?{alias:e.org.alias}:{},tier:e.org.tier,takenAt:e.takenAt},targets:[...p?.targets.filter(y=>y.organizationId!==a)??[],{organizationId:a,name:t.name,choices:s,firstAt:P?.firstAt??g,lastAt:g}]};await Ye(i,`${JSON.stringify(we.parse(m),null,2)}
13
- `)},c=(this.writes.get(i)??Promise.resolve()).then(d,d),u=c.catch(()=>{});return this.writes.set(i,u),u.then(()=>{this.writes.get(i)===u&&this.writes.delete(i)}),await c,o}mappingStoreOf(e,t,r={}){return new G(e.dir,{guard:this.guard,orgId:E(t),...r})}contractPathOf(e,t){return K(this.guard,e.dir,E(t))}async read(e){return he(k(e.dir,ue))}async list(e={}){let t=e.sourceOrganizationId!==void 0?E(e.sourceOrganizationId):void 0,r=e.targetOrganizationId!==void 0?E(e.targetOrganizationId):void 0,o=[];for(let a of await ye(this.root))if(!(!fe.test(a)||t!==void 0&&a!==t))for(let s of await ye(k(this.root,a))){if(!J.safeParse(s).success||e.checkpointId!==void 0&&s!==e.checkpointId)continue;let i=this.folderOf(a,s);o.push(...await this.entriesOf(i,r))}return o.sort((a,s)=>W(s.replayedAt??"",a.replayedAt??"")||W(a.checkpointId,s.checkpointId)||W(a.target.organizationId,s.target.organizationId))}async replaysOf(e,t){return this.list({sourceOrganizationId:e,checkpointId:t})}async entriesOf(e,t){let r=await this.read(e),o=new Map(r?.targets.map(d=>[d.organizationId,d])),a=(await pe(e.dir,this.guard)).filter(d=>fe.test(d)),s=[...new Set([...o.keys(),...a])].filter(d=>t===void 0||d===t),i=[];for(let d of s){let c=o.get(d),u=await this.mappingStoreOf(e,d).recordedLoads(),g=new Map;for(let y of u)for(let{objectApiName:z,ids:C}of ae(y))g.set(z,(g.get(z)??0)+C.length);let p=[...g].map(([y,z])=>({objectApiName:y,records:z})).sort((y,z)=>W(y.objectApiName,z.objectApiName)),P=p.reduce((y,z)=>y+z.records,0),m=u.find(y=>y.earlier!==!0);i.push({sourceOrganizationId:e.sourceOrganizationId,checkpointId:e.checkpointId,...r?{checkpointName:r.checkpoint.name}:{},...r?{takenAt:r.checkpoint.takenAt}:{},target:{organizationId:d,...c?{name:c.name}:{}},...c?{choices:c.choices}:{},...m?{replayedAt:m.endedAt}:{},inPlace:P,inPlaceByObject:p,...m!==void 0&&P===0&&m.removal!==void 0?{removed:!0}:{}})}return i}};function Ve(n){return n.filter(e=>e.inPlace>0)}function Ot(n){let e=Ve(n);if(e.length===0)return;let t=e.map(r=>`${r.inPlace.toLocaleString("en-US")} record${r.inPlace===1?"":"s"} in ${r.target.name??r.target.organizationId}`).join(", ");return`${e.length===1?"A replay":`${e.length} replays`} of it ${e.length===1?"is":"are"} still in place: ${t}. Deleting the checkpoint leaves them there, and each replay is still removed without it.`}async function he(n){let e;try{e=await Be(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}try{let t=we.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}async function Ye(n,e){let t=`${n}.${process.pid}-${_e(4).toString("hex")}.tmp`,r=await Je(t,"wx",te);try{try{await r.writeFile(e,"utf8"),await r.sync()}finally{await r.close()}await $e(t,n)}catch(o){throw await Ue(t,{force:!0}),o}}async function ye(n){let e;try{e=await De(n)}catch(r){if(r.code==="ENOENT")return[];throw r}let t=[];for(let r of e)(await Ge(k(n,r)).catch(()=>{}))?.isDirectory()&&t.push(r);return t.sort()}function W(n,e){return n<e?-1:n>e?1:0}export{K as a,Qe as b,et as c,tt as d,je as e,pe as f,G as g,ue as h,St as i,me as j,Ve as k,Ot as l};
11
+ `,"utf8")}catch(p){d=p instanceof Error?p.message:String(p)}})},u=async()=>{await i,o=!0,await w.rm(t,{force:!0})};return this.retiring.set(t,u),{writtenAs:g=>{N.test(g)&&(s=g)},created:(g,p)=>{let P=p.filter(([m,y])=>m!==""&&N.test(y));if(P.length!==0){a=!0;for(let m=0;m<P.length;m+=1e4)c({at:this.now().toISOString(),object:g,created:P.slice(m,m+1e4)})}},flush:async()=>(await i,d),close:async()=>{await i,this.retiring.delete(t),(o||!a)&&await w.rm(t,{force:!0}),o=!0,V.delete(t)}}}async stoppedLoads(e){let t;try{t=await w.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=`${this.journalStem}.load-`,o=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),a=[];for(let s of t){if(!s.startsWith(r)||!/^\d{1,16}\.ndjson$/.test(s.slice(r.length)))continue;let i=this.guard.assertOutsideRepo(O.join(this.sasDir,s));if(V.has(i))continue;let d;try{d=await w.readFile(i,"utf8")}catch{continue}let c=je(d);!c||o.has(c.startedAt)||c.pid!==process.pid&&Se(c.pid)||a.push({file:i,load:c.load})}return a}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let t=S(e);return[...t?[t]:[],...j(e)].map(r=>({mapping:new Map(Object.entries(r.mapping)),...r.created?{created:r.created}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},endedAt:A(r),...r.removalStamps?{removalStamps:r.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let t=typeof e.orgId=="string"?e.orgId:"",r=S(e);return[...r?[this.recordedOf(r,t)]:[],...j(e).map(o=>({...this.recordedOf(o,t),earlier:!0}))]}recordedOf(e,t){return{orgId:t,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:A(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let t=e.organizationId;if(t===void 0)return!1;let r=await this.currentOrganizationId();return r!==void 0&&!Ce(t,r)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await $(this.filePath);if(e!==void 0)return e;let t=this.singleFilePath;if(t===void 0)return;let r=await $(t);return r?.orgId===this.orgId?r:void 0}async readWithJournals(){let e=await this.readFile(),t=e?[S(e),...j(e)]:[],r=await this.stoppedLoads(t.filter(i=>i!==void 0));if(r.length===0)return{payload:e,journals:[]};let o=[...t.filter(i=>i!==void 0),...r.map(({load:i})=>i)].sort((i,d)=>Date.parse(A(d))-Date.parse(A(i))),[a,...s]=o;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...a,...s.length>0?{earlier:s}:{}},journals:r.map(({file:i})=>i)}}async dropJournals(e){for(let t of e)await w.rm(t,{force:!0}).catch(()=>{})}async write(e){let t=this.filePath;await w.mkdir(O.dirname(t),{recursive:!0}),await w.writeFile(t,`${JSON.stringify(e,null,2)}
12
+ `,"utf8");let r=this.singleFilePath;if(r!==void 0)try{(await $(r))?.orgId===this.orgId&&await w.rm(r)}catch{}}async keptLoads(e,t,r=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let o=new Set(t.map(v)),a=new Set(r),s=S(e);return[...s?[s]:[],...j(e)].map(i=>le(i,o)).filter(i=>ge(i)||a.has(A(i)))}async persist(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=t?.earlier?await this.keptLoads(r,t.earlier.settled,t.earlier.stillToSweep):[],s=await this.currentOrganizationId(),i=this.now().toISOString(),d=g=>Object.fromEntries(Object.entries(g??{}).filter(([p,P])=>e.has(p)&&e.has(P))),c=d(t?.personContacts),u=d(t?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:i,mapping:Object.fromEntries([...e.entries()].sort(([g],[p])=>g.localeCompare(p))),...t?{created:t.created.map(({objectApiName:g,referenceIds:p})=>({objectApiName:g,referenceIds:p.filter(P=>e.has(P))})).filter(g=>g.referenceIds.length>0),load:{startedAt:t.startedAt.toISOString(),endedAt:i},...t.writtenBetween?{writtenBetween:{...t.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(u).length>0?{withTheirRecord:u}:{},...t.runUserId?{runUserId:t.runUserId}:{}}:{},...a.length>0?{earlier:a}:{}}),t?.earlier&&await this.dropJournals(o),t){let g=this.journalPath(t.startedAt),p=this.retiring.get(g);p?await p():await w.rm(g,{force:!0}).catch(()=>{})}}async recordRemoval(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=S(r);if(r===void 0||a===void 0)return!1;let s=[a,...j(r)],i=s.findIndex(g=>A(g)===e);if(i<0)return!1;let d=new Set(t.gone.map(v)),[c,...u]=s.map((g,p)=>le(p===i?_e(g,t):g,d));return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...c,updatedAt:this.now().toISOString(),...u.length>0?{earlier:u}:{}}),await this.dropJournals(o),!0}async recordMade(e,t,r=[],o=[]){let{payload:a,journals:s}=await this.readWithJournals(),i=S(a);if(a===void 0||i===void 0)return!1;let d=[i,...j(a)],c=d.findIndex(m=>A(m)===e);if(c<0)return!1;let u=[...o],g=m=>{let y=pe(m.madeEarlier,t,u),z=pe(m.lateEarlier,r,u),C={...m};return delete C.madeEarlier,delete C.lateEarlier,{...C,...y.length>0?{madeEarlier:y}:{},...z.length>0?{lateEarlier:z}:{}}},[p,...P]=d.map((m,y)=>y===c?g(m):m);return await this.write({version:1,orgId:typeof a.orgId=="string"?a.orgId:"",...a.organizationId!==void 0?{organizationId:a.organizationId}:{},...p,...P.length>0?{earlier:P}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=new Set(e),s=j(t),i=s.filter(d=>ge(d)||!a.has(A(d)));return i.length===s.length?!1:(await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...o,...i.length>0?{earlier:i}:{}}),await this.dropJournals(r),!0)}async recordStamps(e){let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=[o,...j(t)],s=a.map(c=>Te(c,e));if(s.every((c,u)=>c===a[u]))return!1;let[i,...d]=s;return await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...i,...d.length>0?{earlier:d}:{}}),await this.dropJournals(r),!0}};function pe(n,e,t=[]){let r=new Map,o=new Set(t.map(v)),a=[];for(let s of[...n??[],...e]){let i=v(s),d=i.slice(0,3),c=r.get(d)??0;!N.test(s)||o.has(i)||c>=se||(o.add(i),r.set(d,c+1),a.push(s))}return a}function Te(n,e){let t=new Set(Object.values(n.mapping).map(v)),r=Object.entries(e).filter(([a])=>t.has(v(a)));if(r.length===0)return n;let o=new Set(r.map(([a])=>v(a)));return{...n,removalStamps:{...Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([a])=>!o.has(v(a)))),...Object.fromEntries(r)}}}function _e(n,e){let t={...n.removalStamps,...e.stamps},r=[...n.removalSpans??[],...e.span?[e.span]:[]],o=e.mark??n.removal;return{...n,...o?{removal:o}:{},...Object.keys(t).length>0?{removalStamps:t}:{},...r.length>0?{removalSpans:r}:{}}}var Ke="replays",fe="replay.json";function Ot(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?qe(e):k(Ze(),".sandforge");return k(t,Ke)}var H=ee.datetime({offset:!0}),Ve=f({organizationId:Z,name:l().min(1).max(255),choices:q,firstAt:H,lastAt:H}),Ie=f({version:x(1),checkpoint:f({checkpointId:J,name:l().min(1).max(255),organizationId:Z,alias:l().min(1).max(255).optional(),tier:_(["sandbox","scratch","developer"]),takenAt:H}),targets:I(Ve).max(1e4)}),me=/^00D[A-Za-z0-9]{15}$/,he=class{root;guard;now;writes=new Map;constructor(e){this.guard=e.guard??new B,this.root=this.guard.assertOutsideRepo(e.root),this.now=e.now??(()=>new Date)}folderOf(e,t){let r=E(e),o=J.safeParse(t);if(!o.success)throw new ne("invalid","Not a checkpoint\u2019s id");return{dir:this.guard.assertOutsideRepo(k(this.root,r,o.data)),sourceOrganizationId:r,checkpointId:o.data}}async record(e,t,r){let o=this.folderOf(e.org.organizationId,e.checkpointId),a=E(t.organizationId),s=q.parse(r);await re(o.dir);let i=k(o.dir,fe),d=async()=>{let g=this.now().toISOString(),p=await ye(i),P=p?.targets.find(y=>y.organizationId===a),m={version:1,checkpoint:{checkpointId:o.checkpointId,name:e.name,organizationId:o.sourceOrganizationId,...e.org.alias!==void 0?{alias:e.org.alias}:{},tier:e.org.tier,takenAt:e.takenAt},targets:[...p?.targets.filter(y=>y.organizationId!==a)??[],{organizationId:a,name:t.name,choices:s,firstAt:P?.firstAt??g,lastAt:g}]};await He(i,`${JSON.stringify(Ie.parse(m),null,2)}
13
+ `)},c=(this.writes.get(i)??Promise.resolve()).then(d,d),u=c.catch(()=>{});return this.writes.set(i,u),u.then(()=>{this.writes.get(i)===u&&this.writes.delete(i)}),await c,o}mappingStoreOf(e,t,r={}){return new G(e.dir,{guard:this.guard,orgId:E(t),...r})}async createdBy(e,t){let r=await this.mappingStoreOf(e,t).recorded();return r?.created===void 0?void 0:ae(r)}contractPathOf(e,t){return K(this.guard,e.dir,E(t))}async read(e){return ye(k(e.dir,fe))}async list(e={}){let t=e.sourceOrganizationId!==void 0?E(e.sourceOrganizationId):void 0,r=e.targetOrganizationId!==void 0?E(e.targetOrganizationId):void 0,o=[];for(let a of await we(this.root))if(!(!me.test(a)||t!==void 0&&a!==t))for(let s of await we(k(this.root,a))){if(!J.safeParse(s).success||e.checkpointId!==void 0&&s!==e.checkpointId)continue;let i=this.folderOf(a,s);o.push(...await this.entriesOf(i,r))}return o.sort((a,s)=>W(s.replayedAt??"",a.replayedAt??"")||W(a.checkpointId,s.checkpointId)||W(a.target.organizationId,s.target.organizationId))}async replaysOf(e,t){return this.list({sourceOrganizationId:e,checkpointId:t})}async entriesOf(e,t){let r=await this.read(e),o=new Map(r?.targets.map(d=>[d.organizationId,d])),a=(await ue(e.dir,this.guard)).filter(d=>me.test(d)),s=[...new Set([...o.keys(),...a])].filter(d=>t===void 0||d===t),i=[];for(let d of s){let c=o.get(d),u=await this.mappingStoreOf(e,d).recordedLoads(),g=new Map;for(let y of u)for(let{objectApiName:z,ids:C}of ie(y))g.set(z,(g.get(z)??0)+C.length);let p=[...g].map(([y,z])=>({objectApiName:y,records:z})).sort((y,z)=>W(y.objectApiName,z.objectApiName)),P=p.reduce((y,z)=>y+z.records,0),m=u.find(y=>y.earlier!==!0);i.push({sourceOrganizationId:e.sourceOrganizationId,checkpointId:e.checkpointId,...r?{checkpointName:r.checkpoint.name}:{},...r?{takenAt:r.checkpoint.takenAt}:{},target:{organizationId:d,...c?{name:c.name}:{}},...c?{choices:c.choices}:{},...m?{replayedAt:m.endedAt}:{},inPlace:P,inPlaceByObject:p,...m!==void 0&&P===0&&m.removal!==void 0?{removed:!0}:{}})}return i}};function Ye(n){return n.filter(e=>e.inPlace>0)}function bt(n){let e=Ye(n);if(e.length===0)return;let t=e.map(r=>`${r.inPlace.toLocaleString("en-US")} record${r.inPlace===1?"":"s"} in ${r.target.name??r.target.organizationId}`).join(", ");return`${e.length===1?"A replay":`${e.length} replays`} of it ${e.length===1?"is":"are"} still in place: ${t}. Deleting the checkpoint leaves them there, and each replay is still removed without it.`}async function ye(n){let e;try{e=await De(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}try{let t=Ie.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}async function He(n,e){let t=`${n}.${process.pid}-${Je(4).toString("hex")}.tmp`,r=await Be(t,"wx",te);try{try{await r.writeFile(e,"utf8"),await r.sync()}finally{await r.close()}await Ue(t,n)}catch(o){throw await Ge(t,{force:!0}),o}}async function we(n){let e;try{e=await $e(n)}catch(r){if(r.code==="ENOENT")return[];throw r}let t=[];for(let r of e)(await We(k(n,r)).catch(()=>{}))?.isDirectory()&&t.push(r);return t.sort()}function W(n,e){return n<e?-1:n>e?1:0}export{K as a,et as b,tt as c,rt as d,Ae as e,ue as f,G as g,fe as h,Ot as i,he as j,Ye as k,bt as l};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{nc as P,rc as v,uc as S}from"./chunk-KB4ZHM4Q.mjs";import{a as h,b as E}from"./chunk-VV3B6IC3.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Rd as m,be as A,ee as c}from"./chunk-PMWAFDUB.mjs";import{b,f,k as w,l as p}from"./chunk-WZQEK4WT.mjs";var k="Messaging.reserveSingleEmailCapacity(1);",M="System.NoAccessException: The organization is not permitted to send email",x=`/tooling/executeAnonymous?anonymousBody=${encodeURIComponent(k)}`,I=`/query?q=${encodeURIComponent("SELECT PermissionsEmailSingle FROM UserPermissionAccess")}`,L=3e4,$=p({compiled:f(),success:f(),compileProblem:b().nullish(),exceptionMessage:b().nullish()}).loose(),O=p({records:w(p({PermissionsEmailSingle:f().optional()}).loose())}).loose(),V={reading:{unread:"SandForge runs no Apex in a production org"},requests:0};function U(e){return e%1e3===0?`${e/1e3} s`:`${e} ms`}function T(e,n){return e instanceof h?`the org did not answer within ${U(n)}`:`the org refused it: ${R(e)}`}function _(e){let n=$.safeParse(e);if(!n.success)return{unread:"its answer is not one anonymous Apex gives"};let{compiled:r,success:s,compileProblem:t,exceptionMessage:i}=n.data;if(!r)return{unread:`it did not compile${t?`: ${t}`:""}`};if(s)return{level:"all"};let a=i?.trim();return a===M?{refused:!0}:{unread:a?`the org answered: ${a}`:"it failed, and the org did not say why"}}async function Y(e,n={}){let r=n.timeoutMs??L,s=u=>new E(r).withTimeout("forge:deliverability",()=>e.request({method:"GET",url:u})),t;try{t=await s(x)}catch(u){return{reading:{unread:T(u,r)},requests:1}}let i=_(t);if(!("refused"in i))return{reading:i,requests:1};let a="so the org's refusal does not say how it is set",d;try{d=await s(I)}catch(u){return{reading:{unread:`whether the user the run writes as may send email could not be read (${T(u,r)}), ${a}`},requests:2}}let l=O.safeParse(d),o=l.success?l.data.records[0]?.PermissionsEmailSingle:void 0;return o===!0?{reading:{level:"withheld"},requests:2}:{reading:{unread:o===!1?`the user the run writes as may not send email (Send Email), ${a}`:`the org did not say whether the user the run writes as may send email, ${a}`},requests:2}}async function F(e){let n=m(e.running,{applyAssignmentRules:e.applyAssignmentRules,writes:e.writes}),r=P(e.running.automation.unread??[],{applyAssignmentRules:e.applyAssignmentRules===!0}),s=r!==void 0?{sendersUnread:r}:{};if(n.length===0&&r===void 0)return{senders:n};let t;try{t=await e.read()}catch(i){t={reading:{unread:R(i)},requests:1}}return{senders:n,...s,read:t}}function N(e,n={}){if(e.cannotAssign===!0)return[];let r=i=>`${i.objectApiName}\0${i.kind}\0${i.name}`,s=m(c(e,void 0,n.writes),n),t=new Set(m(c(e,A(e,n.writes),n.writes),n).map(r));return s.filter(i=>!t.has(r(i)))}function q(e,n){let r=new Set([...n.assigned,...n.held]);return{assign:e.assign.filter(s=>r.has(s.permissionSet))}}var z=["flows","processes","workflowRules"];async function Q(e){let{plan:n,writes:r,applyAssignmentRules:s,read:t,target:i,run:a}=e,d=typeof t.unread=="string"?void 0:t,l=s===!0?{applyAssignmentRules:s}:{},o=await F({running:d?c(d,n,r):{automation:{objects:[],unread:z.map(y=>({part:y,reason:String(t.unread)}))},firing:[]},...l,writes:r,read:e.readDeliverability}),u=e.mayMute===!0&&n===void 0&&d!==void 0&&o.senders.length>0?N(d,{...l,writes:r}):[],g=o.read?.reading;return{ofRun:o,gate:v({senders:o.senders,...o.sendersUnread!==void 0?{sendersUnread:o.sendersUnread}:{},...g!==void 0?{reading:g}:{},accepted:e.accepted,target:i,run:a,muteQuiets:u,keepsAddresses:e.keepsAddresses===!0}),afterLease:(y,D)=>{if(!(n===void 0||d===void 0))return S({planned:o.senders,held:m(c(d,q(n,y),r),{...l,writes:r}),...g!==void 0?{reading:g}:{},accepted:D,target:i,run:a})}}}export{L as a,V as b,Y as c,F as d,N as e,q as f,Q as g};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{l as i}from"./chunk-XMQ5R6TC.mjs";function u(o,t){let n=e=>e==="production"?`${t} is taken for a production org, and this command writes to none`:void 0;return new i({requestConfirmation:(e,d)=>{let r=n(d);return r===void 0?Promise.resolve(!0):(o(`refused: ${r} (${e})`),Promise.resolve(!1))},declinesWithoutAsking:n})}export{u as a};
7
+ import{m as i}from"./chunk-VINGECAJ.mjs";function u(o,t){let n=e=>e==="production"?`${t} is taken for a production org, and this command writes to none`:void 0;return new i({requestConfirmation:(e,d)=>{let r=n(d);return r===void 0?Promise.resolve(!0):(o(`refused: ${r} (${e})`),Promise.resolve(!1))},declinesWithoutAsking:n})}export{u as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-QO53K5W2.mjs";import"./chunk-7YNM6KFZ.mjs";import"./chunk-H33DVU3D.mjs";import"./chunk-MDMPJEV3.mjs";import"./chunk-GMIGWR6U.mjs";import"./chunk-KGU4SVIT.mjs";import"./chunk-W6PN6TJG.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-S42RBRH2.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as RECOVERY_HANDOFF_DIR_MODE,b as RECOVERY_HANDOFF_FILE_MODE,c as RECOVERY_HANDOFF_FOLDER,d as journalDirOf,h as lastHandoffOf,g as newestHandoffOf,e as recoveryHandoffFolderOf,i as recoveryHandoffNoteOf,f as recoveryHandoffPathOf,j as writeRecoveryHandoff};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-PDRXM5WN.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as loadCreatedRecords,f as loadRecordsInfo,c as loadRecordsKept,b as loadRecordsLeft,d as loadToRemove,e as loadsSweptWith};
7
+ import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-Y2DRK37K.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as loadCreatedRecords,f as loadRecordsInfo,c as loadRecordsKept,b as loadRecordsLeft,d as loadToRemove,e as loadsSweptWith};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{wc as S,xc as O}from"./chunk-6QSHWIZI.mjs";import{b as y,f as b,l as R}from"./chunk-WZQEK4WT.mjs";var v=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],P=new Set(v.map(e=>e.toLowerCase())),W=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function B(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return P.has(n)||S(e)||t&&(t.has(e)||U(t).has(n))||r.byNamespace&&F.test(n)?!0:W.some(i=>n.endsWith(i))}var w=new WeakMap;function U(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function z(e,t){return O(e)||B(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function le(e,t=r=>z(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(i=>t(i))}).map(r=>r.name))}var ge=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",H="ContentDocumentLink",G="ContentVersion",L="Attachment",J=[D,L],K={AccountContactRelation:["Contact"]},V=new Set(["feeditem","feedcomment","feedattachment"]),X=new Set(["casehistory2"]),Y=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),Q=new Set([G,H].map(e=>e.toLowerCase())),Z=["__b","__x","__dlm","__kav","__ka","__e"],$=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function q(e,t,r,n,i){let o=e.name.toLowerCase();return V.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||X.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Z.some(c=>o.endsWith(c))?"unsupportedKind":e.customSetting===!0?n?A(e,i)?void 0:"notWritable":"customSetting":Q.has(o)?"heldWithFiles":o===D.toLowerCase()?(i==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,i)?void 0:"notWritable":S(e.name)?"files":Y.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!$.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,i)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):ee(e)}function ee(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var te="all";function ne(e){return e.customSetting===!0}function oe(e,t){let r=e.filter(ne);if(t===void 0)return{held:new Set,unknown:[]};if(t===te)return{held:new Set(r.map(c=>c.name.toLowerCase())),unknown:[]};let n=new Set(r.map(c=>c.name.toLowerCase())),i=new Set,o=[];for(let c of t){let p=c.toLowerCase();i.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?i.add(p):o.push(c))}return{held:i,unknown:o}}function he(e,t,r=[]){let n=t.access??"write",i=n==="delete"?r:x(e,r),o={out:new Set([...i].map(a=>a.toLowerCase())),tooling:new Set(r.map(a=>a.toLowerCase()))},c=new Set((t.excluded??[]).map(a=>a.toLowerCase())),p=new Map(e.map(a=>[a.name.toLowerCase(),a])),u=oe(e,t.customSettings),h=u.unknown.map(a=>({objectApiName:a,reason:"notCustomSetting"})),g=[],f=[],s=[];if(t.mode==="picked"){let a=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(a.has(l))continue;a.add(l);let m=p.get(l);m?f.push(m):h.push({objectApiName:d,reason:"notFound"})}for(let d of J){let l=d.toLowerCase(),m=p.get(l);if(!(a.has(l)||m===void 0)){if(c.has(l)){h.push({objectApiName:m.name,reason:"excludedByUser"});continue}f.push(m),s.push(m.name)}}for(let[d,l]of Object.entries(K)){let m=d.toLowerCase(),C=p.get(m);if(!(a.has(m)||C===void 0)&&l.some(j=>a.has(j.toLowerCase()))){if(a.add(m),c.has(m)){h.push({objectApiName:C.name,reason:"excludedByUser"});continue}f.push(C)}}for(let d of u.held){let l=p.get(d);a.has(d)||l===void 0||(a.add(d),f.push(l))}}else f.push(...p.values());for(let a of f){let d=a.name.toLowerCase(),l=c.has(d)?"excludedByUser":q(a,o,t.mode,u.held.has(d),n);l===void 0?g.push(a.name):h.push({objectApiName:a.name,reason:l})}return g.sort(),h.sort(k),{mode:t.mode,candidates:g,leftOut:h,addedToPicked:s}}function be(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function Ce(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function Se(e){return e.objects.some(t=>t.customSetting!==void 0)}function re(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var se=()=>({first:"child",firmness:0});function ie(e,t,r=se){let n=new Map(e.map((o,c)=>[o.toLowerCase(),c])),i=e.map(()=>new Map);return e.forEach((o,c)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===c)continue;let h=r(p);if(h===void 0)continue;let[g,f]=h.first==="child"?[u,c]:[c,u],s=i[g].get(f);(s===void 0||h.firmness>s)&&i[g].set(f,h.firmness)}}),N(e.map((o,c)=>c),i,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),i=f=>[...t[f]].filter(([s,a])=>n.has(s)&&a>r).map(([s])=>s),o=ae(e,i,t.length),c=new Map;o.forEach((f,s)=>{for(let a of f)c.set(a,s)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let s=c.get(f)??0;for(let a of i(f)){let d=c.get(a)??0;d===s||u[s].has(d)||(u[s].add(d),p[d]++)}}let h=o.map(()=>!1),g=[];for(let f=o.length;f>0;f--){let s=-1;for(let d=0;d<o.length;d++){if(h[d]||p[d]>0)continue;let l=o[d].length===1,m=s>=0&&o[s].length===1;(s<0||l&&!m||l===m&&o[d][0]<o[s][0])&&(s=d)}h[s]=!0;let a=o[s];if(a.length===1)g.push(a[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of a)for(let[m,C]of t[l])C>r&&c.get(m)===s&&C<d&&(d=C);g.push(...N(a,t,d))}for(let d of u[s])p[d]--}return g}function ae(e,t,r){let n=new Array(r).fill(-1),i=new Array(r).fill(0),o=new Array(r).fill(!1),c=[],p=[],u=0;for(let h of e){if(n[h]>=0)continue;let g=[],f=s=>{n[s]=u,i[s]=u,u++,c.push(s),o[s]=!0,g.push({node:s,edges:t(s),at:0})};for(f(h);g.length>0;){let s=g[g.length-1];if(s.at<s.edges.length){let l=s.edges[s.at++];n[l]<0?f(l):o[l]&&(i[s.node]=Math.min(i[s.node],n[l]));continue}g.pop();let a=g[g.length-1];if(a&&(i[a.node]=Math.min(i[a.node],i[s.node])),i[s.node]!==n[s.node])continue;let d=[];for(let l=c.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==s.node);l=c.pop());p.push(d.sort((l,m)=>l-m))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function ce(e,t){return ie(e,t).map((r,n)=>{let i=re(r);return{objectApiName:r,readOrder:n,...i===void 0?{}:{namespace:i}}})}function ye(e,t,r=new Map){let n=[...e.leftOut],i=[];for(let c of e.candidates){let p=t.get(c);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?i.push(c):n.push({objectApiName:c,reason:"noRecycleBin"}):n.push({objectApiName:c,reason:"noSystemModstamp"});else{let u=r.get(c);n.push({objectApiName:c,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=ce(i,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Oe(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let i of e.objects){let o=t.get(i.objectApiName);o===void 0?n.push({...i,readOrder:n.length}):r.push({objectApiName:i.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{B as a,z as b,E as c,x as d,le as e,ge as f,D as g,H as h,G as i,L as j,J as k,te as l,ne as m,he as n,be as o,Ce as p,Se as q,re as r,ie as s,ye as t,Oe as u};
7
+ import{wc as S,xc as O}from"./chunk-PMWAFDUB.mjs";import{b as y,f as b,l as R}from"./chunk-WZQEK4WT.mjs";var v=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],P=new Set(v.map(e=>e.toLowerCase())),W=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function B(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return P.has(n)||S(e)||t&&(t.has(e)||U(t).has(n))||r.byNamespace&&F.test(n)?!0:W.some(i=>n.endsWith(i))}var w=new WeakMap;function U(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function z(e,t){return O(e)||B(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function le(e,t=r=>z(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(i=>t(i))}).map(r=>r.name))}var ge=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",H="ContentDocumentLink",G="ContentVersion",L="Attachment",J=[D,L],K={AccountContactRelation:["Contact"]},V=new Set(["feeditem","feedcomment","feedattachment"]),X=new Set(["casehistory2"]),Y=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),Q=new Set([G,H].map(e=>e.toLowerCase())),Z=["__b","__x","__dlm","__kav","__ka","__e"],$=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function q(e,t,r,n,i){let o=e.name.toLowerCase();return V.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||X.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Z.some(c=>o.endsWith(c))?"unsupportedKind":e.customSetting===!0?n?A(e,i)?void 0:"notWritable":"customSetting":Q.has(o)?"heldWithFiles":o===D.toLowerCase()?(i==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,i)?void 0:"notWritable":S(e.name)?"files":Y.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!$.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,i)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):ee(e)}function ee(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var te="all";function ne(e){return e.customSetting===!0}function oe(e,t){let r=e.filter(ne);if(t===void 0)return{held:new Set,unknown:[]};if(t===te)return{held:new Set(r.map(c=>c.name.toLowerCase())),unknown:[]};let n=new Set(r.map(c=>c.name.toLowerCase())),i=new Set,o=[];for(let c of t){let p=c.toLowerCase();i.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?i.add(p):o.push(c))}return{held:i,unknown:o}}function he(e,t,r=[]){let n=t.access??"write",i=n==="delete"?r:x(e,r),o={out:new Set([...i].map(a=>a.toLowerCase())),tooling:new Set(r.map(a=>a.toLowerCase()))},c=new Set((t.excluded??[]).map(a=>a.toLowerCase())),p=new Map(e.map(a=>[a.name.toLowerCase(),a])),u=oe(e,t.customSettings),h=u.unknown.map(a=>({objectApiName:a,reason:"notCustomSetting"})),g=[],f=[],s=[];if(t.mode==="picked"){let a=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(a.has(l))continue;a.add(l);let m=p.get(l);m?f.push(m):h.push({objectApiName:d,reason:"notFound"})}for(let d of J){let l=d.toLowerCase(),m=p.get(l);if(!(a.has(l)||m===void 0)){if(c.has(l)){h.push({objectApiName:m.name,reason:"excludedByUser"});continue}f.push(m),s.push(m.name)}}for(let[d,l]of Object.entries(K)){let m=d.toLowerCase(),C=p.get(m);if(!(a.has(m)||C===void 0)&&l.some(j=>a.has(j.toLowerCase()))){if(a.add(m),c.has(m)){h.push({objectApiName:C.name,reason:"excludedByUser"});continue}f.push(C)}}for(let d of u.held){let l=p.get(d);a.has(d)||l===void 0||(a.add(d),f.push(l))}}else f.push(...p.values());for(let a of f){let d=a.name.toLowerCase(),l=c.has(d)?"excludedByUser":q(a,o,t.mode,u.held.has(d),n);l===void 0?g.push(a.name):h.push({objectApiName:a.name,reason:l})}return g.sort(),h.sort(k),{mode:t.mode,candidates:g,leftOut:h,addedToPicked:s}}function be(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function Ce(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function Se(e){return e.objects.some(t=>t.customSetting!==void 0)}function re(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var se=()=>({first:"child",firmness:0});function ie(e,t,r=se){let n=new Map(e.map((o,c)=>[o.toLowerCase(),c])),i=e.map(()=>new Map);return e.forEach((o,c)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===c)continue;let h=r(p);if(h===void 0)continue;let[g,f]=h.first==="child"?[u,c]:[c,u],s=i[g].get(f);(s===void 0||h.firmness>s)&&i[g].set(f,h.firmness)}}),N(e.map((o,c)=>c),i,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),i=f=>[...t[f]].filter(([s,a])=>n.has(s)&&a>r).map(([s])=>s),o=ae(e,i,t.length),c=new Map;o.forEach((f,s)=>{for(let a of f)c.set(a,s)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let s=c.get(f)??0;for(let a of i(f)){let d=c.get(a)??0;d===s||u[s].has(d)||(u[s].add(d),p[d]++)}}let h=o.map(()=>!1),g=[];for(let f=o.length;f>0;f--){let s=-1;for(let d=0;d<o.length;d++){if(h[d]||p[d]>0)continue;let l=o[d].length===1,m=s>=0&&o[s].length===1;(s<0||l&&!m||l===m&&o[d][0]<o[s][0])&&(s=d)}h[s]=!0;let a=o[s];if(a.length===1)g.push(a[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of a)for(let[m,C]of t[l])C>r&&c.get(m)===s&&C<d&&(d=C);g.push(...N(a,t,d))}for(let d of u[s])p[d]--}return g}function ae(e,t,r){let n=new Array(r).fill(-1),i=new Array(r).fill(0),o=new Array(r).fill(!1),c=[],p=[],u=0;for(let h of e){if(n[h]>=0)continue;let g=[],f=s=>{n[s]=u,i[s]=u,u++,c.push(s),o[s]=!0,g.push({node:s,edges:t(s),at:0})};for(f(h);g.length>0;){let s=g[g.length-1];if(s.at<s.edges.length){let l=s.edges[s.at++];n[l]<0?f(l):o[l]&&(i[s.node]=Math.min(i[s.node],n[l]));continue}g.pop();let a=g[g.length-1];if(a&&(i[a.node]=Math.min(i[a.node],i[s.node])),i[s.node]!==n[s.node])continue;let d=[];for(let l=c.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==s.node);l=c.pop());p.push(d.sort((l,m)=>l-m))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function ce(e,t){return ie(e,t).map((r,n)=>{let i=re(r);return{objectApiName:r,readOrder:n,...i===void 0?{}:{namespace:i}}})}function ye(e,t,r=new Map){let n=[...e.leftOut],i=[];for(let c of e.candidates){let p=t.get(c);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?i.push(c):n.push({objectApiName:c,reason:"noRecycleBin"}):n.push({objectApiName:c,reason:"noSystemModstamp"});else{let u=r.get(c);n.push({objectApiName:c,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=ce(i,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Oe(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let i of e.objects){let o=t.get(i.objectApiName);o===void 0?n.push({...i,readOrder:n.length}):r.push({objectApiName:i.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{B as a,z as b,E as c,x as d,le as e,ge as f,D as g,H as h,G as i,L as j,J as k,te as l,ne as m,he as n,be as o,Ce as p,Se as q,re as r,ie as s,ye as t,Oe as u};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{m as d}from"./chunk-JBWJ6UEZ.mjs";var r=".my.salesforce.com",o=/^[a-z0-9-]+--[a-z0-9]+$/,s="scratch";function c(n){if(n===void 0||n==="")return;let e;try{e=new URL(n).hostname.toLowerCase()}catch{return}return e.endsWith(r)&&e.length>r.length?e:void 0}function t(n){if(n===void 0||!n.endsWith(r))return;let e=n.slice(0,-r.length).split(".");return e.every(i=>i!=="")?e:void 0}function a(n){return t(n)?.slice(1).includes(s)===!0}function f(n){let e=t(n);if(e===void 0||e.length>2||a(n))return;let[i]=e;return i!==void 0&&o.test(i)?i:void 0}function g(n,e){return t(n)?.[0]===e}function l(n,e){return n.kind!=="sandbox"||e.kind!=="sandbox"||n.host===void 0||f(e.host)===void 0||n.organizationId.slice(0,15)===e.organizationId.slice(0,15)?!1:d({tier:"sandbox",organizationId:n.organizationId,username:n.username??"",instanceUrl:`https://${n.host}`},{name:e.organizationId,organizationId:e.organizationId,instanceUrl:`https://${e.host??""}`})==="myDomain"}export{c as a,a as b,f as c,g as d,l as e};
7
+ import{m as d}from"./chunk-GMIGWR6U.mjs";var r=".my.salesforce.com",o=/^[a-z0-9-]+--[a-z0-9]+$/,s="scratch";function c(n){if(n===void 0||n==="")return;let e;try{e=new URL(n).hostname.toLowerCase()}catch{return}return e.endsWith(r)&&e.length>r.length?e:void 0}function t(n){if(n===void 0||!n.endsWith(r))return;let e=n.slice(0,-r.length).split(".");return e.every(i=>i!=="")?e:void 0}function a(n){return t(n)?.slice(1).includes(s)===!0}function f(n){let e=t(n);if(e===void 0||e.length>2||a(n))return;let[i]=e;return i!==void 0&&o.test(i)?i:void 0}function g(n,e){return t(n)?.[0]===e}function l(n,e){return n.kind!=="sandbox"||e.kind!=="sandbox"||n.host===void 0||f(e.host)===void 0||n.organizationId.slice(0,15)===e.organizationId.slice(0,15)?!1:d({tier:"sandbox",organizationId:n.organizationId,username:n.username??"",instanceUrl:`https://${n.host}`},{name:e.organizationId,organizationId:e.organizationId,instanceUrl:`https://${e.host??""}`})==="myDomain"}export{c as a,a as b,f as c,g as d,l as e};