sandforge 1.79.0 → 1.81.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 (256) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/chunk-2OIRJEYE.mjs +7 -0
  5. package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-SIOZXPFG.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/chunk-5WGA5CZB.mjs +7 -0
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/chunk-67CC7RAE.mjs +7 -0
  26. package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-AUTM6H6Z.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-OTWRDD6L.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-XBG5SP6Q.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/chunk-DHGPDSXS.mjs +7 -0
  48. package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/chunk-DQR5NDMI.mjs +7 -0
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/chunk-E2OBAWSH.mjs +7 -0
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/chunk-EAFLDSQ2.mjs +7 -0
  56. package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/chunk-FTA5LOVX.mjs +7 -0
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/chunk-HVC5CYIB.mjs +7 -0
  73. package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-IAZB4WIL.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/chunk-L5FGY6YA.mjs +7 -0
  90. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  91. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  92. package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
  93. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  94. package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
  95. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  96. package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
  97. package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
  98. package/lib/chunk-MO3N5XVV.mjs +341 -0
  99. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  100. package/lib/chunk-MWLFFVQV.mjs +8 -0
  101. package/lib/chunk-N6HHNR6J.mjs +7 -0
  102. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  103. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  104. package/lib/chunk-NWPQF5XR.mjs +7 -0
  105. package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
  106. package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
  107. package/lib/chunk-O7DAFE6M.mjs +14 -0
  108. package/lib/chunk-OEHVAJAB.mjs +7 -0
  109. package/lib/chunk-OETEC3P7.mjs +7 -0
  110. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  111. package/lib/chunk-OIIL4NVI.mjs +7 -0
  112. package/lib/chunk-OMZJ37JI.mjs +15 -0
  113. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
  114. package/lib/chunk-OQQHNYR7.mjs +272 -0
  115. package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
  116. package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
  117. package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  118. package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
  119. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  120. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  121. package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  122. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  123. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  124. package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
  125. package/lib/chunk-R2BJWO5N.mjs +20 -0
  126. package/lib/chunk-R6TF26V4.mjs +10 -0
  127. package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
  128. package/lib/chunk-SQGP46QS.mjs +7 -0
  129. package/lib/chunk-SU65Z2BA.mjs +7 -0
  130. package/lib/chunk-SW2NUKQL.mjs +9 -0
  131. package/lib/chunk-T26C576X.mjs +9 -0
  132. package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  133. package/lib/chunk-T5VAULLQ.mjs +7 -0
  134. package/lib/chunk-TEIBWMJM.mjs +7 -0
  135. package/lib/chunk-TKQQVB2D.mjs +9 -0
  136. package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
  137. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  138. package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
  139. package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  140. package/lib/chunk-UIUPPEFB.mjs +7 -0
  141. package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
  142. package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
  143. package/lib/chunk-V2QO6KOE.mjs +19 -0
  144. package/lib/chunk-V473C7LY.mjs +7 -0
  145. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  146. package/lib/chunk-VSU74RQ3.mjs +9 -0
  147. package/lib/chunk-VV3B6IC3.mjs +7 -0
  148. package/lib/chunk-W2AAGIZF.mjs +7 -0
  149. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  150. package/lib/chunk-WD47PGUS.mjs +10 -0
  151. package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
  152. package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
  153. package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
  154. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  155. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  156. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  157. package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
  158. package/lib/chunk-XC54KKKC.mjs +7 -0
  159. package/lib/chunk-XEB6HZ34.mjs +7 -0
  160. package/lib/chunk-XGKSSCW7.mjs +7 -0
  161. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  162. package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  163. package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
  164. package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
  165. package/lib/chunk-YIGFYZQY.mjs +7 -0
  166. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  167. package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  170. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  171. package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
  172. package/lib/sandforge-autopilot.mjs +29 -24
  173. package/lib/sandforge-backup.mjs +67 -32
  174. package/lib/sandforge-checkpoint.mjs +1 -347
  175. package/lib/sandforge-cleanup.mjs +14 -10
  176. package/lib/sandforge-clone.mjs +1 -1
  177. package/lib/sandforge-compare.mjs +9 -8
  178. package/lib/sandforge-dataops.mjs +1 -1
  179. package/lib/sandforge-empty.mjs +15 -15
  180. package/lib/sandforge-env.mjs +101 -101
  181. package/lib/sandforge-frozen.mjs +1 -257
  182. package/lib/sandforge-mcp.mjs +33 -14
  183. package/lib/sandforge-monitor.mjs +7 -7
  184. package/lib/sandforge-pipeline.mjs +88 -0
  185. package/lib/sandforge-seed.mjs +1 -1
  186. package/lib/sandforge-sync.mjs +1 -1
  187. package/lib/sandforge.mjs +6 -6
  188. package/package.json +2 -1
  189. package/lib/chunk-2S5OMIIA.mjs +0 -7
  190. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  191. package/lib/chunk-3F5YMM2F.mjs +0 -7
  192. package/lib/chunk-3RYLICRX.mjs +0 -7
  193. package/lib/chunk-42RER7V4.mjs +0 -14
  194. package/lib/chunk-4GL773D5.mjs +0 -7
  195. package/lib/chunk-4HFRHFGQ.mjs +0 -7
  196. package/lib/chunk-4U6NXJNL.mjs +0 -7
  197. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  198. package/lib/chunk-5AJRHRXA.mjs +0 -20
  199. package/lib/chunk-5HMAPZBV.mjs +0 -7
  200. package/lib/chunk-5P4PHJRL.mjs +0 -9
  201. package/lib/chunk-5QKTYCWE.mjs +0 -11
  202. package/lib/chunk-6LAXTAVN.mjs +0 -7
  203. package/lib/chunk-6MUEPV7M.mjs +0 -9
  204. package/lib/chunk-6QSM2WIH.mjs +0 -10
  205. package/lib/chunk-75ADZS6B.mjs +0 -7
  206. package/lib/chunk-ALJVEUUS.mjs +0 -7
  207. package/lib/chunk-ALUFROGA.mjs +0 -7
  208. package/lib/chunk-B45CNPUX.mjs +0 -47
  209. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  210. package/lib/chunk-CGWXQX75.mjs +0 -7
  211. package/lib/chunk-D3QRXG63.mjs +0 -787
  212. package/lib/chunk-EEVVGGM6.mjs +0 -7
  213. package/lib/chunk-ENLBYECD.mjs +0 -7
  214. package/lib/chunk-EQOQASDQ.mjs +0 -7
  215. package/lib/chunk-FQBRBBY4.mjs +0 -7
  216. package/lib/chunk-GAM726CK.mjs +0 -7
  217. package/lib/chunk-HJC7AIBK.mjs +0 -7
  218. package/lib/chunk-HUMEKZT5.mjs +0 -8
  219. package/lib/chunk-I3JKJTLO.mjs +0 -110
  220. package/lib/chunk-I7O6C2B5.mjs +0 -8
  221. package/lib/chunk-KLX67VPL.mjs +0 -7
  222. package/lib/chunk-L776PUMV.mjs +0 -7
  223. package/lib/chunk-LRFAIUN7.mjs +0 -7
  224. package/lib/chunk-LV6G4XTK.mjs +0 -7
  225. package/lib/chunk-MYTIL2JD.mjs +0 -10
  226. package/lib/chunk-NEVXIGR6.mjs +0 -10
  227. package/lib/chunk-NGSMZZDA.mjs +0 -7
  228. package/lib/chunk-NHWE66K5.mjs +0 -7
  229. package/lib/chunk-OQOZAPCI.mjs +0 -7
  230. package/lib/chunk-PA3MKJVH.mjs +0 -7
  231. package/lib/chunk-QROPNEGY.mjs +0 -14
  232. package/lib/chunk-QWT2C74M.mjs +0 -7
  233. package/lib/chunk-RH3N2H7P.mjs +0 -7
  234. package/lib/chunk-SRQDABQ2.mjs +0 -15
  235. package/lib/chunk-SVS6UMDU.mjs +0 -323
  236. package/lib/chunk-TNXUU6W7.mjs +0 -14
  237. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  238. package/lib/chunk-VXHDBYMI.mjs +0 -7
  239. package/lib/chunk-WJY54JO7.mjs +0 -13
  240. package/lib/chunk-WRU5FJFC.mjs +0 -7
  241. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  242. package/lib/chunk-XEFDB2R4.mjs +0 -7
  243. package/lib/chunk-XETCPL7E.mjs +0 -7
  244. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  245. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  246. package/lib/chunk-YMJVMFPY.mjs +0 -7
  247. package/lib/chunk-YPSRZRIT.mjs +0 -7
  248. package/lib/chunk-YS4G22C2.mjs +0 -7
  249. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  250. package/lib/chunk-Z7X534S4.mjs +0 -10
  251. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  252. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  253. package/lib/chunk-ZPYJPGDK.mjs +0 -7
  254. package/lib/chunk-ZQOZ4EFW.mjs +0 -7
  255. package/lib/chunk-ZUTYVST5.mjs +0 -7
  256. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -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{k as be}from"./chunk-TBZMC2VV.mjs";import{a as ge,c as B,d as we}from"./chunk-LQ4DRFUH.mjs";import{b as fe,e as pe,i as me,j as D,l as S}from"./chunk-57VHUYNG.mjs";import{b as se}from"./chunk-KLX67VPL.mjs";import{g as P,j as te,l as T,m as ie,p as ne}from"./chunk-342FN7AO.mjs";import{A as ce,B as le,C as ue,w as ae,y as de}from"./chunk-Z7X534S4.mjs";import{$ as re}from"./chunk-6QSM2WIH.mjs";import{v as I,y as oe}from"./chunk-NEVXIGR6.mjs";import{u as ee}from"./chunk-6MUEPV7M.mjs";import{e as X}from"./chunk-OTWRDD6L.mjs";import{s as Z}from"./chunk-VXHDBYMI.mjs";import{g as V,h as Y,i as q,q as Q}from"./chunk-PA3MKJVH.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{Vc as J}from"./chunk-B45CNPUX.mjs";var ve="No record would be read or written.";function je(t,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${t} is being taken`:e.operation==="rewind"?`A rewind is writing to ${t}`:e.operation==="undo"?`An undo is writing to ${t}`:e.operation==="empty"?`An emptying of its objects is writing to ${t}`:`SandForge is deleting checkpoints of ${t}`} (process ${e.pid} on ${e.host}): rewind once it has ended. ${ve}`}}function Ae(t){return{query:e=>t.query(e),queryMore:e=>t.queryMore(e)}}function Ee(t){let e=t.objects.find(r=>r.objectApiName===V);if(e===void 0)return 0;let n=e.toBringBack;return n.inBin+n.withParent+n.deletedWhileTaken}function Pe(t,e){return{objectsRead:[...t],objects:[],unread:["flows","triggers","processes","workflowRules"].map(n=>({part:n,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Te(t,e){let n=new Map,r;return{bodies:n,global:()=>r,describeGlobal:()=>r??=t.describeGlobal(),reader:{lane:()=>e.lane(),tooling:i=>e.tooling(i),calls:()=>e.calls(),describe:async(i,a)=>{let d=await e.describe(i,a);return"body"in d&&n.set(i,d.body),d}}}}async function Je(t,e){let{org:n,signal:r}=t,{checkpoint:i,orgName:a}=e,d,p=await se(Ae(n),{act:"preview",orgName:a,registered:e.registered,username:e.username,organizationId:i.org.organizationId,customSettings:Q(i)},{userId:async()=>d=await n.userId()});if(!p.allowed)return{previewed:!1,refusal:p.refusal};let m=await ce(n,a),g=Te(n,re(n,r)),ke=await fe({grants:p.grants,...d!==void 0?{userId:d}:{},username:e.username,checkpoint:i,reader:g.reader}),h=await n.serverTime(),R=oe("pv",(t.now??(()=>new Date))()),c=await pe({checkpoint:i,folder:e.folder,reader:g.reader,describeGlobal:g.describeGlobal,previewId:R,readAt:h,queryAllFiles:p.queryAllFiles,access:ke,...r?{signal:r}:{}}),O=m.fileStorage;c.files!==void 0&&O!==void 0&&(c.files.storage.remaining=O.remaining*1048576);let w=e.objects!==void 0?new Set(e.objects):void 0,l=me(c,w),b=ge(l),F=w===void 0&&i.scope.mode==="picked"&&c.objects.some(o=>o.outside.length>0),ye=F&&e.acceptOutside===!1,y;if(w!==void 0||ye){y=await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,...w!==void 0?{objects:w}:{},acceptOutside:e.acceptOutside===!0,heldRows:D(i,e.folder),...r?{signal:r}:{}});for(let{objectApiName:o}of y.acts)b.includes(o)||b.push(o)}let s;if(b.length>0&&t.readAutomation)try{s=await t.readAutomation(b)}catch(o){s=Pe(b,K(o))}let C,k=0,G=y?B(c,y):l,v=we(G),u=s&&e.muteAutomation===!0?ee(s,J(v)):void 0,j=s&&u&&u.plan.assign.length>0&&t.mute?await be(t.mute,s,v):void 0,he=j&&"refusal"in j?j.refusal:void 0;if(s){let o=await ne({act:"rewind",orgName:a,automation:s,steps:v,...u?{plan:u.plan}:{},accepted:!1,mayMute:u===void 0,read:()=>Z(n)});C=o.gate.deliverability,k=o.ofRun.read?.requests??0}let M=g.global(),N=M?new Set((await X({describeGlobal:()=>M})).keys()):void 0,W=new Set(i.objects.map(({objectApiName:o})=>o.toLowerCase()));if(i.files!==void 0)for(let o of[Y,q])W.add(o.toLowerCase());let _=new Map;for(let[o,Oe]of g.bodies)_.set(o,ae(Oe,{inCheckpoint:W,...N?{worked:N}:{}}));let L=de({objects:i.objects,diff:l,automationRequests:s?.requests??0,...k>0?{deliverabilityRequests:k}:{},relationships:_,...e.reusesPreview===!0?{reusesPreview:!0}:{}}),Re={...L,apiRequestsLeft:m.remaining},$=P(G.objects),f=u?.automation??s,A=f?T($,f,m.emails):[],x=f?te($,f):void 0,U=F&&e.acceptOutside===void 0&&f?T(P(B(c,await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,acceptOutside:!1,heldRows:D(i,e.folder),...r?{signal:r}:{}})).objects),f,m.emails):void 0,E=t.store.heldBy(i.org.organizationId),z=E===void 0?await t.runWriting?.(p.org.id):void 0,H=E!==void 0?je(a,E):z!==void 0?{code:"RUN_WRITING",message:z}:he??le("rewind",{run:L.apiRequests-k,deliverability:k},m,a)??ie("rewind",A,a)??(l.files!==void 0?ue("rewind",{files:Ee(l),bytes:l.files.storage.bringBack},O?.remaining,a):void 0);return{previewed:!0,diff:c,...s?{automation:s}:{},...A.length>0?{emails:A}:{},...U?{emailsKeepingOutside:U}:{},...x!==void 0?{emailsUncounted:x}:{},...C?{deliverability:C}:{},estimate:Re,...H?{refusal:H}:{}}}export{Je as a};
7
+ import{k as be}from"./chunk-YCSFP6ER.mjs";import{a as ge,c as B,d as we}from"./chunk-GYKNCYES.mjs";import{b as fe,e as pe,i as me,j as D,l as S}from"./chunk-YOGMP72T.mjs";import{b as ue}from"./chunk-YIGFYZQY.mjs";import{g as P,j as te,l as T,m as ie,p as ne}from"./chunk-GWRKS3AL.mjs";import{A as ce,B as le,v as se,x as ae,z as de}from"./chunk-6SEDOIO3.mjs";import{j as oe}from"./chunk-ETT5GP4P.mjs";import{A as re,x as I}from"./chunk-E2YJVSX6.mjs";import{v as ee}from"./chunk-T26C576X.mjs";import{e as X}from"./chunk-BNO5GIJ6.mjs";import{c as Z}from"./chunk-6IGEASOF.mjs";import{g as V,h as Y,i as q,q as Q}from"./chunk-EAFLDSQ2.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{zd as J}from"./chunk-DPYTG6DM.mjs";var ve="No record would be read or written.";function je(t,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${t} is being taken`:e.operation==="rewind"?`A rewind is writing to ${t}`:e.operation==="undo"?`An undo is writing to ${t}`:e.operation==="empty"?`An emptying of its objects is writing to ${t}`:`SandForge is deleting checkpoints of ${t}`} (process ${e.pid} on ${e.host}): rewind once it has ended. ${ve}`}}function Ae(t){return{query:e=>t.query(e),queryMore:e=>t.queryMore(e)}}function Ee(t){let e=t.objects.find(r=>r.objectApiName===V);if(e===void 0)return 0;let n=e.toBringBack;return n.inBin+n.withParent+n.deletedWhileTaken}function Pe(t,e){return{objectsRead:[...t],objects:[],unread:["flows","triggers","processes","workflowRules"].map(n=>({part:n,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Te(t,e){let n=new Map,r;return{bodies:n,global:()=>r,describeGlobal:()=>r??=t.describeGlobal(),reader:{lane:()=>e.lane(),tooling:i=>e.tooling(i),calls:()=>e.calls(),describe:async(i,a)=>{let d=await e.describe(i,a);return"body"in d&&n.set(i,d.body),d}}}}async function Je(t,e){let{org:n,signal:r}=t,{checkpoint:i,orgName:a}=e,d,p=await ue(Ae(n),{act:"preview",orgName:a,registered:e.registered,username:e.username,organizationId:i.org.organizationId,customSettings:Q(i)},{userId:async()=>d=await n.userId()});if(!p.allowed)return{previewed:!1,refusal:p.refusal};let m=await de(n,a),g=Te(n,oe(n,r)),ke=await fe({grants:p.grants,...d!==void 0?{userId:d}:{},username:e.username,checkpoint:i,reader:g.reader}),h=await n.serverTime(),R=re("pv",(t.now??(()=>new Date))()),c=await pe({checkpoint:i,folder:e.folder,reader:g.reader,describeGlobal:g.describeGlobal,previewId:R,readAt:h,queryAllFiles:p.queryAllFiles,access:ke,...r?{signal:r}:{}}),O=m.fileStorage;c.files!==void 0&&O!==void 0&&(c.files.storage.remaining=O.remaining*1048576);let w=e.objects!==void 0?new Set(e.objects):void 0,l=me(c,w),b=ge(l),F=w===void 0&&i.scope.mode==="picked"&&c.objects.some(o=>o.outside.length>0),ye=F&&e.acceptOutside===!1,y;if(w!==void 0||ye){y=await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,...w!==void 0?{objects:w}:{},acceptOutside:e.acceptOutside===!0,heldRows:D(i,e.folder),...r?{signal:r}:{}});for(let{objectApiName:o}of y.acts)b.includes(o)||b.push(o)}let s;if(b.length>0&&t.readAutomation)try{s=await t.readAutomation(b)}catch(o){s=Pe(b,K(o))}let C,k=0,G=y?B(c,y):l,v=we(G),u=s&&e.muteAutomation===!0?ee(s,J(v)):void 0,j=s&&u&&u.plan.assign.length>0&&t.mute?await be(t.mute,s,v):void 0,he=j&&"refusal"in j?j.refusal:void 0;if(s){let o=await ne({act:"rewind",orgName:a,automation:s,steps:v,...u?{plan:u.plan}:{},accepted:!1,mayMute:u===void 0,read:()=>Z(n)});C=o.gate.deliverability,k=o.ofRun.read?.requests??0}let M=g.global(),N=M?new Set((await X({describeGlobal:()=>M})).keys()):void 0,W=new Set(i.objects.map(({objectApiName:o})=>o.toLowerCase()));if(i.files!==void 0)for(let o of[Y,q])W.add(o.toLowerCase());let _=new Map;for(let[o,Oe]of g.bodies)_.set(o,se(Oe,{inCheckpoint:W,...N?{worked:N}:{}}));let L=ae({objects:i.objects,diff:l,automationRequests:s?.requests??0,...k>0?{deliverabilityRequests:k}:{},relationships:_,...e.reusesPreview===!0?{reusesPreview:!0}:{}}),Re={...L,apiRequestsLeft:m.remaining},$=P(G.objects),f=u?.automation??s,A=f?T($,f,m.emails):[],x=f?te($,f):void 0,U=F&&e.acceptOutside===void 0&&f?T(P(B(c,await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,acceptOutside:!1,heldRows:D(i,e.folder),...r?{signal:r}:{}})).objects),f,m.emails):void 0,E=t.store.heldBy(i.org.organizationId),z=E===void 0?await t.runWriting?.(p.org.id):void 0,H=E!==void 0?je(a,E):z!==void 0?{code:"RUN_WRITING",message:z}:he??ce("rewind",{run:L.apiRequests-k,deliverability:k},m,a)??ie("rewind",A,a)??(l.files!==void 0?le("rewind",{files:Ee(l),bytes:l.files.storage.bringBack},O?.remaining,a):void 0);return{previewed:!0,diff:c,...s?{automation:s}:{},...A.length>0?{emails:A}:{},...U?{emailsKeepingOutside:U}:{},...x!==void 0?{emailsUncounted:x}:{},...C?{deliverability:C}:{},estimate:Re,...H?{refusal:H}:{}}}export{Je as a};
@@ -4,8 +4,8 @@ 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{e as ds,f as cs}from"./chunk-LQ4DRFUH.mjs";import{a as es,b as ts,c as ye,d as ns,e as ss,f as rt,g as rs,h as is,i as os,j as as}from"./chunk-57VHUYNG.mjs";import{i as ls,l as us}from"./chunk-5O6JOMHS.mjs";import{b as Yn}from"./chunk-HUMEKZT5.mjs";import{a as jt,b as $n,c as we,d as Lt,e as Nt,f as zn,g as Wn,m as _n}from"./chunk-MYTIL2JD.mjs";import{d as Ot,e as Ne,k as Pt,m as et}from"./chunk-JVL444U5.mjs";import{b as qn}from"./chunk-KLX67VPL.mjs";import{a as Xn,b as Qn}from"./chunk-H45UXY6G.mjs";import{a as Cn,b as Fn}from"./chunk-5P4PHJRL.mjs";import{Ac as Rn,vc as Ze,zc as bn}from"./chunk-YMJVMFPY.mjs";import{a as wn,b as mn,c as yn,e as Ye,f as kn}from"./chunk-ALJVEUUS.mjs";import{a as It,d as In,f as On,h as Pn,j as An,k as jn,l as Xe,m as Ln,p as Nn,q as Bn}from"./chunk-342FN7AO.mjs";import{A as Kn,B as Hn,C as Vn,a as hn,w as Gn,x as Jn}from"./chunk-Z7X534S4.mjs";import{$ as At,J as vt,K as fn,N as pn,P as Ve,_ as $e,ga as Dn,ia as tt,la as Mn,ma as nt,pa as E,sa as Ce,ua as xn}from"./chunk-6QSM2WIH.mjs";import{t as Se,x as Be,y as Un,z as st}from"./chunk-WJY54JO7.mjs";import{E as H,J as En,d as Qe,g as Tn,v as Me,w as je,x as Le,y as Ue}from"./chunk-NEVXIGR6.mjs";import{l as gn}from"./chunk-NTDN2JQZ.mjs";import{a as Rt,b as un}from"./chunk-SAR5622P.mjs";import{s as St,u as Sn}from"./chunk-6MUEPV7M.mjs";import{C as cn}from"./chunk-HJC7AIBK.mjs";import{b as Y,d as ge,e as ln}from"./chunk-OTWRDD6L.mjs";import{Ba as Zn,s as vn}from"./chunk-VXHDBYMI.mjs";import{g as Ae,h as ne,i as an,q as dn}from"./chunk-PA3MKJVH.mjs";import{i as He}from"./chunk-INIT2UKJ.mjs";import{ca as Ke,ia as rn,ja as on}from"./chunk-CGWXQX75.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{Kc as sn,Sc as kt,Tb as nn,Vc as bt,ra as Qt,ta as Je,ua as en,vb as tn}from"./chunk-B45CNPUX.mjs";import{b as X,e as Yt,f as De,i as yt,k as le,l as _,o as Ge,p as Zt,u as Pe,v as Z,z as Xt}from"./chunk-7EANH5PY.mjs";import{randomBytes as Us}from"node:crypto";import{rm as $s}from"node:fs/promises";import{join as zs}from"node:path";var ar=5,dr="005",cr=new Set(["001"]),Bt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",it="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function ue(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function Fe(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)ot(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ot(i,e){i.length<ar&&!i.includes(e)&&i.push(e)}var lr=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function ur(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=lr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:a,id:o,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,f=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(l=>l).join(": ")).filter(u=>u!=="").join("; ");return{success:a,...typeof o=="string"?{id:o}:{},...p!==void 0?{code:p}:{},...f!==""?{words:f}:{}}})}function fr(i){let e=[];for(let t=0;t<i.length;t+=Y)e.push(i.slice(t,t+Y));return e}async function Ct(i,e,t,n){let s=ue();for(let r of fr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let a=ur(await t(r),r.length),o={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=a[c],f=n(p);if(f==="done"){s.done++,o.done.push(d),p.id!==void 0&&o.made.push({from:d.Id,id:p.id});return}if(o.left.push(d.Id),f==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ot(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...o.made),await e.after?.(o)}return s}function ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ot(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function at(i,e,t={}){let n=ue(),s=ps(e,a=>a.LinkedEntityId?.startsWith(dr)===!0,Bt,n),r=await Ct(s,t,a=>i.destroy(ne,a.map(o=>o.Id)),a=>a.success?"done":a.code==="ENTITY_IS_DELETED"||a.code==="NOT_FOUND"?"already":"refused");return Fe(r,n),r}async function dt(i,e,t={},n=s=>s){return Ct(e,t,s=>i.create(ne,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function ct(i,e,t={}){let n=d=>cr.has(d.LinkedEntityId.slice(0,3)),s=ue(),r=new Map,a=ps(e,d=>d.Visibility===d.now.Visibility&&n(d),it,s);for(let d of a){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ot(s.reasons,it),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let o=await Ct(a,t,d=>i.update(ne,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return Fe(s,o),s}import{randomBytes as ks}from"node:crypto";import{closeSync as pr,createReadStream as bs,fsyncSync as hr,openSync as gr,readFileSync as wr,renameSync as mr,writeSync as yr}from"node:fs";import{open as ut,readdir as Rs,rm as vs,stat as kr,truncate as Ss}from"node:fs/promises";import{dirname as Is,join as ee}from"node:path";import{createInterface as Os}from"node:readline";var Te="journal.ndjson",br="before.json",J=2e3,Ps=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Tt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),be=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),V=Xt.datetime({offset:!0}),ae=le(Ps).min(1).max(J),As=Yt().int().positive(),js=_({kind:Z("head"),version:Z(1),rewindId:Je,checkpointId:Qt,organizationId:en,startedAt:V,userId:Tt,automatedProcessUserId:Tt.optional(),backup:X().min(1).max(200),at:V}),Rr=_({kind:Z("resumed"),startedAt:V,userId:Tt,at:V}),vr=_({kind:Pe(["bringingBack","withParent","givingBack"]),objectApiName:be,ids:ae,parents:ae.optional(),carriers:Z(!0).optional(),at:V}),Sr=_({kind:Z("bringBackLeft"),objectApiName:be,ids:ae,at:V}),Ir=_({kind:Z("recreating"),objectApiName:be,ids:ae,at:V}),Or=_({kind:Z("recreated"),objectApiName:be,ids:ae,from:ae,at:V}),Pr=_({kind:Pe(["deleting","deleteLeft"]),step:As,objectApiName:be,ids:ae,at:V}),Ar=_({kind:Z("heldInPlace"),objectApiName:be,by:le(be).min(1).max(100),ids:ae,at:V}),jr=_({kind:Z("beforeParent"),objectApiName:be,ids:ae,parents:ae,at:V}),Lr=_({kind:Z("deleted"),step:As,at:V}),Nr=_({kind:Z("removal"),state:yt(),at:V}),Br=_({kind:Z("unlinking"),links:le(we).min(1).max(J),at:V}),Cr=_({kind:Pe(["unlinkLeft","linksUpdateLeft"]),ids:ae,at:V}),Fr=_({kind:Z("relinked"),ids:ae,from:ae,at:V}),Ls=we.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),Tr=_({kind:Z("linksUpdating"),links:le(Ls).min(1).max(J),at:V}),Er=_({kind:Z("linksUndone"),part:Pe(["reinserted","removed","shared"]),ids:ae,at:V}),Dr=_({kind:Z("wrote"),at:V}),Mr=_({kind:Z("end"),at:V}),Ur=_({kind:Z("undo"),state:yt(),status:Pe(["success","partial","failure","cancelled"]),at:V}),$r=Zt("kind",[js,Rr,vr,Sr,Ar,jr,Ir,Or,Pr,Lr,Nr,Br,Cr,Fr,Tr,Er,Dr,Mr,Ur]),zr=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Et(i){let e;try{e=await ut(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ut(i,e){let t=await ut(i,"a",Qe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Wr(i,e){let t=`${i}.${process.pid}-${ks(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=gr(t,"wx",Qe);try{for(let r=0;r<n.length;)r+=yr(s,n,r,n.length-r);hr(s)}finally{pr(s)}mr(t,i)}function _r(i){let e=[];try{let n=JSON.parse(wr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,Wr(i,`${JSON.stringify({version:1,openings:e})}
8
- `)}}}function W(i){return i.slice(0,15)}function pe(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*qr(i){if(!fn(i)){for(let{objectApiName:e,ids:t}of i)t.length>0&&(yield{objectApiName:e,ids:[...t]});return}for(let{objectApiName:e}of i.objects)for await(let t of i.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}var lt=class i{constructor(e,t,n,s,r,a){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=a;this.rewindId=e.rewindId,this.backup=e.backup;let o=new Set,d=new Fn({...Cn(t),appendFile:async(p,f)=>{await Ut(p,f),o.has(p)||(o.add(p),await Et(Is(p)))}}),c={begin:()=>Le(ee(t,"backups")),append:(p,f,u)=>d.append(p,f,u)};if(this.kept=Qn({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:_r(ee(t,br)),now:a}),this.kept.id!==e.backup)throw new H("damaged","The rewind\u2019s journal names another backup of its values than the one they are kept in.");this.values=d,this.keep=async(p,f)=>{await this.kept.keep(p,f);let u=f.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);for(let l of pe(u))await this.append({kind:"givingBack",objectApiName:p,ids:l})}}dir;resumed;handle;step;now;keep;values;queue=Promise.resolve();closed=!1;openStep;kept;rewindId;backup;static async opened(e,t,n,s,r){let a=await ut(ee(e,Te),"a",Qe);try{return new i(t,e,n,a,s,r)}catch(o){throw await a.close(),o}}append(e){if(this.closed)return Promise.reject(new Error("The rewind\u2019s journal is closed."));let t=`${JSON.stringify({...e,at:this.now().toISOString()})}
9
- `,n=this.queue.then(async()=>{await this.handle.appendFile(t,"utf8"),await this.handle.sync()});return this.queue=n.catch(()=>{}),n}async appendIds(e,t,n,s=!1){for(let r of pe(n))await this.append({kind:e,objectApiName:t,ids:r,...s?{carriers:s}:{}})}bringingBack(e,t,n={}){let s=new Map;for(let{objectApiName:r,ids:a}of e){let[o]=a;o!==void 0&&s.set(o.slice(0,3),r)}return async r=>{let a=new Set(r.map(d=>s.get(d.slice(0,3)))),[o]=[...a];if(a.size!==1||o===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",o,r,n.carriers===!0),t(r)}}async withParent(e,t,n,s={}){let r=s.carriers===!0;if(n===void 0){await this.appendIds("withParent",e,t,r);return}if(n.length!==t.length)throw new Error("Each record that comes back with a parent is named beside that parent.");for(let a=0;a<t.length;a+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(a,a+J),parents:n.slice(a,a+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of pe(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of pe(n))await this.append({kind:"heldInPlace",objectApiName:e,by:[...t],ids:s})}async beforeParent(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"beforeParent",objectApiName:e,ids:s.map(({id:r})=>r),parents:s.map(({parent:r})=>r)})}}async recreating(e,t){for(let n of pe(t))await this.append({kind:"recreating",objectApiName:e,ids:n})}async recreated(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"recreated",objectApiName:e,ids:s.map(({id:r})=>r),from:s.map(({from:r})=>r)})}}async deleting(e){let t=++this.step;this.openStep=t;for await(let{objectApiName:n,ids:s}of qr(e))for(let r of pe(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async deleted(e){let t=this.openStep;if(t===void 0)throw new Error("No removal was named to the journal before it.");for await(let{objectApiName:n,ids:s}of e.left())for(let r of pe(s))await this.append({kind:"deleteLeft",step:t,objectApiName:n,ids:r});await this.append({kind:"deleted",step:t}),this.openStep=void 0}async removal(e){let t={...e.removalStamps&&Object.keys(e.removalStamps).length>0?{removalStamps:e.removalStamps}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:e.removalSpans}:{}};Object.keys(t).length!==0&&await this.append({kind:"removal",state:{version:1,...t}})}async unlinking(e){for(let t=0;t<e.length;t+=J)await this.append({kind:"unlinking",links:e.slice(t,t+J)})}async unlinkLeft(e){for(let t of pe(e))await this.append({kind:"unlinkLeft",ids:t})}async relinked(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J);await this.append({kind:"relinked",ids:n.map(({id:s})=>s),from:n.map(({from:s})=>s)})}}async linksUpdating(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J).map(s=>({Id:s.Id,LinkedEntityId:s.LinkedEntityId,ShareType:s.ShareType,Visibility:s.Visibility}));await this.append({kind:"linksUpdating",links:n})}}async linksUpdateLeft(e){for(let t of pe(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of pe(t))await this.append({kind:"linksUndone",part:e,ids:n})}async wrote(){await this.append({kind:"wrote"})}async end(){await this.append({kind:"end"})}async undone(e,t){await this.append({kind:"undo",state:{version:1,...e},status:t})}async read(){return await this.queue,Ns(ee(this.dir,Te))}async facts(){return await this.queue,Gr(ee(this.dir,Te))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ke(i,e){let t=(await kr(i)).size,n=t===0;if(t>0){let p=await ut(i,"r");try{let f=Buffer.alloc(1);await p.read(f,0,1,t-1),n=f[0]===10}finally{await p.close()}}let s=0,r=0,a=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let f;try{f=JSON.parse(p)}catch{f=void 0}let u=$r.safeParse(f);if(!u.success)throw new H("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);xr(u.data),s++,await e(u.data)},o=bs(i,{encoding:"utf8"}),d=Os({input:o,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await a(c),c=p}finally{d.close(),o.destroy()}return c!==void 0&&n&&await a(c),{count:s,whole:r,size:t}}function xr(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names links inserted again without the links they stand for.");if(i.kind==="recreated"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records deleted before a parent without their parent.");if((i.kind==="withParent"||i.kind==="bringingBack")&&i.parents!==void 0&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var he=class{byObject=new Map;add(e,t){let n=this.byObject.get(e)??new Map;for(let s of t)n.has(W(s))||n.set(W(s),s);this.byObject.set(e,n)}drop(e,t){let n=this.byObject.get(e);if(n)for(let s of t)n.delete(W(s))}list(e=()=>!0){return[...this.byObject].flatMap(([t,n])=>{let s=[...n].filter(([r])=>e(r)).map(([,r])=>r);return s.length>0?[{objectApiName:t,ids:s}]:[]})}keys(){return new Set([...this.byObject.values()].flatMap(e=>[...e.keys()]))}};function hs(i){let e={};for(let t of i)e={...e,...t,...t.removalStamps||e.removalStamps?{removalStamps:{...e.removalStamps,...t.removalStamps}}:{},...t.removalSpans||e.removalSpans?{removalSpans:[...e.removalSpans??[],...t.removalSpans??[]]}:{}};return e}function gs(i){let e=gn(i);if(e===void 0)throw new H("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var ze=class{head;step=0;passes=[];rewindStates=[];undoStates=[];undos=[];lastWrite=Number.NEGATIVE_INFINITY;endedAt;line(e){if(this.head===void 0){if(e.kind!=="head")throw new H("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(zr.has(e.kind)&&(this.lastWrite=Math.max(this.lastWrite,Date.parse(e.at))),"step"in e&&(this.step=Math.max(this.step,e.step)),e.kind){case"head":throw new H("damaged","The rewind\u2019s journal has two heads.");case"resumed":this.passes.push({startedAt:e.startedAt,userId:e.userId});break;case"removal":this.rewindStates.push(gs(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(gs(e.state)),this.undos.push({status:e.status,at:e.at});break;default:break}}result(){let e=this.head;if(e===void 0)throw new H("damaged","The rewind\u2019s journal does not begin with its head.");return{head:{rewindId:e.rewindId,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:e.startedAt,userId:e.userId,...e.automatedProcessUserId!==void 0?{automatedProcessUserId:e.automatedProcessUserId}:{},backup:e.backup},passes:this.passes,...Number.isFinite(this.lastWrite)?{lastWriteAt:new Date(this.lastWrite).toISOString()}:{},...this.endedAt!==void 0?{endedAt:this.endedAt}:{},rewind:hs(this.rewindStates),undo:hs(this.undoStates),undos:this.undos}}},Dt=class{broughtBack=new he;recreated=new he;carriers=new he;carried=new Map;givenBack=new he;held=new he;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new he,left:new Set,answered:!1},this.steps.set(e,t)),t}line(e){switch(e.kind){case"bringingBack":case"withParent":this.broughtBack.add(e.objectApiName,e.ids),e.carriers===!0&&e.kind==="bringingBack"&&this.carriers.add(e.objectApiName,e.ids),e.parents?.forEach((t,n)=>{let s=e.ids[n],r=e.carriers===!0?this.carried:this.withParents;r.has(W(s))||r.set(W(s),{objectApiName:e.objectApiName,id:s,parent:t})});break;case"bringBackLeft":this.broughtBack.drop(e.objectApiName,e.ids),this.carriers.drop(e.objectApiName,e.ids);for(let t of e.ids)this.withParents.delete(W(t)),this.carried.delete(W(t));break;case"givingBack":this.givenBack.add(e.objectApiName,e.ids);break;case"recreated":this.recreated.add(e.objectApiName,e.ids);break;case"heldInPlace":{this.held.add(e.objectApiName,e.ids);let t=this.heldBy.get(e.objectApiName)??new Set;for(let n of e.by)t.add(n);this.heldBy.set(e.objectApiName,t);break}case"beforeParent":e.ids.forEach((t,n)=>{this.beforeParent.push({objectApiName:e.objectApiName,id:t,parent:e.parents[n]})});break;case"deleting":this.stepOf(e.step).deleting.add(e.objectApiName,e.ids);break;case"deleteLeft":for(let t of e.ids)this.stepOf(e.step).left.add(W(t));break;case"deleted":this.stepOf(e.step).answered=!0;break;default:break}}result(){let e=new he;for(let{deleting:u,left:l,answered:h}of this.steps.values())for(let{objectApiName:g,ids:w}of u.list(y=>!h||!l.has(y)))e.add(g,w);let t=this.held.list().map(({objectApiName:u,ids:l})=>({objectApiName:u,ids:l,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new he;for(let{objectApiName:u,id:l,parent:h}of this.beforeParent){let g=W(h);n.has(W(l))&&(n.has(g)||!s.has(g))&&r.add(u,[l])}let a=r.list(),o=u=>{let l=new Map;for(let{objectApiName:h,id:g,parent:w}of u){let y=l.get(h)??{objectApiName:h,ids:[],parents:[]};y.ids.push(g),y.parents.push(w),l.set(h,y)}return[...l.values()]},d=o(this.withParents.values()),c=o(this.carried.values()),p=this.carriers.list(),f=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...a.length>0?{deletedBeforeParent:a}:{},...d.length>0?{withParents:d}:{},...f.length>0?{recreated:f}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function Ns(i){let e=new ze,t=new Dt;try{await ke(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof H?n:new H("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function Gr(i){let e=new ze;try{await ke(i,t=>e.line(t))}catch(t){throw t instanceof H?t:new H("notFound","No journal of this rewind is kept.")}return e.result()}function Jr(i,e,t){if(i.head.rewindId!==t||i.head.checkpointId!==e.checkpointId||i.head.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function wo(i,e){let t=await We(i,e);if(!t)throw new H("notFound","No journal of this rewind is kept.");return Ns(t.file)}function Bs(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function We(i,e){let t=je(i,e),n=ee(t,Te),s=new ze,r;try{r=await ke(n,o=>s.line(o))}catch(o){if(o instanceof H)throw o;return}if(r.count===0||s.head===void 0)return;let a=s.result();return Jr(a,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:a}}async function Cs(i,e){return i.whole<i.size&&await Ss(i.file,i.whole),lt.opened(i.dir,i.head,!0,i.step,e)}var ws=18;async function Kr(i){let e;try{e=(await Rs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&Je.safeParse(n.name).success).map(n=>n.name).sort().reverse()}catch{return[]}let[t]=e;return t===void 0?[]:e.filter(n=>n.slice(0,ws)===t.slice(0,ws))}async function Fs(i){let{folder:e}=i;Bs(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await Kr(e)){let c=await We(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Cs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(f){throw await p.close(),f}return p}let s=n??Ue("rw",t()),r=je(e,s);await Le(r),await Le(ee(r,"backups")),await Ss(ee(r,Te),0).catch(()=>{});let a=js.safeParse({kind:"head",version:1,rewindId:s,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:i.startedAt,userId:i.userId,...i.automatedProcessUserId!==void 0?{automatedProcessUserId:i.automatedProcessUserId}:{},backup:Xn(s),at:t().toISOString()});if(!a.success)throw new H("invalid",`Not a rewind to journal: ${a.error.message}`);let o=await lt.opened(r,a.data,!1,0,t);try{await o.append(a.data),await Et(r),await Et(e.rewindsDir)}catch(d){throw await o.close(),d}return o}async function Ts(i,e,t,n=()=>new Date){Bs(t,i);let s=await We(i,e);if(!s)throw new H("notFound","No journal of this rewind is kept.");return Cs(s,n)}async function Es(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=En(n),r=[],a=[...n].sort((o,d)=>o.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:o,checkpoint:d}of a){if(d===void 0)continue;let c;try{c=(await Rs(o.rewindsDir,{withFileTypes:!0})).filter(f=>f.isDirectory()&&Je.safeParse(f.name).success).map(f=>f.name).sort()}catch{continue}let p=(f,u)=>u?.checkpointId===o.checkpointId&&u.rewindId===f;for(let f of c){if(p(f,t)||p(f,s))continue;let u=await We(o,f).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await vs(je(o,f),{recursive:!0,force:!0}),r.push({checkpointId:o.checkpointId,name:d.name,rewindId:f}))}}return r}var Mt=class i{constructor(e,t,n){this.dir=e;this.objects=t;this.keys=n}dir;objects;keys;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async written(e,t){await Le(e);let n=new E,s=new Map,r=new Map,a=async o=>{let d=r.get(o)??[];d.length!==0&&(await Ut(ms(e,o),d.join("")),r.set(o,[]))};await t(async(o,{id:d,parent:c})=>{if(!n.add(d))return;s.set(o,(s.get(o)??0)+1);let p=r.get(o)??[];p.push(`${d} ${c}
7
+ import{e as ds,f as cs}from"./chunk-GYKNCYES.mjs";import{a as es,b as ts,c as ye,d as ns,e as ss,f as rt,g as rs,h as is,i as os,j as as}from"./chunk-YOGMP72T.mjs";import{i as ls,l as us}from"./chunk-6CDIIFNX.mjs";import{c as Yn}from"./chunk-MWLFFVQV.mjs";import{b as Vn}from"./chunk-YIGFYZQY.mjs";import{a as jt,b as Gn,c as we,d as Lt,e as Nt,f as Jn,g as Kn,m as Hn}from"./chunk-R6TF26V4.mjs";import{d as Pt,f as Ce,l as At,n as tt}from"./chunk-JU2XEKEO.mjs";import{a as Xn,b as Qn}from"./chunk-K55LH4ZQ.mjs";import{Bc as bn,Cc as Rn,xc as Ze}from"./chunk-CAFUNR6D.mjs";import{a as wn,b as mn,c as yn,e as Ye,f as kn,h as Wn,i as _n}from"./chunk-AITNZWLB.mjs";import{a as It,d as In,f as On,h as Pn,j as An,k as jn,l as Xe,m as Ln,p as Nn,q as Bn}from"./chunk-GWRKS3AL.mjs";import{A as $n,B as zn,a as hn,v as Dn,w as Mn,z as Un}from"./chunk-6SEDOIO3.mjs";import{J as vt,K as fn,N as pn,P as Ve}from"./chunk-ZWCRWF7E.mjs";import{a as Rt,b as un}from"./chunk-54HYHHVL.mjs";import{l as gn}from"./chunk-MNITSYI2.mjs";import{B as nt,E as xn,F as st,i as Me,j as Ot,l as Se,p as Ne,q as Tn,r as et,z as qn}from"./chunk-ETT5GP4P.mjs";import{b as E,e as Be,g as En}from"./chunk-SW2NUKQL.mjs";import{A as $e,H,N as Fn,d as Qe,g as Cn,x as Ue,y as je,z as Le}from"./chunk-E2YJVSX6.mjs";import{t as St,v as Sn}from"./chunk-T26C576X.mjs";import{b as Y,d as ge,e as ln}from"./chunk-BNO5GIJ6.mjs";import{c as vn}from"./chunk-6IGEASOF.mjs";import{fc as Zn}from"./chunk-KOQV4WXC.mjs";import{i as He}from"./chunk-INIT2UKJ.mjs";import{E as cn}from"./chunk-XEB6HZ34.mjs";import{da as Ke,ja as rn,ka as on}from"./chunk-55LQD3Y3.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{g as Ae,h as ne,i as an,q as dn}from"./chunk-EAFLDSQ2.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{Ra as Qt,Ta as Je,Ua as en,Yb as tn,od as sn,vc as nn,wd as kt,zd as bt}from"./chunk-DPYTG6DM.mjs";import{b as X,e as Yt,f as De,i as yt,k as le,l as _,o as Ge,p as Zt,u as Pe,v as Z,z as Xt}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Us}from"node:crypto";import{rm as $s}from"node:fs/promises";import{join as zs}from"node:path";var ar=5,dr="005",cr=new Set(["001"]),Bt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",it="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function ue(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function Fe(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)ot(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ot(i,e){i.length<ar&&!i.includes(e)&&i.push(e)}var lr=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function ur(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=lr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:a,id:o,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,f=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(l=>l).join(": ")).filter(u=>u!=="").join("; ");return{success:a,...typeof o=="string"?{id:o}:{},...p!==void 0?{code:p}:{},...f!==""?{words:f}:{}}})}function fr(i){let e=[];for(let t=0;t<i.length;t+=Y)e.push(i.slice(t,t+Y));return e}async function Ct(i,e,t,n){let s=ue();for(let r of fr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let a=ur(await t(r),r.length),o={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=a[c],f=n(p);if(f==="done"){s.done++,o.done.push(d),p.id!==void 0&&o.made.push({from:d.Id,id:p.id});return}if(o.left.push(d.Id),f==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ot(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...o.made),await e.after?.(o)}return s}function ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ot(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function at(i,e,t={}){let n=ue(),s=ps(e,a=>a.LinkedEntityId?.startsWith(dr)===!0,Bt,n),r=await Ct(s,t,a=>i.destroy(ne,a.map(o=>o.Id)),a=>a.success?"done":a.code==="ENTITY_IS_DELETED"||a.code==="NOT_FOUND"?"already":"refused");return Fe(r,n),r}async function dt(i,e,t={},n=s=>s){return Ct(e,t,s=>i.create(ne,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function ct(i,e,t={}){let n=d=>cr.has(d.LinkedEntityId.slice(0,3)),s=ue(),r=new Map,a=ps(e,d=>d.Visibility===d.now.Visibility&&n(d),it,s);for(let d of a){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ot(s.reasons,it),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let o=await Ct(a,t,d=>i.update(ne,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return Fe(s,o),s}import{randomBytes as ks}from"node:crypto";import{closeSync as pr,createReadStream as bs,fsyncSync as hr,openSync as gr,readFileSync as wr,renameSync as mr,writeSync as yr}from"node:fs";import{open as ut,readdir as Rs,rm as vs,stat as kr,truncate as Ss}from"node:fs/promises";import{dirname as Is,join as ee}from"node:path";import{createInterface as Os}from"node:readline";var Te="journal.ndjson",br="before.json",J=2e3,Ps=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Tt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),be=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),V=Xt.datetime({offset:!0}),ae=le(Ps).min(1).max(J),As=Yt().int().positive(),js=_({kind:Z("head"),version:Z(1),rewindId:Je,checkpointId:Qt,organizationId:en,startedAt:V,userId:Tt,automatedProcessUserId:Tt.optional(),backup:X().min(1).max(200),at:V}),Rr=_({kind:Z("resumed"),startedAt:V,userId:Tt,at:V}),vr=_({kind:Pe(["bringingBack","withParent","givingBack"]),objectApiName:be,ids:ae,parents:ae.optional(),carriers:Z(!0).optional(),at:V}),Sr=_({kind:Z("bringBackLeft"),objectApiName:be,ids:ae,at:V}),Ir=_({kind:Z("recreating"),objectApiName:be,ids:ae,at:V}),Or=_({kind:Z("recreated"),objectApiName:be,ids:ae,from:ae,at:V}),Pr=_({kind:Pe(["deleting","deleteLeft"]),step:As,objectApiName:be,ids:ae,at:V}),Ar=_({kind:Z("heldInPlace"),objectApiName:be,by:le(be).min(1).max(100),ids:ae,at:V}),jr=_({kind:Z("beforeParent"),objectApiName:be,ids:ae,parents:ae,at:V}),Lr=_({kind:Z("deleted"),step:As,at:V}),Nr=_({kind:Z("removal"),state:yt(),at:V}),Br=_({kind:Z("unlinking"),links:le(we).min(1).max(J),at:V}),Cr=_({kind:Pe(["unlinkLeft","linksUpdateLeft"]),ids:ae,at:V}),Fr=_({kind:Z("relinked"),ids:ae,from:ae,at:V}),Ls=we.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),Tr=_({kind:Z("linksUpdating"),links:le(Ls).min(1).max(J),at:V}),Er=_({kind:Z("linksUndone"),part:Pe(["reinserted","removed","shared"]),ids:ae,at:V}),Dr=_({kind:Z("wrote"),at:V}),Mr=_({kind:Z("end"),at:V}),Ur=_({kind:Z("undo"),state:yt(),status:Pe(["success","partial","failure","cancelled"]),at:V}),$r=Zt("kind",[js,Rr,vr,Sr,Ar,jr,Ir,Or,Pr,Lr,Nr,Br,Cr,Fr,Tr,Er,Dr,Mr,Ur]),zr=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Et(i){let e;try{e=await ut(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ut(i,e){let t=await ut(i,"a",Qe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Wr(i,e){let t=`${i}.${process.pid}-${ks(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=gr(t,"wx",Qe);try{for(let r=0;r<n.length;)r+=yr(s,n,r,n.length-r);hr(s)}finally{pr(s)}mr(t,i)}function _r(i){let e=[];try{let n=JSON.parse(wr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,Wr(i,`${JSON.stringify({version:1,openings:e})}
8
+ `)}}}function W(i){return i.slice(0,15)}function pe(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*qr(i){if(!fn(i)){for(let{objectApiName:e,ids:t}of i)t.length>0&&(yield{objectApiName:e,ids:[...t]});return}for(let{objectApiName:e}of i.objects)for await(let t of i.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}var lt=class i{constructor(e,t,n,s,r,a){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=a;this.rewindId=e.rewindId,this.backup=e.backup;let o=new Set,d=new _n({...Wn(t),appendFile:async(p,f)=>{await Ut(p,f),o.has(p)||(o.add(p),await Et(Is(p)))}}),c={begin:()=>Le(ee(t,"backups")),append:(p,f,u)=>d.append(p,f,u)};if(this.kept=Qn({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:_r(ee(t,br)),now:a}),this.kept.id!==e.backup)throw new H("damaged","The rewind\u2019s journal names another backup of its values than the one they are kept in.");this.values=d,this.keep=async(p,f)=>{await this.kept.keep(p,f);let u=f.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);for(let l of pe(u))await this.append({kind:"givingBack",objectApiName:p,ids:l})}}dir;resumed;handle;step;now;keep;values;queue=Promise.resolve();closed=!1;openStep;kept;rewindId;backup;static async opened(e,t,n,s,r){let a=await ut(ee(e,Te),"a",Qe);try{return new i(t,e,n,a,s,r)}catch(o){throw await a.close(),o}}append(e){if(this.closed)return Promise.reject(new Error("The rewind\u2019s journal is closed."));let t=`${JSON.stringify({...e,at:this.now().toISOString()})}
9
+ `,n=this.queue.then(async()=>{await this.handle.appendFile(t,"utf8"),await this.handle.sync()});return this.queue=n.catch(()=>{}),n}async appendIds(e,t,n,s=!1){for(let r of pe(n))await this.append({kind:e,objectApiName:t,ids:r,...s?{carriers:s}:{}})}bringingBack(e,t,n={}){let s=new Map;for(let{objectApiName:r,ids:a}of e){let[o]=a;o!==void 0&&s.set(o.slice(0,3),r)}return async r=>{let a=new Set(r.map(d=>s.get(d.slice(0,3)))),[o]=[...a];if(a.size!==1||o===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",o,r,n.carriers===!0),t(r)}}async withParent(e,t,n,s={}){let r=s.carriers===!0;if(n===void 0){await this.appendIds("withParent",e,t,r);return}if(n.length!==t.length)throw new Error("Each record that comes back with a parent is named beside that parent.");for(let a=0;a<t.length;a+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(a,a+J),parents:n.slice(a,a+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of pe(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of pe(n))await this.append({kind:"heldInPlace",objectApiName:e,by:[...t],ids:s})}async beforeParent(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"beforeParent",objectApiName:e,ids:s.map(({id:r})=>r),parents:s.map(({parent:r})=>r)})}}async recreating(e,t){for(let n of pe(t))await this.append({kind:"recreating",objectApiName:e,ids:n})}async recreated(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"recreated",objectApiName:e,ids:s.map(({id:r})=>r),from:s.map(({from:r})=>r)})}}async deleting(e){let t=++this.step;this.openStep=t;for await(let{objectApiName:n,ids:s}of qr(e))for(let r of pe(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async deleted(e){let t=this.openStep;if(t===void 0)throw new Error("No removal was named to the journal before it.");for await(let{objectApiName:n,ids:s}of e.left())for(let r of pe(s))await this.append({kind:"deleteLeft",step:t,objectApiName:n,ids:r});await this.append({kind:"deleted",step:t}),this.openStep=void 0}async removal(e){let t={...e.removalStamps&&Object.keys(e.removalStamps).length>0?{removalStamps:e.removalStamps}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:e.removalSpans}:{}};Object.keys(t).length!==0&&await this.append({kind:"removal",state:{version:1,...t}})}async unlinking(e){for(let t=0;t<e.length;t+=J)await this.append({kind:"unlinking",links:e.slice(t,t+J)})}async unlinkLeft(e){for(let t of pe(e))await this.append({kind:"unlinkLeft",ids:t})}async relinked(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J);await this.append({kind:"relinked",ids:n.map(({id:s})=>s),from:n.map(({from:s})=>s)})}}async linksUpdating(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J).map(s=>({Id:s.Id,LinkedEntityId:s.LinkedEntityId,ShareType:s.ShareType,Visibility:s.Visibility}));await this.append({kind:"linksUpdating",links:n})}}async linksUpdateLeft(e){for(let t of pe(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of pe(t))await this.append({kind:"linksUndone",part:e,ids:n})}async wrote(){await this.append({kind:"wrote"})}async end(){await this.append({kind:"end"})}async undone(e,t){await this.append({kind:"undo",state:{version:1,...e},status:t})}async read(){return await this.queue,Ns(ee(this.dir,Te))}async facts(){return await this.queue,Gr(ee(this.dir,Te))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ke(i,e){let t=(await kr(i)).size,n=t===0;if(t>0){let p=await ut(i,"r");try{let f=Buffer.alloc(1);await p.read(f,0,1,t-1),n=f[0]===10}finally{await p.close()}}let s=0,r=0,a=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let f;try{f=JSON.parse(p)}catch{f=void 0}let u=$r.safeParse(f);if(!u.success)throw new H("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);xr(u.data),s++,await e(u.data)},o=bs(i,{encoding:"utf8"}),d=Os({input:o,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await a(c),c=p}finally{d.close(),o.destroy()}return c!==void 0&&n&&await a(c),{count:s,whole:r,size:t}}function xr(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names links inserted again without the links they stand for.");if(i.kind==="recreated"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records deleted before a parent without their parent.");if((i.kind==="withParent"||i.kind==="bringingBack")&&i.parents!==void 0&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var he=class{byObject=new Map;add(e,t){let n=this.byObject.get(e)??new Map;for(let s of t)n.has(W(s))||n.set(W(s),s);this.byObject.set(e,n)}drop(e,t){let n=this.byObject.get(e);if(n)for(let s of t)n.delete(W(s))}list(e=()=>!0){return[...this.byObject].flatMap(([t,n])=>{let s=[...n].filter(([r])=>e(r)).map(([,r])=>r);return s.length>0?[{objectApiName:t,ids:s}]:[]})}keys(){return new Set([...this.byObject.values()].flatMap(e=>[...e.keys()]))}};function hs(i){let e={};for(let t of i)e={...e,...t,...t.removalStamps||e.removalStamps?{removalStamps:{...e.removalStamps,...t.removalStamps}}:{},...t.removalSpans||e.removalSpans?{removalSpans:[...e.removalSpans??[],...t.removalSpans??[]]}:{}};return e}function gs(i){let e=gn(i);if(e===void 0)throw new H("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var ze=class{head;step=0;passes=[];rewindStates=[];undoStates=[];undos=[];lastWrite=Number.NEGATIVE_INFINITY;endedAt;line(e){if(this.head===void 0){if(e.kind!=="head")throw new H("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(zr.has(e.kind)&&(this.lastWrite=Math.max(this.lastWrite,Date.parse(e.at))),"step"in e&&(this.step=Math.max(this.step,e.step)),e.kind){case"head":throw new H("damaged","The rewind\u2019s journal has two heads.");case"resumed":this.passes.push({startedAt:e.startedAt,userId:e.userId});break;case"removal":this.rewindStates.push(gs(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(gs(e.state)),this.undos.push({status:e.status,at:e.at});break;default:break}}result(){let e=this.head;if(e===void 0)throw new H("damaged","The rewind\u2019s journal does not begin with its head.");return{head:{rewindId:e.rewindId,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:e.startedAt,userId:e.userId,...e.automatedProcessUserId!==void 0?{automatedProcessUserId:e.automatedProcessUserId}:{},backup:e.backup},passes:this.passes,...Number.isFinite(this.lastWrite)?{lastWriteAt:new Date(this.lastWrite).toISOString()}:{},...this.endedAt!==void 0?{endedAt:this.endedAt}:{},rewind:hs(this.rewindStates),undo:hs(this.undoStates),undos:this.undos}}},Dt=class{broughtBack=new he;recreated=new he;carriers=new he;carried=new Map;givenBack=new he;held=new he;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new he,left:new Set,answered:!1},this.steps.set(e,t)),t}line(e){switch(e.kind){case"bringingBack":case"withParent":this.broughtBack.add(e.objectApiName,e.ids),e.carriers===!0&&e.kind==="bringingBack"&&this.carriers.add(e.objectApiName,e.ids),e.parents?.forEach((t,n)=>{let s=e.ids[n],r=e.carriers===!0?this.carried:this.withParents;r.has(W(s))||r.set(W(s),{objectApiName:e.objectApiName,id:s,parent:t})});break;case"bringBackLeft":this.broughtBack.drop(e.objectApiName,e.ids),this.carriers.drop(e.objectApiName,e.ids);for(let t of e.ids)this.withParents.delete(W(t)),this.carried.delete(W(t));break;case"givingBack":this.givenBack.add(e.objectApiName,e.ids);break;case"recreated":this.recreated.add(e.objectApiName,e.ids);break;case"heldInPlace":{this.held.add(e.objectApiName,e.ids);let t=this.heldBy.get(e.objectApiName)??new Set;for(let n of e.by)t.add(n);this.heldBy.set(e.objectApiName,t);break}case"beforeParent":e.ids.forEach((t,n)=>{this.beforeParent.push({objectApiName:e.objectApiName,id:t,parent:e.parents[n]})});break;case"deleting":this.stepOf(e.step).deleting.add(e.objectApiName,e.ids);break;case"deleteLeft":for(let t of e.ids)this.stepOf(e.step).left.add(W(t));break;case"deleted":this.stepOf(e.step).answered=!0;break;default:break}}result(){let e=new he;for(let{deleting:u,left:l,answered:h}of this.steps.values())for(let{objectApiName:g,ids:w}of u.list(y=>!h||!l.has(y)))e.add(g,w);let t=this.held.list().map(({objectApiName:u,ids:l})=>({objectApiName:u,ids:l,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new he;for(let{objectApiName:u,id:l,parent:h}of this.beforeParent){let g=W(h);n.has(W(l))&&(n.has(g)||!s.has(g))&&r.add(u,[l])}let a=r.list(),o=u=>{let l=new Map;for(let{objectApiName:h,id:g,parent:w}of u){let y=l.get(h)??{objectApiName:h,ids:[],parents:[]};y.ids.push(g),y.parents.push(w),l.set(h,y)}return[...l.values()]},d=o(this.withParents.values()),c=o(this.carried.values()),p=this.carriers.list(),f=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...a.length>0?{deletedBeforeParent:a}:{},...d.length>0?{withParents:d}:{},...f.length>0?{recreated:f}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function Ns(i){let e=new ze,t=new Dt;try{await ke(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof H?n:new H("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function Gr(i){let e=new ze;try{await ke(i,t=>e.line(t))}catch(t){throw t instanceof H?t:new H("notFound","No journal of this rewind is kept.")}return e.result()}function Jr(i,e,t){if(i.head.rewindId!==t||i.head.checkpointId!==e.checkpointId||i.head.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function wo(i,e){let t=await We(i,e);if(!t)throw new H("notFound","No journal of this rewind is kept.");return Ns(t.file)}function Bs(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function We(i,e){let t=je(i,e),n=ee(t,Te),s=new ze,r;try{r=await ke(n,o=>s.line(o))}catch(o){if(o instanceof H)throw o;return}if(r.count===0||s.head===void 0)return;let a=s.result();return Jr(a,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:a}}async function Cs(i,e){return i.whole<i.size&&await Ss(i.file,i.whole),lt.opened(i.dir,i.head,!0,i.step,e)}var ws=18;async function Kr(i){let e;try{e=(await Rs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&Je.safeParse(n.name).success).map(n=>n.name).sort().reverse()}catch{return[]}let[t]=e;return t===void 0?[]:e.filter(n=>n.slice(0,ws)===t.slice(0,ws))}async function Fs(i){let{folder:e}=i;Bs(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await Kr(e)){let c=await We(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Cs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(f){throw await p.close(),f}return p}let s=n??$e("rw",t()),r=je(e,s);await Le(r),await Le(ee(r,"backups")),await Ss(ee(r,Te),0).catch(()=>{});let a=js.safeParse({kind:"head",version:1,rewindId:s,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:i.startedAt,userId:i.userId,...i.automatedProcessUserId!==void 0?{automatedProcessUserId:i.automatedProcessUserId}:{},backup:Xn(s),at:t().toISOString()});if(!a.success)throw new H("invalid",`Not a rewind to journal: ${a.error.message}`);let o=await lt.opened(r,a.data,!1,0,t);try{await o.append(a.data),await Et(r),await Et(e.rewindsDir)}catch(d){throw await o.close(),d}return o}async function Ts(i,e,t,n=()=>new Date){Bs(t,i);let s=await We(i,e);if(!s)throw new H("notFound","No journal of this rewind is kept.");return Cs(s,n)}async function Es(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=Fn(n),r=[],a=[...n].sort((o,d)=>o.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:o,checkpoint:d}of a){if(d===void 0)continue;let c;try{c=(await Rs(o.rewindsDir,{withFileTypes:!0})).filter(f=>f.isDirectory()&&Je.safeParse(f.name).success).map(f=>f.name).sort()}catch{continue}let p=(f,u)=>u?.checkpointId===o.checkpointId&&u.rewindId===f;for(let f of c){if(p(f,t)||p(f,s))continue;let u=await We(o,f).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await vs(je(o,f),{recursive:!0,force:!0}),r.push({checkpointId:o.checkpointId,name:d.name,rewindId:f}))}}return r}var Mt=class i{constructor(e,t,n){this.dir=e;this.objects=t;this.keys=n}dir;objects;keys;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async written(e,t){await Le(e);let n=new E,s=new Map,r=new Map,a=async o=>{let d=r.get(o)??[];d.length!==0&&(await Ut(ms(e,o),d.join("")),r.set(o,[]))};await t(async(o,{id:d,parent:c})=>{if(!n.add(d))return;s.set(o,(s.get(o)??0)+1);let p=r.get(o)??[];p.push(`${d} ${c}
10
10
  `),r.set(o,p),p.length>=J&&await a(o)});for(let o of s.keys())await a(o);return new i(e,[...s].map(([o,d])=>({objectApiName:o,count:d})),n)}async*pages(e,t=J){if(!this.objects.some(a=>a.objectApiName===e))return;let n=bs(ms(this.dir,e),{encoding:"utf8"}),s=Os({input:n,crlfDelay:1/0}),r=[];try{for await(let a of s){let[o,d]=a.split(" ");o===void 0||d===void 0||(r.push({id:o,parent:d}),r.length>=t&&(yield r,r=[]))}}finally{s.close(),n.destroy()}r.length>0&&(yield r)}};function ms(i,e){return ee(i,`${nn(e)}.pairs`)}async function Ft(i,e,t){return e.length>0&&(await Le(Is(i)),await Ut(i,e.map(n=>`${JSON.stringify(n)}
11
- `).join(""))),{count:e.length,pages:async function*(){if(e.length===0)return;let n=[];for await(let s of tt(i))n.push(t(s)),n.length>=J&&(yield n,n=[]);n.length>0&&(yield n)}}}async function Hr(i,e){let t=new Map,n=new Map,s=new Map,r=new Set,a=new Set,o=new Set,d=new Set;await ke(i,u=>{switch(u.kind){case"unlinking":for(let l of u.links)t.has(W(l.Id))||t.set(W(l.Id),l);break;case"unlinkLeft":for(let l of u.ids)t.delete(W(l));break;case"relinked":for(let l of u.ids)n.set(W(l),{Id:l});break;case"linksUpdating":r=new Set;for(let l of u.links)s.has(W(l.Id))||(s.set(W(l.Id),l),r.add(W(l.Id)));break;case"linksUpdateLeft":for(let l of u.ids)r.has(W(l))&&s.delete(W(l));break;case"linksUndone":{let l=u.part==="reinserted"?a:u.part==="removed"?o:d;for(let h of u.ids)l.add(W(h));break}default:break}});for(let u of[...n.keys()])t.has(u)&&(n.delete(u),t.delete(u));let c=[...t].filter(([u])=>!a.has(u)).map(([,u])=>u),p=[...n].filter(([u])=>!o.has(u)).map(([,u])=>u),f=[...s].filter(([u])=>!d.has(u)).map(([,u])=>u);if(c.length+p.length+f.length!==0)return{reinsert:await Ft(ee(e,"links.reinsert.ndjson"),c,u=>we.parse(u)),remove:await Ft(ee(e,"links.remove.ndjson"),p,u=>({Id:_({Id:Ps}).parse(u).Id})),share:await Ft(ee(e,"links.share.ndjson"),f,u=>Ls.parse(u))}}function ys(i,e){let t=new Map(i.map(s=>[s.objectApiName,s.readOrder])),n=s=>t.get(s)??-1;return s=>[...s].sort((r,a)=>e?n(a.objectApiName)-n(r.objectApiName):n(r.objectApiName)-n(a.objectApiName))}async function $t(i,e,t){let n=ee(i,Te),s=ee(i,`undo-${ks(4).toString("hex")}`),r=()=>vs(s,{recursive:!0,force:!0});try{let a=b=>{if(b===void 0)return()=>!0;let R=new E;for(let C of b)R.add(C);return C=>R.has(C)},o=a(e.undo.removalLeft),d=a(e.undo.undeleteLeft),c=a(e.undo.restoreLeft),p=new E,f=new Set,u=new Map,l=new E,h=new Map,g=new E,w=new Set,y=new Map;await ke(n,b=>{switch(b.kind){case"bringBackLeft":for(let R of b.ids)w.add(W(R));break;case"bringingBack":case"withParent":case"recreated":for(let R of b.ids)p.add(R),w.size>0&&w.delete(W(R));b.kind==="withParent"&&b.carriers===!0&&b.parents&&b.ids.forEach((R,C)=>{let te=b.parents?.[C];te!==void 0&&!y.has(W(R))&&y.set(W(R),{objectApiName:b.objectApiName,id:R,parent:W(te)})});break;case"givingBack":for(let R of b.ids)g.add(R);break;case"deleteLeft":{let R=u.get(b.step)??new E;for(let C of b.ids)R.add(C);u.set(b.step,R);break}case"deleted":f.add(b.step);break;case"heldInPlace":{for(let C of b.ids)l.add(C);let R=h.get(b.objectApiName)??new Set;for(let C of b.by)R.add(C);h.set(b.objectApiName,R);break}default:break}});let m=b=>p.has(b)&&!w.has(b),k=new E,L=new Ce(ee(s,"bringBack"));await ke(n,async b=>{if(b.kind!=="deleting")return;let R=f.has(b.step)?u.get(b.step):void 0;for(let C of b.ids){if(R?.has(C)===!0)continue;let te=W(C);m(te)?k.add(C):d(te)&&await L.add(b.objectApiName,C)}});let S=new E;for(let b=y.size>0;b;){b=!1;for(let{id:R,parent:C}of y.values())S.has(R)||g.has(R)||(k.has(C)||S.has(C))&&(S.add(R),b=!0)}let T=b=>k.has(b)||S.has(b),F=b=>!w.has(b)&&!T(b)&&o(b),P=new E,j=new E;await ke(n,b=>{b.kind!=="withParent"||b.parents===void 0||b.ids.forEach((R,C)=>{if(!j.add(R))return;let te=W(b.parents?.[C]??"");F(W(R))&&m(te)&&F(te)&&P.add(R)})});let z=new E,q=new Map;for(let{objectApiName:b,id:R,parent:C}of y.values())!F(W(R))||P.has(R)||!g.has(R)||F(C)&&y.has(C)||(z.add(R),q.set(b,(q.get(b)??0)+1));let x=new Ce(ee(s,"remove")),A=new Ce(ee(s,"giveBack")),B=new E,G=new Map,v=await Mt.written(ee(s,"goesWithParent"),async b=>{await ke(n,async R=>{if(R.kind==="givingBack"){for(let C of R.ids)c(W(C))&&await A.add(R.objectApiName,C);return}if(R.kind==="recreated"){for(let C of R.ids)!F(W(C))||!await x.add(R.objectApiName,C)||(B.add(C),G.set(R.objectApiName,(G.get(R.objectApiName)??0)+1));return}if(!(R.kind!=="bringingBack"&&R.kind!=="withParent"))for(let[C,te]of R.ids.entries()){let fe=W(te);if(!F(fe))continue;let Oe=R.parents?.[C];P.has(fe)?Oe!==void 0&&await b(R.objectApiName,{id:te,parent:Oe}):await x.add(R.objectApiName,te)}})}),N=await A.finish(),M=await Hr(n,s),K=new E,U=new Map;for(let{objectApiName:b}of N.objects)for await(let R of N.pages(b))for(let C of R)l.has(C)&&(K.add(C),U.set(b,(U.get(b)??0)+1));return{remove:await xn.of(x,ys(t,!1)),bringBack:await L.finish(ys(t,!0)),giveBack:N,giveBackKeys:A.keys,backup:e.head.backup,held:{keys:K,objects:[...U].map(([b,R])=>({objectApiName:b,count:R,by:[...h.get(b)??[]]}))},goesWithParent:v,remade:{keys:B,objects:[...G].map(([b,R])=>({objectApiName:b,count:R}))},compensated:{has:b=>T(W(String(b)))},carriedAlone:{keys:z,objects:[...q].map(([b,R])=>({objectApiName:b,count:R}))},...M?{links:M}:{},dispose:r}}catch(a){throw await r(),a}}async function mo(i,e,t){let n=await We(i,e);if(!n)throw new H("notFound","No journal of this rewind is kept.");return $t(n.dir,n.facts,t)}function yo(i){let e=new Map,t=s=>{let r=e.get(s);return r||(r={objectApiName:s,deleted:0,broughtBack:0,givenBack:0},e.set(s,r)),r};for(let{objectApiName:s,count:r}of i.bringBack.objects)r>0&&(t(s).deleted+=r);for(let{objectApiName:s,count:r}of i.remove.objects)r>0&&(t(s).broughtBack+=r);for(let{objectApiName:s,count:r}of i.giveBack.objects)r>0&&(t(s).givenBack+=r);for(let{objectApiName:s,count:r}of i.held.objects){let a=t(s);a.givenBackHeld=(a.givenBackHeld??0)+r}let n=i.links;if(n){let s=t(ne);s.deleted+=n.reinsert.count,s.broughtBack+=n.remove.count,s.givenBack+=n.share.count}return[...e.values()]}var Vr=50,Yr=/Entity is not in the recycle bin/,Zr="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own, then a record it hangs from was deleted after it, it can no longer come back, with that record or without; deleted with a record still in the bin, it comes back only with that record (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin')",Xr=100;function re(i){return i.slice(0,15)}var Qr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ei(i,e){return{batches:async(t,n,s)=>{let r=await i.batches(t,n,s);return r?{async*[Symbol.asyncIterator](){for await(let a of r)yield a.map(o=>Object.fromEntries(Object.entries(o).filter(([d,c])=>d==="Id"||typeof c!="string"||!Qr.test(c)||!e.has(c))))}}:null}}}function ti(i){return{objects:[],cancelled:i,gone:[],stamps:{},left:async function*(){}}}function Ds(i,e){if(e){i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}}async function*Ms(i,e,t,n=()=>!0){let s=[];for await(let r of i.pages(e,t))for(let a of r)n(re(a))&&(s.push(a),s.length>=t&&(yield s,s=[]));s.length>0&&(yield s)}function ni(i){let e=i.bringBack.objects.filter(({count:r})=>r>0).map(({objectApiName:r})=>r),t=new Set(i.held.objects.flatMap(({by:r})=>r)),n=e.findIndex(r=>t.has(r)),s=n<0||i.held.keys.size===0?e.length:n;return{bringFirst:e.slice(0,s),bringAfter:e.slice(s),held:r=>i.held.keys.has(r)}}function si(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}function ri(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);s?si(s,n):t.push({...n,reasons:[...n.reasons]})}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}function ii(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);if(!s){t.push(n);continue}s.planned+=n.planned,Ds(s,n)}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}async function zt(i,e,t,n){if(e.cancelled)return e;let s=new Set(e.left.map(re)),r=new Set,a=[];for(let o of e.objects){let d=o.reasons.find(l=>Yr.test(l));if(d===void 0||o.refused===0){a.push(o);continue}let c=t.filter(({objectApiName:l})=>l===o.objectApiName).flatMap(l=>l.ids.filter(h=>s.has(re(h)))),p=0;try{let l=de(o.objectApiName);for(let h of ge(c,Y)){let g=await i.query(`SELECT Id FROM ${l} WHERE Id IN (${h})`);for(let w of g.records)typeof w.Id!="string"||r.has(re(w.Id))||(r.add(re(w.Id)),p++)}}catch(l){n.push(`Whether the ${o.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${Q(l)}): they are counted refused.`),a.push(o);continue}let f=Math.min(p,o.refused),u=o.refused-f;a.push({...o,refused:u,alreadyBack:o.alreadyBack+f,reasons:u===0?o.reasons.filter(l=>l!==d):o.reasons.map(l=>l===d?Zr:l)})}return{...e,objects:a,left:e.left.filter(o=>!r.has(re(o)))}}async function oi(i,e,t,n){let s=new Map(n.map(o=>[re(o),o])),r=new Map,a=await i.batches(e,t,Y);for await(let o of a??[])for(let d of o){if(typeof d.Id!="string")continue;let c=s.get(re(d.Id));if(c===void 0)continue;let p=r.get(re(c))??{id:c,values:{}};for(let[f,u]of Object.entries(d))f!=="Id"&&!(f in p.values)&&(p.values[f]=u);r.set(re(c),p)}return r}async function ai(i,e,t,n,s){let r=[],a=e.backup;for(let{objectApiName:o}of e.giveBack.objects){let d=de(o),c={objectApiName:o,count:0,ids:[],by:{}};try{for await(let p of Ms(e.giveBack,o,Se,f=>!n.has(f))){let f=await oi(t,a,o,p);if(f.size===0)continue;let u=new Set;for(let{values:w}of f.values())for(let y of Object.keys(w))u.add(de(y));let l=["Id","LastModifiedById",...u],h=l.length>Xr?Y/4:Y,g=async w=>(await i.query(w)).records;for(let w of ge([...f.values()].map(y=>y.id),h)){let y=await He(`SELECT ${l.join(", ")} FROM ${d} WHERE Id IN (${w})`,g);for(let m of y){if(typeof m.Id!="string")continue;let k=f.get(re(m.Id));if(!k||!Object.entries(k.values).some(([T,F])=>!wn(F,m[T])))continue;c.count++,c.ids.length<Vr&&c.ids.push(k.id);let S=typeof m.LastModifiedById=="string"?m.LastModifiedById:"unknown";c.by[S]=(c.by[S]??0)+1}}}}catch(p){s.push(`The ${o} records the undo gave back could not be read again (${Q(p)}): whether they all hold their values from before the rewind was not checked.`)}c.count>0&&r.push(c)}return r}async function di(i,e,t,n,s){let r=new Map(Object.entries(n).map(([o,d])=>[re(o),Date.parse(d)])),a=new E;for(let{objectApiName:o}of e.objects){let d=de(o);for await(let c of e.pages(o))for(let p of ge(c,Y)){if(s?.aborted)return a;let f;try{f=(await i.query(`SELECT Id, LastModifiedDate FROM ${d} WHERE Id IN (${p})`)).records}catch{continue}for(let u of f){if(typeof u.Id!="string")continue;let l=re(u.Id),h=Date.parse(String(u.LastModifiedDate??""));(h<=t||h<=(r.get(l)??Number.NaN))&&a.add(u.Id)}}}return a}async function Fo(i){let e=await Ts(i.folder,i.rewindId,i.lock);try{let t=await e.facts(),n=await $t(e.dir,t,i.objects);try{return await ci(e,t,n,i)}finally{await n.dispose()}}finally{await e.close()}}async function ci(i,e,t,n){let{org:s,signal:r}=n,a=t.goesWithParent,o=ei(i.values,t.compensated),d={remove:t.remove.spool.count+a.count,bringBack:t.bringBack.count,giveBack:t.giveBack.count},c=[],p={...e.rewind.removalStamps,...e.undo.removalStamps},f=Object.keys(p).length>0?p:void 0,u=[...e.rewind.removalSpans??[],...e.undo.removalSpans??[]],l=mn(s),h,g=new E,w={},y=new Set(n.objects.filter(I=>I.customSetting!==void 0).map(I=>I.objectApiName)),m=I=>!y.has(I),k=ni(t),L,S,T=new Map,F=async I=>{for(let D of I)for await(let $ of t.bringBack.pages(D)){let oe=(L?.cancelled??!1)||r?.aborted===!0?{objects:[{objectApiName:D,planned:$.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,notReached:$.length,reasons:[]}],left:[...$],wrote:!1,cancelled:!0,stamps:{}}:await Ze({org:s,plan:[{objectApiName:D,ids:$}],undelete:n.undelete,...r?{signal:r}:{}});T.set(D,[...T.get(D)??[],...oe.left]),L=ri(L,oe)}return!(L?.cancelled??!1)&&r?.aborted!==!0},P=async(I,D=m)=>{for(let{objectApiName:$}of t.giveBack.objects){if(!D($))continue;let ie=de($),oe={objectApiName:$,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]},ce={objects:[oe],left:[],wrote:!1,cancelled:!1,stamps:{}};for await(let ve of Ms(t.giveBack,$,Se,I)){if(oe.planned+=ve.length,(S?.cancelled??!1)||ce.cancelled||r?.aborted){ce.cancelled=!0,oe.notReached=(oe.notReached??0)+ve.length,ce.left.push(...ve);continue}if(h!==void 0){let ir=ve.filter(or=>g.has(or));Object.assign(w,await kn(s,ie,ir,h,l))}let Vt={...p,...w},Ee=await Ye({org:s,plan:[{objectApiName:$,backup:t.backup,ids:ve}],backups:o,...e.lastWriteAt!==void 0?{lastWriteAt:e.lastWriteAt}:{},includeChanged:!1,...Object.keys(Vt).length>0?{stamps:Vt}:{},...r?{signal:r}:{}});Ds(oe,Ee.objects[0]),ce.left.push(...Ee.left),ce.wrote||=Ee.wrote,ce.cancelled||=Ee.cancelled,Object.assign(ce.stamps,Ee.stamps)}oe.planned>0&&(S=ii(S,ce))}return!(S?.cancelled??!1)&&r?.aborted!==!0},j=async()=>{if(t.bringBack.count>0&&t.giveBack.count>0){let D=await yn(s);h=Date.now()+D-vt;let $=Date.parse(e.lastWriteAt??""),ie=Number.isFinite($)?$+D+vt:Number.NEGATIVE_INFINITY;g=await di(s,t.giveBack,ie,p,r)}return await F(k.bringFirst.filter(m))&&await P(k.held)&&await F(k.bringAfter.filter(m))&&(L&&(L=await zt(s,L,[...T].map(([D,$])=>({objectApiName:D,ids:$})),c)),await P(D=>!k.held(D))),(L?.wrote??!1)||(S?.wrote??!1)},z,q=(I,D)=>{if(typeof I.Id!="string"||!a.keys.has(I.Id))return!1;if(z===void 0){let oe=new E;for(let ce of S?.left??[])oe.add(ce);z={stamps:new Map(Object.entries({...p,...w}).map(([ce,ve])=>[re(ce),Date.parse(ve)])),notGiven:oe}}let $=Date.parse(String(I.LastModifiedDate??I.SystemModstamp??"")),ie=re(I.Id);return $<=D||$<=(z.stamps.get(ie)??Number.NaN)?!0:t.giveBackKeys.has(ie)&&S!==void 0&&!z.notGiven.has(ie)},x=t.links,A={removed:ue(),reinserted:ue(),shared:ue()};if(x&&x.remove.count>0&&!r?.aborted)for await(let I of x.remove.pages())Fe(A.removed,await at(s,I,{after:async({done:D})=>{D.length>0&&await i.linksUndone("removed",D.map($=>$.Id))},stopped:()=>r?.aborted===!0}));let B;if(t.remove.spool.count>0?B=await Ve(s,t.remove,{...n.splitting?{splitting:n.splitting}:{},runStartedAt:new Date(e.head.startedAt),...e.lastWriteAt!==void 0?{runRecordedAt:new Date(e.lastWriteAt)}:{},...f?{removalStamps:f}:{},...u.length>0?{removalSpans:u}:{},includeChanged:!1,...a.count>0?{goesWithParent:q,goesWithParentReadBelow:!0}:{},...t.bringBack.count>0||t.giveBack.count>0?{sweep:j}:{},...n.onUndeletable?{onUndeletable:n.onUndeletable}:{},...r?{signal:r}:{},...n.onProgress?{onProgress:n.onProgress}:{}}):(r?.aborted||await j(),B=ti(r?.aborted===!0&&!L&&!S)),y.size>0&&!B.stoppedForUndeletable&&(await P(()=>!0,I=>y.has(I)),await F([...k.bringFirst,...k.bringAfter].filter(I=>y.has(I)))),x&&!B.stoppedForUndeletable&&!r?.aborted){let I=s.create?.bind(s);for await(let D of x.reinsert.pages()){if(!I){A.reinserted.refused+=D.length,A.reinserted.reasons.push("The links the rewind removed could not be inserted again: this connection inserts no record.");continue}Fe(A.reinserted,await dt({create:I},D,{after:async({made:$})=>{$.length>0&&await i.linksUndone("reinserted",$.map(ie=>ie.from))},stopped:()=>r?.aborted===!0}))}for await(let D of x.share.pages())Fe(A.shared,await ct(s,D.map($=>({...$,now:{ShareType:"",Visibility:""}})),{after:async({done:$})=>{$.length>0&&await i.linksUndone("shared",$.map(ie=>ie.Id))},stopped:()=>r?.aborted===!0}))}let G=x?{unlinked:A.removed.done,relinked:A.reinserted.done,linksUpdated:A.shared.done,linksRefused:A.removed.refused+A.reinserted.refused+A.shared.refused}:void 0;for(let I of[...A.removed.reasons,...A.reinserted.reasons,...A.shared.reasons])c.includes(I)||c.push(`A link between a file and a record: ${I}`);let v=new Date().toISOString();if(B.stoppedForUndeletable)return{rewindId:n.rewindId,status:"cancelled",deleted:[],restored:[],undeleted:[],residual:[],planned:d,notes:[],stoppedForUndeletable:!0,finishedAt:v};let N=[],M=new E,K=new Map,U=new Map;for await(let{objectApiName:I,ids:D}of B.left())for(let $ of D)M.add($),N.push($),t.remade.keys.has($)&&K.set(I,(K.get(I)??0)+1),t.carriedAlone.keys.has($)&&U.set(I,(U.get(I)??0)+1);let b=t.remade.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(K.get(I)??0)})).filter(({count:I})=>I>0),R=t.carriedAlone.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(U.get(I)??0)})).filter(({count:I})=>I>0),C=[];for(let{objectApiName:I}of a.objects){let D=0;for await(let $ of a.pages(I))for(let{id:ie,parent:oe}of $)M.has(oe)?N.push(ie):D++;D!==0&&C.push({objectApiName:I,planned:D,deleted:D,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})}let te=[...C,...B.objects],fe=bn(Rn(hn(te,B.cancelled),te,S),te,S,L),Oe=[];if(S&&fe!=="cancelled"){let I=new E;for(let D of S.left)I.add(D);Oe=await ai(s,t,o,I,c)}Oe.length>0&&fe==="success"&&(fe="partial"),(G?.linksRefused??0)>0&&fe==="success"&&(fe="partial");let nr=t.remove.spool.count>0,sr=S?.objects.some(I=>I.restored+(I.restoredWithout??0)>0)===!0,Ht={...w,...B.stamps},rr={...Object.keys(Ht).length>0?{removalStamps:Ht}:{},...B.span?{removalSpans:[B.span]}:{},...nr?{removalLeft:N}:{},...S?{restoreLeft:S.left}:{},...sr?{restoredAt:v}:{},...L?{undeleteLeft:L.left}:{},...L&&!L.cancelled?{undeletedAt:v}:{}};try{await i.undone(rr,fe)}catch(I){c.push(`What this undo did could not be kept in the rewind\u2019s journal (${Q(I)}): an undo after it may set out to take back what it took back already.`)}return{rewindId:n.rewindId,status:fe,deleted:te,...b.length>0?{remade:b}:{},...R.length>0?{carriedAlone:R}:{},...C.length>0?{wentAlong:C.map(({objectApiName:I,deleted:D})=>({objectApiName:I,count:D}))}:{},restored:S?.objects??[],undeleted:L?.objects??[],...G?{files:G}:{},residual:Oe,planned:d,notes:c,finishedAt:v}}var li=1e3,ui=Tn*24*60*6e4,Ws=50,Ks=5,Hs=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],_s=[...Hs.filter(i=>i!=="carrier"),"goneForGood","convertedLead","activatedContract","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach"],fi="Left in the recycle bin: deleted since by another user, which only a user with View All Data and Modify All Data restores. Not made again: it is there still.",Jt="Left as it is: out of the user's reach. Without View All Data and Modify All Data, nothing proves the user sees what others deleted of this object in the recycle bin, so it may be there out of sight, and it is never made again.",pi={convertedLead:"Left converted: Salesforce can't unconvert a lead, and refuses any update of a converted one.",activatedContract:"Left activated: Salesforce won't set an activated contract back to Draft, so it is not given back.",deletedWithCreatedParent:"Left in the recycle bin: deleted with a record created since that Salesforce does not undelete on its own, it comes back with that record only.",deletedWithParentOutside:"Left in the recycle bin: deleted with its parent, a record of an object the checkpoint does not hold, it comes back with that record only. A checkpoint that holds that object brings it back.",deletedByOther:fi,outOfReach:Jt},ft={createdSince:"removal",broughtBackSince:"removal",comesBackWithParent:"removal",giveBack:"restore",inBin:"undelete",withParent:"undelete",deletedWhileTaken:"undelete",toRecreate:"recreate",carrier:"undelete"},Wt={outsideNotAccepted:"Kept: records outside the checkpoint created since hang from it, and their deletion was not accepted.",holdsLeft:"Kept: a record the rewind left hangs from it, and its deletion would take that record along.",noUndoNotAccepted:"Kept: Undo couldn't bring it back once deleted on its own, and that was not accepted.",beforeParentNotAccepted:"Kept: Undo couldn't bring it back once deleted before a record it points at, which the rewind deletes next, and that was not accepted.",keyTaken:"Kept in the recycle bin: a row of this custom setting made or changed since holds its owner or its name, and brought back beside it the setting would hold two. It comes back once that row is gone."};function hi(i){return`Kept: records it does not delete hang from it (${i.join(", ")}), and its deletion would take them along.`}var _t="It still differs from the checkpoint once the org was read again.",_e=/Entity is not in the recycle bin/,gi="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin'). Make them again, with new Ids, or --accept-recreate on the command line, makes it again with a new Id.",Ie="No record was written.",qs=4;function wi(i,e,t){let n=e.some(o=>Ke[o]!==void 0)?"as it is created or given its status back":"as it is created",s=[...new Set(t.fired.map(o=>`${o.objectApiName}: '${o.name}'`))],r=s.length-qs;return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and ${s.length>0?`making it again runs what ${i} runs ${n} (${s.slice(0,qs).join(", ")}${r>0?` and ${r} more`:""})`:`what ${i} runs ${n} could not all be read`}, which this rewind did not ask about. Rewind again: its preview counts it to make again, and asks.`}var mi="Account",yi="Contact",ki="001",bi="005",Ri=_({sobjects:le(_({name:X(),queryable:De().optional()}).loose())}).loose(),vi=/No such column 'IsDeleted'/;function qt(i){return i.toLowerCase()===ne.toLowerCase()}function Si(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];if(typeof r!="object"||r===null)return!1;let{success:a,errors:o}=r;return a===!0?!1:(Array.isArray(o)?o:[o]).some(d=>{let c=typeof d=="string"?d:typeof d=="object"&&d!==null?String(d.message??""):"";return _e.test(c)})})}function Ii(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];return typeof r=="object"&&r!==null&&r.success===!1})}function ya(i){let e=Yn(i),t=pn(i,"Checkpoint rewind"),n=t.bulkDestroy;return{get version(){return e.version},request:s=>e.request(s),query:async(s,r)=>await i.query(s,{scanAll:r?.scanAll===!0}),queryMore:s=>e.queryMore(s),describeGlobal:()=>e.describeGlobal(),serverTime:()=>e.serverTime(),userId:()=>e.userId(),describe:s=>t.describe(s),update:(s,r)=>t.update(s,r),create:(s,r)=>i.sobject(s).create(r,{headers:tn()}),destroy:(s,r)=>t.destroy(s,r),queryDeleted:s=>t.queryDeleted(s),...n?{bulkDestroy:(s,r,a)=>n(s,r,a)}:{}}}async function Oi(i,e,t){if(!i||!e)return e?{automation:e}:{};try{let n=await i(e,bt(t));return{automation:n.automation??e,mute:n}}catch(n){if(!St(n))throw n;let s=Sn(e,bt(t));return{refusal:{code:"MUTE",message:`${n.message} ${Ie}`},automation:s.automation,plan:s.plan}}}async function Pi(i,e,t,n){let s=i?.prepared?await i.prepared.acquire(e):void 0;i&&!s&&n(i.muted);let r;try{r=await t(s)}catch(a){if(!s)throw a;let o=await s.release();throw n(o),Object.assign(a instanceof Error?a:new Error(String(a)),{mutedAutomation:o})}return s&&n(await s.release()),r}var qe=class extends Error{constructor(){super("The rewind was stopped before it wrote anything to the org."),this.name="RewindStopped"}};function O(i){return i.slice(0,15)}function pt(i){let e=cn(i);return e===null?Number.NaN:Date.parse(e)}async function*se(i){try{for await(let e of tt(i))yield e}catch(e){if(e.code!=="ENOENT")throw e}}async function xs(i,e){let t=[];for await(let n of se(i)){let s=we.safeParse(n);if(!s.success)throw new Error(`A line of ${i} names no ${e} link: the plan is not whole.`);t.push(s.data)}return t}async function Ai(i){let e=[];for await(let t of se(i)){let n=Nt.safeParse(t);if(!n.success)throw new Error(`A line of ${i} names no link: the plan is not whole.`);e.push(n.data)}return e}var ji=_({sobjects:le(_({name:X(),keyPrefix:X().nullish()}).loose())}).loose();function Li(i){return{query:e=>i.query(e),queryMore:e=>i.queryMore(e)}}function Ni(i,e){return{rewound:!1,refusal:{code:i,message:e}}}function Gs(i,e){return{rewound:!1,refusal:i,...e.length>0?{alsoRefused:[...e]}:{}}}function Bi(i,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${i} is being taken`:e.operation==="rewind"?`A rewind is writing to ${i}`:e.operation==="undo"?`An undo is writing to ${i}`:e.operation==="empty"?`An emptying of its objects is writing to ${i}`:`SandForge is deleting checkpoints of ${i}`} (process ${e.pid} on ${e.host}): rewind once it has ended. No record was read or written.`}}var Vs=new Set(["noUndoNotAccepted","beforeParentNotAccepted"]),Ci={noUndoNotAccepted:"Salesforce undeletes them only with their parent, which stays",beforeParentNotAccepted:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"};function Fi(i){return{code:"NO_UNDO",message:`${[...Vs].flatMap(t=>{let n=i.filter(a=>a.reason===t);if(n.length===0)return[];let s=n.reduce((a,o)=>a+o.count,0),r=[...new Set(n.map(a=>a.objectApiName))].join(", ");return[`Undo couldn't bring back ${s} ${r} record(s) this rewind deletes: ${Ci[t]??""}.`]}).join(" ")} Rewind refused; accept that Undo couldn't bring them back to rewind all the same. ${Ie}`}}function Ti(i){let e=i.reduce((n,s)=>n+s.count,0),t=[...new Set(i.map(n=>n.objectApiName))].join(", ");return{code:"RECREATE",message:`${e} ${t} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; accept that they get new Ids to rewind all the same. ${Ie}`}}function Ei(i,e){return{code:"UNSEEN",message:`${e.map(({objectApiName:n,children:s,records:r})=>`Deleting ${r} ${n} record(s) created since also deletes what ${i} can't see under them in ${s.join(", ")}: Rewind can't count those.`).join(" ")} Rewind refused; accept that it deletes what ${i} can't see to rewind all the same. ${Ie}`}}function Di(i,e){return(i.unseen??[]).flatMap(t=>{let n=e.objects.find(r=>r.objectApiName===t.objectApiName),s=(n?.deleted??0)+(n?.withParentDeleted??0);return s>0?[{...t,records:s}]:[]})}function Mi(i,e){if(e.kind==="org")return[];if(i.access.kind==="org")return["View All Data and Modify All Data"];let t=new Set(i.unread.map(n=>n.objectApiName));return[...e.notHeld].filter(([n])=>!t.has(n)).map(([n,s])=>`${n}: ${s}`)}function Ui(i,e){return{code:"PERMISSIONS",message:`The preview read ${i} with permissions its user no longer has (${e.join("; ")}). Preview the rewind again: it reads the org as the user can now. ${Ie}`}}var $i="accept that it runs to rewind all the same";function zi(i,e,t,n){let s=kt(e,t),r=[...new Set(s.map(d=>d.objectApiName))],a=(t.recreate??[]).length>0?"makes them again, ":"",o=s.length>0?`${ds(s)} flow(s), trigger(s) or rule(s) of ${r.join(", ")} run as the rewind brings records back, ${a}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${i}: ${o}. ${jn("rewind",n)}Rewind refused; ${$i}. ${Ie}`}}function Wi(i,e){return{objectsRead:[...i],objects:[],unread:["flows","triggers","processes","workflowRules"].map(t=>({part:t,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Js(i){return i.replace(/the value from before is no longer taken/g,"the checkpoint's value is no longer taken").replace(/left as the run wrote it\b/g,"left as it is").replace(/left as the run wrote them\b/g,"left as they are").replace(/^The values from before the run could not be read:/,"The checkpoint's values could not be read:").replace(/record\(s\) of the run stay, and were not sent\./,"record(s) the rewind would delete stay, and were not sent.")}function me(i,e){i.length<Ks&&!i.includes(e)&&i.push(e)}function ht(i,e,t){let n=t;for(let s of e){if(n<=0)return;let r=Number(i[s]??0),a=Math.min(r,n);i[s]=r-a,n-=a}}function wt(i){return{objectApiName:i,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}function Ys(i,e){i.planned+=e.planned,i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)me(i.reasons,t)}function mt(i){return{objectApiName:i,planned:0,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]}}function Zs(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Re(i){return{objectApiName:i,planned:0,created:0,refused:0,reasons:[]}}function Xs(i,e){i.planned+=e.planned,i.created+=e.created,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Qs(i,e){i.planned+=e.planned,i.deleted+=e.deleted,i.alreadyGone+=e.alreadyGone,i.keptChanged+=e.keptChanged,i.keptDependents+=e.keptDependents,i.refused+=e.refused,e.notVisible&&(i.notVisible=(i.notVisible??0)+e.notVisible),e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.heldBy)i.heldBy.includes(t)||i.heldBy.push(t);for(let t of e.unchecked)i.unchecked.includes(t)||i.unchecked.push(t);for(let t of e.reasons)me(i.reasons,t);e.filesLeft&&(i.filesLeft={count:(i.filesLeft?.count??0)+e.filesLeft.count,names:[...i.filesLeft?.names??[],...e.filesLeft.names].slice(0,Ks)})}var xe=class{restored=new Map;undeleted=new Map;recreated=new Map;deleted=new Map;left={restore:new Map,undelete:new Map,recreate:new Map,removal:new Map};heldInPlace=new Map;notInBin=new Map;notAsked=new Map;draftsLeft=new Map;lost=new Map;outOfReach=new Map;links={unlink:ue(),relink:ue(),share:ue()};wrote=!1;cancelled=!1;leftBy(e,t,n){let s=this.left[e].get(t);s||(s=new E,this.left[e].set(t,s));for(let r of n)s.add(r)}mark(e,t,n){let s=this[e].get(t);s||(s=new E,this[e].set(t,s)),s.add(n)}cameBackGiven=new Map;cameBackRestored=0;restore(e,t){let n=this.restored.get(e.objectApiName)??wt(e.objectApiName),s=t?.restored.length??0,r=t?.alreadyGone.length??0;if(Ys(n,{...e,planned:e.planned-s-r,restored:e.restored-s,alreadyGone:e.alreadyGone-r,reasons:e.reasons.map(Js)}),this.restored.set(e.objectApiName,n),s+r===0||!t)return;let a=this.cameBackGiven.get(e.objectApiName)??new E;for(let o of[...t.restored,...t.alreadyGone])a.add(o);this.cameBackGiven.set(e.objectApiName,a),this.cameBackRestored+=s}undelete(e){let t=this.undeleted.get(e.objectApiName)??mt(e.objectApiName);Zs(t,e),this.undeleted.set(e.objectApiName,t)}recreate(e){let t=this.recreated.get(e.objectApiName)??Re(e.objectApiName);Xs(t,e),this.recreated.set(e.objectApiName,t)}delete(e){for(let t of e){let n=this.deleted.get(t.objectApiName),s={...t,reasons:t.reasons.map(Js)};n?Qs(n,s):this.deleted.set(t.objectApiName,structuredClone(s))}}};async function _i(i){let e=new Map;for(let t of i)for(let{objectApiName:n}of t.objects){let s=e.get(n)??new E;for await(let r of t.pages(n))for(let a of r)s.add(a);e.set(n,s)}return e}async function gt(i,e,t){let n=await _i(e),s=new Map,r=new Map;for(let a of i)for(let{objectApiName:o}of a.objects){let d=n.get(o);if(!d)continue;let c=s.get(o)??new E;s.set(o,c);let p=t?.get(o);for await(let f of a.pages(o))for(let u of f)d.has(u)&&p?.has(u)!==!0&&c.add(u)&&r.set(o,(r.get(o)??0)+1)}return r}async function qi(i,e){let t=i.tally,n=new Map([...t.deleted].map(([o,d])=>[o,structuredClone(d)])),s=new Map([...t.restored].map(([o,d])=>[o,structuredClone(d)])),r=new Map([...t.undeleted].map(([o,d])=>[o,structuredClone(d)])),a=new Map([...t.recreated].map(([o,d])=>[o,structuredClone(d)]));if(e){let{tally:o,plan:d}=e,c=await gt([d.giveBack.beforeDeletes,d.giveBack.afterDeletes],[i.plan.giveBack.beforeDeletes,i.plan.giveBack.afterDeletes],t.cameBackGiven);for(let[l,h]of o.restored){let g=s.get(l)??wt(l),w=c.get(l)??0;ht(g,["refused","notReached","notKept","keptChanged","restoredWithout","alreadyGone","restored"],w),g.planned-=Math.min(w,g.planned),Ys(g,h),s.set(l,g)}let p=await gt([d.bringBack],[i.plan.bringBack]);for(let[l,h]of o.undeleted){let g=r.get(l)??mt(l),w=p.get(l)??0;ht(g,["refused","notReached","goneForGood","alreadyBack","undeleted"],w),g.planned-=Math.min(w,g.planned),Zs(g,h),r.set(l,g)}let f=await gt([d.recreate],[i.plan.recreate]);for(let[l,h]of o.recreated){let g=a.get(l)??Re(l),w=f.get(l)??0;ht(g,["refused","notReached","created"],w),g.planned-=Math.min(w,g.planned),Xs(g,h),a.set(l,g)}let u=await gt([d.deletes.spool],[i.plan.deletes.spool]);for(let[l,h]of o.deleted){let g=n.get(l);if(!g){n.set(l,structuredClone(h));continue}let w=u.get(l)??0;ht(g,["refused","keptDependents","keptChanged","notVisible","alreadyGone","deleted"],w),g.planned-=Math.min(w,g.planned),Qs(g,h)}}for(let[o,{reason:d}]of[...t.heldInPlace,...e?.tally.heldInPlace??[]]){let c=s.get(o);c&&me(c.reasons,d)}return{deleted:[...n.values()],restored:[...s.values()],undeleted:[...r.values()],recreated:[...a.values()]}}function xi(i){let e=new Map;return{bodies:e,reader:{lane:()=>i.lane(),tooling:t=>i.tooling(t),calls:()=>i.calls(),describe:async(t,n)=>{let s=await i.describe(t,n);return"body"in s&&e.set(t,s.body),s}}}}function Gi(i){let e=i.objects,t=e.filter(n=>n.deleted+n.withParentDeleted+n.nextPassDeleted>0).map(n=>n.objectApiName);return{bringBack:e.filter(n=>n.broughtBack+n.backWithParent+(n.carriers??0)>0).map(n=>n.objectApiName),recreate:e.filter(n=>n.recreated>0).map(n=>n.objectApiName),giveBack:e.filter(n=>n.givenBackFirst+n.givenBackAfter+n.givenBackNextPass+On(n)>0).map(n=>n.objectApiName),setToDraft:e.filter(n=>In(n)>0).map(n=>n.objectApiName),delete:t}}function Ji(i){let e=Gi(i),{unlink:t,relink:n,share:s,unlinkFrom:r}=i.links,a=(o,d)=>d?[...o??[],ne]:[...o??[]];return{...e,delete:a(e.delete,t.count+r.count>0),recreate:a(e.recreate,n.count>0),giveBack:a(e.giveBack,s.count>0)}}function er(i){let{unlink:e,relink:t,share:n,unlinkFrom:s}=i.links;return e.count+t.count+n.count+s.count}function xt(i){return i.deletes.spool.count+i.bringBack.count+i.recreate.count+i.giveBack.beforeDeletes.count+i.giveBack.afterDeletes.count+er(i)>0}function Ki(i,e){let t=0,n=r=>(t++,r()),s=i.bulkDestroy?.bind(i);return{org:{get version(){return i.version},request:r=>n(()=>i.request(r)),query:(r,a)=>n(()=>i.query(r,a)),queryMore:r=>n(()=>i.queryMore(r)),describeGlobal:()=>n(()=>i.describeGlobal()),serverTime:()=>n(()=>i.serverTime()),userId:()=>n(()=>i.userId()),describe:r=>n(()=>i.describe(r)),update:(r,a)=>n(()=>i.update(r,a)),create:(r,a)=>n(()=>i.create(r,a)),destroy:(r,a)=>n(()=>i.destroy(r,a)),queryDeleted:r=>n(()=>i.queryDeleted(r)),...s?{bulkDestroy:async(r,a,o)=>{let d=1;try{let c=await s(r,a,o);return d=c.requests??1,c}finally{t+=d}}}:{}},undelete:r=>n(()=>e(r)),used:()=>t,add:r=>{t+=r}}}async function ka(i,e){let{checkpoint:t,orgName:n}=e;if(e.reusesPreview&&e.reusesPreview.previewId!==e.previewId)throw new Error("A rewind acts on the preview it names: the one given is another.");let s=Ki(i.org,i.undelete),r,a=await qn(Li(s.org),{act:"rewind",orgName:n,registered:e.registered,username:e.username,organizationId:t.org.organizationId,customSettings:dn(t)},{userId:async()=>r=await s.org.userId()});if(!a.allowed)return{rewound:!1,refusal:a.refusal};let o=i.store.lock(t.org.organizationId,"rewind",t.checkpointId);if("busy"in o)return{rewound:!1,refusal:Bi(n,o.busy)};let d=new Kt(i,e,s,o.lock,a.queryAllFiles,{grants:a.grants,...r!==void 0?{userId:r}:{}});try{let c=await i.runWriting?.(a.org.id);return c!==void 0?Ni("RUN_WRITING",c):await d.go()}finally{await d.cleanUp(),o.lock.release()}}var Kt=class{constructor(e,t,n,s,r,a){this.deps=e;this.request=t;this.count=n;this.lock=s;this.queryAllFiles=r;this.user=a;this.org=this.clock.watched(n.org),this.signal=e.signal,this.now=e.now??(()=>new Date),this.kept=xi(At(this.org,this.signal)),this.picked=t.objects!==void 0?new Set(t.objects):void 0}deps;request;count;lock;queryAllFiles;user;org;signal;now;notes=[];ownDirs=[];ended=!1;kept;global;cascadesOfObject=new Map;lifecycles=new Map;unqueried;noBin=new Set;splitting=Rt();stamps={};stampOf=new Map;spans=[];userId="";owners=new Set;carried=new E;comesBack=new E;before=Number.NaN;clock=new ls(()=>this.now().getTime());access=es;picked;leftFields=new Map;asked;emailsCounted;stopped(){return this.signal?.aborted===!0}progress(e,t,n,s){this.deps.onProgress?.({phase:e,pass:t,percentage:n,step:s})}describeGlobal(){return this.global??=this.org.describeGlobal()}async diff(e){let t=Ue("pv",this.now()),n=Me(this.request.folder,t);return this.ownDirs.push(n),{diff:await ss({checkpoint:this.request.checkpoint,folder:this.request.folder,reader:this.kept.reader,describeGlobal:()=>this.describeGlobal(),previewId:t,readAt:e,queryAllFiles:this.queryAllFiles,access:this.access,...this.signal?{signal:this.signal}:{}}),dir:n}}async plan(e,t,n,s){let r=await is({checkpoint:this.request.checkpoint,pass:e,confirmedDir:t,freshDir:n.dir,readAt:s,ownWriters:rt(this.request.checkpoint.takenBy,this.userId),acceptOutside:this.request.acceptOutside,acceptNoUndo:this.request.acceptNoUndo,acceptRecreate:this.request.acceptRecreate,...e===2&&Object.keys(this.stamps).length>0?{removalStamps:{...this.stamps}}:{},...e===2&&this.spans.length>0?{removalSpans:[...this.spans]}:{},...e===2?{recreated:await Be.read(this.request.folder)}:{},...this.picked!==void 0?{objects:this.picked,heldRows:as(this.request.checkpoint,this.request.folder)}:{},dir:zs(n.dir,`plan${e}-${Us(4).toString("hex")}`),...this.signal?{signal:this.signal}:{}}),a=new Map;for(let{objectApiName:o}of this.request.checkpoint.objects){let d=new E;for(let c of Hs){let p=c==="inBin"||c==="withParent";for await(let f of se(ye(r.dir,o,c)))typeof f.Id=="string"&&(d.add(f.Id),p&&this.comesBack.add(f.Id))}d.size>0&&a.set(o,d)}return{plan:r,acted:a}}async relationships(){let e=this.global,t=e?new Set((await ln({describeGlobal:()=>e})).keys()):void 0,n=new Set(this.request.checkpoint.objects.map(({objectApiName:r})=>r.toLowerCase()));if(this.request.checkpoint.files!==void 0)for(let r of[ne,an])n.add(r.toLowerCase());let s=new Map;for(let[r,a]of this.kept.bodies)s.set(r,Gn(a,{inCheckpoint:n,...t?{worked:t}:{}}));return s}async go(){let{checkpoint:e,orgName:t,folder:n}=this.request,s=await Kn(this.org,t);if(this.stopped())throw new qe;this.progress("reading",1,5,`Reading ${t} again`);let r=this.request.reusesPreview,a,o,d;try{this.access=await ts({grants:this.user.grants,...this.user.userId!==void 0?{userId:this.user.userId}:{},username:this.request.username,checkpoint:e,reader:this.kept.reader});let U=r?Mi(r,this.access):[];if(U.length>0)return{rewound:!1,refusal:Ui(t,U)};if(a=r?r.readAt:await this.org.serverTime(),this.before=Date.parse(a)-li,!Number.isFinite(this.before))throw new Error(`Not a date: ${a}`);o=r?{diff:r,dir:Me(n,this.request.previewId)}:await this.diff(a),d=await this.plan(1,Me(n,this.request.previewId),o,a)}catch(U){throw U instanceof $e||this.stopped()?new qe:U}let c=[],p=d.plan.left.filter(U=>Vs.has(U.reason));p.length>0&&c.push(Fi(p));let f=d.plan.left.filter(U=>U.reason==="recreateNotAccepted");f.length>0&&c.push(Ti(f));let u=Di(o.diff,d.plan);u.length>0&&!this.request.acceptUnseen&&c.push(Ei(this.request.username,u));let l=Vn("rewind",await this.bringBackFiles(d.plan,o.dir),s.fileStorage?.remaining,t);l&&c.push(l);let h=e.lastRewind,g=h!==void 0&&h.endedAt===void 0&&h.undoneAt===void 0,w=xt(d.plan);if(!w){let[U,...b]=c;if(U)return Gs(U,b);if(!g)return this.wroteNothing(o,d,s.remaining)}let y=Ji(d.plan),m;if(w&&this.deps.readAutomation){let U=[...new Set([...y.bringBack??[],...y.recreate??[],...y.giveBack??[],...y.setToDraft??[],...y.delete??[]])];try{m=await this.deps.readAutomation(U)}catch(b){m=Wi(U,Q(b))}this.count.add(m.requests)}let k=m,L=w?await Oi(this.deps.mute,m,y):{},S="refusal"in L?L:void 0,T="refusal"in L?void 0:L.mute;S&&c.push(S.refusal),L.automation&&(m=L.automation);let F=S?S.plan:T?.plan,P=this.request.acceptEmails===!0,j=w&&k?await Nn({act:"rewind",orgName:t,automation:k,steps:y,...F?{plan:F}:{},accepted:P,mayMute:this.deps.mute===void 0&&this.request.canMute===!0,read:()=>vn(this.org)}):void 0,z=Jn({objects:e.objects,diff:os(o.diff,this.picked),automationRequests:0,relationships:await this.relationships(),...r?{reusesPreview:!0}:{}}),q=Zn(j?.ofRun),x=Hn("rewind",{run:this.count.used()-(q.deliverability??0)+z.apiRequests,...q},s,t);w&&x&&c.push(x),this.splitting=Rt(un(s.remaining,this.count.used()+z.apiRequests));let A=Pn(d.plan.objects),B=m?Ln("rewind",Xe(A,m,s.emails),t):void 0;w&&B&&c.push(B);let G=m?An(A,m):void 0;m&&!this.request.acceptAutomation&&(kt(m,y).length>0||sn(m.unread)||G!==void 0)&&c.push(zi(t,m,y,G)),w&&j?.refusal&&c.push(j.refusal);let[v,...N]=c;if(v)return Gs(v,N);if(m&&(this.asked={automation:m,steps:y,accepted:this.request.acceptAutomation},this.emailsCounted={written:[...A],limits:s.emails}),this.stopped())throw new qe;this.userId=await this.org.userId(),this.owners=new Set(rt(e.takenBy,this.userId).map(O));let M=await Fs({folder:n,lock:this.lock,startedAt:a,userId:this.userId,...e.takenBy.automatedProcessUserId!==void 0?{automatedProcessUserId:e.takenBy.automatedProcessUserId}:{},now:this.now}),K;try{let U=await Pi(T,`rewind ${e.checkpointId} ${a}`,R=>{let C=R&&F&&k&&j?Bn({act:"rewind",orgName:t,automation:k,steps:y,plan:F,held:R.outcome,planned:j.ofRun.senders,...j.ofRun.read?{reading:j.ofRun.read.reading}:{},accepted:P}):void 0;return C?Promise.resolve({rewound:!1,refusal:C}):this.passes(M,a,o,d,s.remaining)},R=>{K=R}).catch(R=>{if(St(R))return{rewound:!1,refusal:{code:"MUTE",message:`${R.message} ${Ie}`}};throw R}),b=j?.gate.audit;return U.rewound?{...U,...K?{result:{...U.result,mutedAutomation:K}}:{},...b!==void 0?{deliverability:b}:{}}:U}finally{await M.close()}}async wroteNothing(e,t,n){let s=await this.residualOf(e,e,[t],new xe),r=this.pickedOnly(e.diff.unread),a=await this.scopeOf(e,e);return this.ended=!0,{rewound:!0,result:this.resultOf({rewindId:Ue("rw",this.now()),status:s.length>0||r.length>0?"partial":"success",tally:{deleted:[],restored:[],undeleted:[],recreated:[]},residual:s,unread:r,passes:1,leftToday:n,...a?{scope:a}:{}}),notes:this.notes}}async passes(e,t,n,s,r){let{checkpoint:a}=this.request,o=await e.read();this.addStamps(o.rewind.removalStamps??{}),this.spans.push(...o.rewind.removalSpans??[]);for(let{ids:v}of o.did.carried??[])for(let N of v)this.carried.add(N);let d=new Date(Date.parse(o.head.startedAt)+ui).toISOString(),c;await this.deps.store.update(a.checkpointId,v=>(v.lastRewind?.rewindId!==e.rewindId&&(c=v.lastRewind),{...v,lastRewind:{rewindId:e.rewindId,undoUntil:d}}));let p=xt(s.plan),f=p?await this.pass(e,s.plan,n.diff,1):new xe,u=[s],l,h,g=f.cancelled;try{if(!g&&f.wrote){this.progress("reading",2,70,`Reading ${this.request.orgName} again`);let v=await this.diff(await this.org.serverTime()),N=await this.plan(2,s.plan.dir,v,t);if(u.push(N),h=v,xt(N.plan)){let M=await this.pass(e,N.plan,v.diff,2);l={tally:M,plan:N.plan},g=M.cancelled,!g&&M.wrote&&(this.progress("checking",2,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime()))}}else!g&&p?(this.progress("checking",1,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime())):g||(h=n)}catch(v){if(!(v instanceof $e)&&!this.stopped())throw v;g=!0}this.stopped()&&(g=!0);let w=await qi({tally:f,plan:s.plan},l),y=!g&&h?await this.residualOf(h,n,u,f,l?.tally):[],m=!g&&h?this.pickedOnly(h.diff.unread):[],k=await this.scopeOf(g?void 0:h,n),L=w.deleted.some(v=>v.deleted>0)||w.restored.some(v=>v.restored+(v.restoredWithout??0)>0)||w.undeleted.some(v=>v.undeleted>0)||w.recreated.some(v=>v.created>0)||f.cameBackRestored+(l?.tally.cameBackRestored??0)>0,S=g?"cancelled":y.some(v=>v.reason==="changedDuringRewind")?"unstable":y.length>0||m.length>0?L?"partial":"failure":"success",T=this.filesOf(y,[f,...l?[l.tally]:[]]),F=(T?.unlinked??0)+(T?.relinked??0)+(T?.linksUpdated??0),P=L||F>0||(g||e.resumed)&&(await e.facts()).lastWriteAt!==void 0,j=[];if(g&&!P)try{await this.deps.store.update(a.checkpointId,v=>(delete v.lastRewind,c?{...v,lastRewind:c}:v))}catch(v){this.notes.push(`The checkpoint could not be told the rewind stopped before it wrote anything (${Q(v)}): its list may not offer to undo the rewind before it.`)}if(!g){await e.end(),this.ended=!0;let v=h?.diff.readAt??this.now().toISOString(),N=P?{rewindId:e.rewindId,endedAt:v,undoUntil:d}:c;try{await this.deps.store.update(a.checkpointId,M=>(delete M.lastRewind,N?{...M,lastRewind:N}:M))}catch(M){this.notes.push(P?`The checkpoint could not be told when the rewind ended (${Q(M)}): its list may not offer to undo it.`:`The checkpoint could not be told the rewind wrote nothing (${Q(M)}): its list may not offer to undo the rewind before it.`)}try{P&&(j=await Es(this.deps.store,this.lock,{checkpointId:a.checkpointId,rewindId:e.rewindId}))}catch(M){this.notes.push(`The journals of the earlier rewinds of ${this.request.orgName} could not be deleted (${Q(M)}): they stay until their checkpoint goes.`)}}let z=await e.read(),q=this.undoCannotOf(z),x=(z.did.carriers??[]).map(({objectApiName:v,ids:N})=>({objectApiName:v,count:N.length}));if(g){let v=new Set(z.did.deleted.flatMap(({ids:M})=>M.map(O))),N=(z.did.carriers??[]).map(({objectApiName:M,ids:K})=>({objectApiName:M,count:K.filter(U=>!v.has(O(U))).length})).filter(({count:M})=>M>0);N.length>0&&this.notes.push(`Stopped with ${N.map(({objectApiName:M,count:K})=>`${K} ${M}`).join(", ")} record(s) brought back for a moment still in the org: they had taken records of the checkpoint along. Rewind again to delete them, with what came back with them.`)}let A=new Map;for(let v of[f,...l?[l.tally]:[]])for(let[N,M]of v.draftsLeft)A.set(N,[...A.get(N)??[],...M]);let B=[...A].map(([v,N])=>({objectApiName:v,count:N.length,ids:N.slice(0,Ws)})),G={rewound:!0,result:this.resultOf({rewindId:e.rewindId,status:S,tally:w,residual:y,unread:m,passes:l?2:1,leftToday:r,...P?{undo:{until:d,cannot:q}}:{},removedJournals:j,carriers:x,draftsLeft:B,...T?{files:T}:{},...k?{scope:k}:{}}),notes:this.notes};if(L||z.lastWriteAt!==void 0&&(g||e.resumed)){let v=await us({folder:this.request.folder,lock:this.lock,checkpoint:a,result:G.result,startedAt:t,...!g&&h?{endedAt:h.diff.readAt}:{},clock:this.clock});v!==void 0&&this.notes.push(v)}if(!P){await e.close();try{await $s(je(this.request.folder,e.rewindId),{recursive:!0,force:!0})}catch(v){this.notes.push(`The journal of this rewind, which wrote nothing, could not be deleted (${Q(v)}): it stays until a later rewind that writes ends, or its checkpoint goes.`)}}return G}filesOf(e,t){if(this.request.checkpoint.files===void 0)return;let n=r=>t.reduce((a,o)=>a+o.links[r].done,0),s={unlinked:n("unlink"),relinked:n("relink"),linksUpdated:n("share"),linksRefused:e.filter(r=>r.objectApiName===ne&&r.reason==="refused").reduce((r,a)=>r+a.count,0)};return s.unlinked+s.relinked+s.linksUpdated+s.linksRefused>0?s:void 0}async bringBackFiles(e,t){let n=new E;for await(let r of e.bringBack.pages(Ae))for(let a of r)n.add(a);if(n.size===0)return{files:0,bytes:0};let s=new Map;for await(let r of se(nt(t,Ae)))typeof r.Id=="string"&&typeof r.ContentSize=="number"&&n.has(r.Id)&&s.set(O(r.Id),r.ContentSize);if(s.size<n.size&&this.request.checkpoint.files!==void 0)for await(let r of _n(this.request.folder))n.has(r.Id)&&!s.has(O(r.Id))&&r.ContentSize!==null&&s.set(O(r.Id),r.ContentSize);return{files:n.size,bytes:[...s.values()].reduce((r,a)=>r+a,0)}}undoCannotOf(e){let t=new Set(this.request.checkpoint.objects.filter(a=>!a.undeletable).map(a=>a.objectApiName)),n=new Set(e.did.broughtBack.flatMap(({ids:a})=>a.map(O))),s=new Set((e.did.deletedBeforeParent??[]).flatMap(({ids:a})=>a.map(O))),r=[];for(let{objectApiName:a,ids:o}of e.did.deleted){let d=o.map(O).filter(f=>!n.has(f)),c=d.filter(f=>s.has(f)).length,p=t.has(a)?d.length-c:0;p>0&&r.push({objectApiName:a,count:p}),c>0&&r.push({objectApiName:a,count:c,reason:"deletedBeforeParent"})}return r}resultOf(e){let t=this.count.used();return{checkpointId:this.request.checkpoint.checkpointId,rewindId:e.rewindId,status:e.status,deleted:e.tally.deleted,restored:e.tally.restored.filter(n=>n.planned>0),undeleted:e.tally.undeleted.filter(n=>n.planned>0),...e.tally.recreated.length>0?{recreated:e.tally.recreated}:{},...(e.carriers??[]).length>0?{carriers:e.carriers}:{},...(e.draftsLeft??[]).length>0?{draftsLeft:e.draftsLeft}:{},residual:e.residual,...e.unread.length>0?{unread:[...e.unread]}:{},passes:e.passes,...e.undo?{undo:e.undo}:{},...(e.removedJournals??[]).length>0?{removedJournals:e.removedJournals}:{},...e.files?{files:e.files}:{},apiRequests:{used:t,leftToday:Math.max(0,e.leftToday-t)},finishedAt:this.now().toISOString(),...e.scope?{scope:e.scope}:{}}}pickedOnly(e){let t=this.picked;return t===void 0?[...e]:e.filter(n=>t.has(n.objectApiName))}async scopeOf(e,t){let n=this.picked;if(n===void 0)return;let{checkpoint:s}=this.request,r=s.objects.map(({objectApiName:d})=>d).filter(d=>n.has(d)),a=[],o=0;if(e!==void 0){let d=[...s.objects].sort((c,p)=>c.readOrder-p.readOrder);for(let{objectApiName:c}of d){if(n.has(c))continue;let p=new E;for await(let u of se(ye(t.dir,c,"goneForGood")))typeof u.Id=="string"&&p.add(u.Id);let f=new E;for(let u of _s)for await(let l of se(ye(e.dir,c,u)))typeof l.Id!="string"||p.has(l.Id)||f.add(l.Id);f.size>0&&(a.push(c),o+=f.size)}if(s.files!==void 0&&!n.has(Ae)){let c=new E;for(let p of["linkAdded","linkRemoved","linkChanged"])for await(let f of se(Lt(e.dir,p)))typeof f.Id=="string"&&c.add(f.Id);c.size>0&&(a.push(ne),o+=c.size)}}return{objects:r,notRewound:{objects:a,records:o}}}async readLeftFields(e){let t=e.limited?.leftFields;if(!(t===void 0||t.count===0))for await(let n of se(t.file)){if(typeof n.Id!="string"||!Array.isArray(n.fields))continue;let s=this.leftFields.get(O(n.Id))??new Set;for(let r of n.fields)typeof r=="string"&&s.add(r.toLowerCase());this.leftFields.set(O(n.Id),s)}}async cleanUp(){let e=[...this.ownDirs];this.ended&&e.push(Me(this.request.folder,this.request.previewId));for(let t of e)await $s(t,{recursive:!0,force:!0}).catch(()=>{})}async pass(e,t,n,s){let r=new xe;await this.readLeftFields(t);let a={},o=l=>{Object.assign(a,l),this.addStamps(l)},d=this.allowLists(n),c=new E;for(let{objectApiName:l}of t.giveBack.afterDeletes.objects){let h=t.giveBack.heldBy.find(g=>g.objectApiName===l)?.by;for await(let g of t.giveBack.afterDeletes.pages(l)){for(let w of g)c.add(w);h&&await e.heldInPlace(l,h,g)}}await this.keepFirst(e,t.giveBack.afterDeletes,d);let p=this.request.acceptRecreate?new Ce(zs(t.dir,`remake-${Us(4).toString("hex")}`)):void 0,f=async()=>{t.bringBack.count>0&&(this.progress("bringingBack",s,s===1?25:80,"Bringing back what was deleted since"),await this.bringBack(e,t.bringBack,t.carriers,r,o,p));let l=p&&p.objects.length>0?await this.withPlanned(p,t.recreate):t.recreate;if(!r.cancelled&&!this.stopped()&&l.count>0)this.progress("recreating",s,s===1?32:81,"Making again what the recycle bin no longer holds"),await this.recreate(e,l,r);else if(l.count>0){for(let{objectApiName:h,count:g}of l.objects)r.recreate({...Re(h),planned:g,notReached:g});r.cancelled=!0}return!r.cancelled&&!this.stopped()&&t.giveBack.beforeDeletes.count>0&&(this.progress("givingBack",s,s===1?40:82,"Giving back what was changed since"),await this.giveBack(e,t,t.giveBack.beforeDeletes,"before",d,c,r,o)),r.wrote},u;if(t.deletes.spool.count>0){this.progress("deleting",s,s===1?55:85,"Deleting what was created since");for(let{objectApiName:w,file:y}of t.beforeParent){let m=[];for await(let k of se(y)){let L=Array.isArray(k.parents)?k.parents:[];for(let S of L)typeof k.Id=="string"&&typeof S=="string"&&m.push({id:k.Id,parent:S});m.length>=J&&await e.beforeParent(w,m.splice(0))}m.length>0&&await e.beforeParent(w,m)}await e.deleting(t.deletes);let l={...this.stamps,...t.removal.removalStamps},h=[...this.spans,...t.removal.removalSpans??[]].filter((w,y,m)=>m.findIndex(k=>JSON.stringify(k)===JSON.stringify(w))===y),g=(w,y)=>{if(typeof w.Id!="string"||!this.carried.has(w.Id)&&!t.goesAlong.has(w.Id))return!1;let m=pt(w.LastModifiedDate??w.SystemModstamp);return m<=y||m<=(this.stampOf.get(O(w.Id))??Number.NaN)};u=await Ve(this.org,t.deletes,{splitting:this.splitting,runStartedAt:t.removal.runStartedAt,runEndedAt:t.removal.runEndedAt,includeChanged:t.removal.includeChanged,alongAccepted:!0,...Object.keys(l).length>0?{removalStamps:l}:{},...h.length>0?{removalSpans:h}:{},...this.carried.size+t.carriers.size+t.goesAlong.size>0?{goesWithParent:g}:{},...t.alongToDraft.spool.count>0?{alongToDraft:t.alongToDraft}:{},...t.bringBack.count+t.recreate.count+t.giveBack.beforeDeletes.count>0?{sweep:f}:{},...this.deps.onUndeletable?{onUndeletable:this.deps.onUndeletable}:{},...this.signal?{signal:this.signal}:{},onProgress:(w,y,m)=>this.progress("deleting",s,s===1?55:85,`Deleting ${m}: ${w} / ${y}`)}),await e.deleted(u),r.delete(u.objects);for await(let{objectApiName:w,ids:y}of u.left())r.leftBy("removal",w,y);u.cancelled&&(r.cancelled=!0),(u.objects.some(w=>w.deleted>0)||u.span)&&(r.wrote=!0),o(u.stamps),u.span&&this.spans.push(u.span)}else this.stopped()?r.cancelled=!0:await f();return!r.cancelled&&!this.stopped()&&t.giveBack.afterDeletes.count>0&&(this.progress("givingBack",s,s===1?65:88,"Giving back what the deleted records held in place"),await this.giveBack(e,t,t.giveBack.afterDeletes,"after",d,c,r,o)),!r.cancelled&&!this.stopped()&&er(t)>0&&(this.progress("givingBack",s,s===1?68:89,"Putting back the links between files and records"),await this.writeLinks(e,t,r)),this.stopped()&&(r.cancelled=!0),await e.removal({removalStamps:a,removalSpans:u?.span?[u.span]:[]}),r}async writeLinks(e,t,n){let s=()=>this.stopped(),r=async d=>{d!==0&&(n.wrote=!0,await e.wrote())},a=await xs(t.links.unlink.file,"linkAdded"),o=new Set(a.map(d=>O(d.Id)));for(let d of await this.heldLinksOf(t.links.unlinkFrom,t))o.has(O(d.Id))||a.push(d);if(n.links.unlink=await at(this.org,a,{before:d=>e.unlinking(d),after:async({done:d,left:c})=>{c.length>0&&await e.unlinkLeft(c),await r(d.length)},stopped:s}),n.links.unlink.cancelled&&(n.cancelled=!0),!n.cancelled&&t.links.relink.count>0){let d=await Be.read(this.request.folder);n.links.relink=await dt(this.org,await xs(t.links.relink.file,"linkRemoved"),{after:async({made:c})=>{c.length>0&&await e.relinked(c),await r(c.length)},stopped:s},c=>d.currentOf(O(c))??c),n.links.relink.cancelled&&(n.cancelled=!0)}if(!n.cancelled&&t.links.share.count>0){let d=await Ai(t.links.share.file),c=new Map(d.map(p=>[O(p.Id),p.now]));n.links.share=await ct(this.org,d,{before:p=>e.linksUpdating(p.map(f=>({...f,...c.get(O(f.Id))??{}}))),after:async({done:p,left:f})=>{f.length>0&&await e.linksUpdateLeft(f),await r(p.length)},stopped:s}),n.links.share.cancelled&&(n.cancelled=!0)}}async heldLinksOf(e,t){if(e.count===0)return[];let n=ji.safeParse(await this.describeGlobal()),s=zn(n.success?n.data.sobjects:[],this.request.checkpoint.objects.map(({objectApiName:a})=>a)),r=[];for await(let a of e.pages(Ae,jt))for(let o of ge(a,jt)){let d=await this.org.query(`SELECT ${$n.join(", ")} FROM ${ne} WHERE ContentDocumentId IN (${o})`);for(;;){for(let c of d.records){let p=we.safeParse(c);!p.success||Wn(p.data,s)===void 0||t.deletes.has(O(p.data.LinkedEntityId))||r.push(p.data)}if(d.done||!d.nextRecordsUrl)break;d=await this.org.queryMore(d.nextRecordsUrl)}}return r}allowLists(e){let t=new Map(e.objects.map(s=>[s.objectApiName,new Set(s.notCompared.map(r=>r.toLowerCase()))])),n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s]));return s=>{let r=n.get(s),a=t.get(s);return Pt(s,r?.fields??[],this.request.checkpoint.ignoredFields).filter(o=>!a?.has(o.toLowerCase()))}}async keepFirst(e,t,n){for(let{objectApiName:s}of t.objects){let r=n(s);if(r.length===0)continue;let a=de(s),d=this.request.checkpoint.objects.find(f=>f.objectApiName===s)?.fields.some(f=>f===Ne)===!0,c=["Id",...r.map(de),...d?[Ne]:[]],p=async f=>(await this.org.query(f)).records;try{for await(let f of t.pages(s))for(let u of ge(f,Y)){if(this.stopped())return;let h=(await He(`SELECT ${c.join(", ")} FROM ${a} WHERE Id IN (${u})`,p)).map(g=>et(s,g,r));h.length>0&&await e.keep(s,h)}}catch(f){if(f instanceof $e)return;this.notes.push(`What the ${s} records given back after the deletions held could not be kept before the rewind wrote (${Q(f)}): Undo gives them back what they held once the deletions were through.`)}}}async cascadesOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let o=await this.kept.reader.describe(e);t="body"in o?o.body:void 0}let n=Ot.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=e===mi&&n.data.fields.some(o=>o.name===Ne),r=(n.data.childRelationships??[]).filter(o=>o.cascadeDelete===!0);if(r.length===0)return[];let a=await this.unqueriedObjects();return r.filter(o=>!a.has(o.childSObject)).map(o=>({child:o.childSObject,field:o.field,...s&&o.childSObject===yi&&o.field==="AccountId"?{persons:!0}:{}}))}unqueriedObjects(){return this.unqueried??=this.describeGlobal().then(e=>{let t=Ri.safeParse(e);return t.success?new Set(t.data.sobjects.filter(n=>n.queryable===!1).map(n=>n.name)):new Set},()=>(this.global=void 0,new Set)),this.unqueried}async insertFieldsOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let d=await this.kept.reader.describe(e);t="body"in d?d.body:void 0}let n=Ot.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=new Map(n.data.fields.map(d=>[d.name.toLowerCase(),d])),r=this.request.checkpoint.objects.find(d=>d.objectApiName===e),a=Pt(e,r?.fields??[],this.request.checkpoint.ignoredFields).filter(d=>s.get(d.toLowerCase())?.createable===!0),o=a.filter(d=>s.get(d.toLowerCase())?.type==="reference");return{fields:a.map(de),lookups:o}}async withPlanned(e,t){for(let{objectApiName:s}of t.objects)for await(let r of t.pages(s))for(let a of r)await e.add(s,a);let n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s.readOrder]));return e.finish(s=>[...s].sort((r,a)=>(n.get(a.objectApiName)??0)-(n.get(r.objectApiName)??0)))}async recreate(e,t,n){let{checkpoint:s,folder:r}=this.request,a=new E;for(let{objectApiName:u}of t.objects)for await(let l of t.pages(u))for(let h of l)a.add(h);let o=await Be.read(r),d=new Set,c=u=>o.originalOf(u.slice(0,15))??u.slice(0,15),p=[],f=new Map;for(let{objectApiName:u,count:l}of t.objects){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:l,notReached:l}),n.cancelled=!0;continue}let h;try{h=await this.insertFieldsOf(u)}catch(y){if(y instanceof $e){n.cancelled=!0,n.recreate({...Re(u),planned:l,notReached:l});continue}let m=Q(y);n.recreate({...Re(u),planned:l,refused:l,reasons:[m]});for await(let k of t.pages(u))n.leftBy("recreate",u,k);continue}let g=h.fields.find(y=>y.toLowerCase()==="status"),w=g!==void 0?await this.lifecycleOf(u):void 0;for await(let y of t.pages(u,Se)){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:y.length,notReached:y.length}),n.cancelled=!0;continue}let m=await st.read(r,s.snapshotId,u,o),k=[],L=await m.chunk(y).batches(s.snapshotId,u,Y);for await(let P of L??[])k.push(...P);let S={...Re(u),planned:y.length},T=new E;for(let P of k)typeof P.Id=="string"&&T.add(P.Id);let F=y.filter(P=>!T.has(P));F.length>0&&(S.refused+=F.length,me(S.reasons,"The checkpoint holds no values of it."),n.leftBy("recreate",u,F));for(let P=0;P<k.length;P+=Y){if(this.stopped()){let G=k.length-P;S.notReached=(S.notReached??0)+G,n.leftBy("recreate",u,k.slice(P).map(v=>String(v.Id))),n.cancelled=!0;break}let j=k.slice(P,P+Y),z=j.map(G=>m.snapshotIdOf(String(G.Id))),q=new Map,x=j.map((G,v)=>{let N=et(u,G,h.fields);delete N.Id;let M=g!==void 0&&w?on(N[g],w):void 0;g!==void 0&&M!==void 0&&(q.set(v,String(N[g])),N[g]=M),tr(N,this.leftFields.get(O(z[v])));for(let K of h.lookups){let U=N[K];if(typeof U!="string"||U.length<15||!a.has(U))continue;let b=c(U),R=d.has(b)?o.currentOf(b):void 0;if(R!==void 0){N[K]=R;continue}p.push({objectApiName:u,from:z[v].slice(0,15),field:K,target:b}),N[K]=null}return N});await e.recreating(u,z);let A=Gt(await this.org.create(u,x)),B=[];if(j.forEach((G,v)=>{let N=A[v];if(N?.success===!0&&typeof N.id=="string"){B.push({objectApiName:u,from:z[v],to:N.id});let M=q.get(v);if(g!==void 0&&M!==void 0){let K=f.get(u)??[];K.push({id:N.id,field:g,status:M}),f.set(u,K)}return}S.refused++,me(S.reasons,N?.error??"The org gave no answer for it."),n.leftBy("recreate",u,[String(G.Id)])}),B.length>0){await Be.add(r,B),await e.recreated(u,B.map(G=>({from:G.from,id:G.to}))),await e.wrote(),n.wrote=!0,S.created+=B.length;for(let G of B)d.add(G.from.slice(0,15));o=await Be.read(r)}}n.recreate(S)}}await this.fillOwed(p,o,d,n),await this.giveStatusesBack(f,n)}lifecycleOf(e){let t=Ke[e];if(t===void 0)return Promise.resolve(void 0);let n=this.lifecycles.get(e);return n||(n=rn(async s=>(await this.org.query(s)).records,t),this.lifecycles.set(e,n)),n}async giveStatusesBack(e,t){let n=[...e];for(let[s,[r,a]]of n.entries())for(let o=0;o<a.length;o+=Y){if(this.stopped()){let f=[[r,a.slice(o)],...n.slice(s+1)];for(let[u,l]of f)l.length!==0&&t.draftsLeft.set(u,[...t.draftsLeft.get(u)??[],...l.map(({id:h})=>h)]);return}let d=a.slice(o,o+Y),c=Gt(await this.org.update(r,d.map(({id:f,field:u,status:l})=>({Id:f,[u]:l})))),p=t.recreated.get(r);d.forEach(({id:f},u)=>{let l=c[u];l?.success!==!0&&(p&&me(p.reasons,`Made again as a draft, but its status was refused: ${l?.error??"the org gave no answer for it."}`),t.leftBy("recreate",r,[f]))})}}async fillOwed(e,t,n,s){let r=new Map;for(let{objectApiName:a,from:o,field:d,target:c}of e){if(!n.has(o)||!n.has(c))continue;let p=t.currentOf(o),f=t.currentOf(c);if(p===void 0||f===void 0)continue;let u=r.get(a)??new Map;u.set(p,{...u.get(p),Id:p,[d]:f}),r.set(a,u)}for(let[a,o]of r){let d=[...o.values()];for(let c=0;c<d.length;c+=Y){if(this.stopped())return;let p=d.slice(c,c+Y),f=Gt(await this.org.update(a,p)),u=s.recreated.get(a);f.forEach((l,h)=>{l.success||(u&&me(u.reasons,`Made again, but a lookup to a record made after it was refused: ${l.error}`),s.leftBy("recreate",a,[String(p[h].Id)]))})}}}async bringBack(e,t,n,s,r,a){let o=At(this.org),d=this.makesAgain();for(let{objectApiName:c,count:p}of t.objects){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:p,notReached:p}),s.cancelled=!0;continue}let f;try{f=await this.cascadesOf(c)}catch(l){f=[],this.notes.push(`The records that come back with ${c} could not be told (${Q(l)}): Undo may not send those ${c} records back to the recycle bin.`)}let u=async function*(){for await(let l of t.pages(c,Se)){let h=l.filter(w=>n.has(w));h.length>0&&(yield{ids:h,asCarriers:!0});let g=h.length>0?l.filter(w=>!n.has(w)):l;g.length>0&&(yield{ids:g,asCarriers:!1})}};for await(let{ids:l,asCarriers:h}of u()){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:l.length,notReached:l.length}),s.cancelled=!0;continue}let g=e.bringingBack([{objectApiName:c,ids:l}],this.count.undelete,{carriers:h}),w=new Map,y=new Map,m=async S=>{let{byParent:T,under:F}=await this.nameChildren(e,o,f,c,S,h),P=await g(S);r(await this.undeleteStamps(c,S,T));for(let j of Si(P,S))w.set(O(j),F.get(O(j))??[]);for(let j of Ii(P,S))y.set(O(j),{id:j,under:F.get(O(j))??[]});return P},k=await zt(this.org,await Ze({org:this.org,plan:[{objectApiName:c,ids:l}],undelete:m,...this.signal?{signal:this.signal}:{}}),[{objectApiName:c,ids:l}],this.notes);await this.notBroughtBack(e,c,y,k.left);let L=await this.settleGone(c,k,w,s,a,d);for(let S of L.objects)s.undelete(S);s.leftBy("undelete",c,L.left),L.wrote&&(s.wrote=!0,await e.wrote()),L.cancelled&&(s.cancelled=!0)}}}makesAgain(){let e=new Map,{checkpoint:t,folder:n}=this.request;return async(s,r)=>{let a=t.objects.find(d=>d.objectApiName===s);if(!a||!ns(a))return!1;let o=e.get(s);return o||(o=st.read(n,t.snapshotId,s).catch(()=>{}),e.set(s,o)),(await o)?.has(r)===!0}}remakeUnaskedWords(e){let t=this.asked;if(!t)return;let n=[...new Set(e)],s=cs(t.automation,t.steps,n,t.accepted);if(!(s.fired.length===0&&!s.blind))return wi(this.request.orgName,n,s)}remakeEmailsWords(e){let t=this.emailsCounted,n=this.asked;if(!t||!n)return;let s=e.flatMap(c=>[{objectApiName:c,write:"insert",records:1},...Ke[c]!==void 0?[{objectApiName:c,write:"update",records:1}]:[]]),r=Xe(t.written,n.automation,t.limits),o=Xe([...t.written,...s],n.automation,t.limits).filter(c=>c.verdict==="exceeds");if(o.length===0){t.written.push(...s);return}return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and making it again sends ${o.map(c=>{let p=c.emails-(r.find(f=>f.limit===c.limit)?.emails??0);return`${It(p,c.limit)} more than the ${It(c.emails-p,c.limit)} it counted, past the ${c.remaining??0} of ${c.max??0} ${this.request.orgName} has left today`}).join("; ")}. Rewind again: its preview counts it to make again, and its emails.`}async settleGone(e,t,n,s,r,a){let o=t.left.filter(h=>n.has(O(h)));if(o.length===0)return t;let d=new Set,c=0,p=0,f,u=h=>this.access.heldAs(h)==="parent";await this.keepNotInBin(e,o);for(let h of o){if(u(e)){p++,s.mark("outOfReach",e,h);for(let m of n.get(O(h))??[])s.mark("outOfReach",m.objectApiName,m.id);continue}if(!await a(e,h)){s.mark("lost",e,h);continue}let g=[];for(let m of n.get(O(h))??[])u(m.objectApiName)?s.mark("outOfReach",m.objectApiName,m.id):await a(m.objectApiName,m.id)&&g.push(m);let w=[e,...g.map(m=>m.objectApiName)],y=r?this.remakeUnaskedWords(w)??this.remakeEmailsWords(w):void 0;if(r&&y===void 0){await r.add(e,h);for(let m of g)await r.add(m.objectApiName,m.id);d.add(O(h));continue}if(y!==void 0){f=y,s.notAsked.set(O(h),y);for(let m of g)s.notAsked.set(O(m.id),y);continue}c++,s.mark("notInBin",e,h);for(let m of g)s.mark("notInBin",m.objectApiName,m.id)}let l=o.length-d.size;return{...t,objects:t.objects.map(h=>{if(h.objectApiName!==e)return h;let g=l===0?h.reasons.filter(w=>!_e.test(w)):c>0?h.reasons.map(w=>_e.test(w)?gi:w):f!==void 0?h.reasons.map(w=>_e.test(w)?f??w:w):p>0?h.reasons.map(w=>_e.test(w)?Jt:w):h.reasons;return{...h,planned:h.planned-d.size,refused:Math.max(0,h.refused-d.size),reasons:g}}),left:t.left.filter(h=>!d.has(O(h)))}}async notBroughtBack(e,t,n,s){if(n.size===0)return;let r=new Set(s.map(O)),a=new Map,o=(d,c)=>{let p=a.get(d)??[];p.push(c),a.set(d,p)};for(let[d,{id:c,under:p}]of n)if(r.has(d)){o(t,c);for(let f of p)o(f.objectApiName,f.id)}try{for(let[d,c]of a)await e.bringBackLeft(d,c)}catch(d){this.notes.push(`Which ${t} records ${this.request.orgName} refused to bring back could not be kept in the rewind\u2019s journal (${Q(d)}): its undo may count them among what it sends back to the recycle bin.`)}}async keepNotInBin(e,t){try{await Un.add(this.request.folder,e,t)}catch(n){this.notes.push(`The ${e} records ${this.request.orgName} answered are no longer in the recycle bin could not be kept with the checkpoint (${Q(n)}): a later preview counts them to bring back again.`)}}async nameChildren(e,t,n,s,r,a=!1){let o=new Map,d=new Map,c=new Set(r.map(O)),p=new Map(r.map(h=>[O(h),O(h)])),f=new Map,u=new Map,l=[{objectApiName:s,cascades:n,ids:[...r]}];for(;l.length>0;){let h=new Map;for(let{objectApiName:g,cascades:w,ids:y}of l)for(let m of ge(y,Y)){let k=w.filter(({child:T})=>!this.noBin.has(T));if(k.length===0)break;let L=k.map(({child:T,field:F,persons:P})=>({objectApiName:T,soql:`SELECT Id, ${de(F)}${P?`, ${Ne}`:""}${qt(T)?", IsDeleted":""} FROM ${de(T)} WHERE ${F} IN (${m})${qt(T)?"":" AND IsDeleted = true"}`,scanAll:!0}));(await Dn(t,L,(T,F)=>{let{child:P,field:j,persons:z}=k[T];for(let q of F){let x=q[j];if(typeof q.Id!="string"||typeof x!="string"||qt(P)&&q.IsDeleted!==!0)continue;let A=O(q.Id),B=p.get(O(x));B===void 0||c.has(A)||(c.add(A),p.set(A,B),o.set(B,[...o.get(B)??[],q.Id]),!(z&&q[Ne]===!0)&&(d.set(B,[...d.get(B)??[],{objectApiName:P,id:q.Id}]),f.set(P,[...f.get(P)??[],q.Id]),u.set(P,[...u.get(P)??[],a?O(x):B]),h.set(P,[...h.get(P)??[],q.Id])))}})).forEach((T,F)=>{if(!T.read){if(vi.test(T.reason)){this.noBin.add(k[F].child);return}this.notes.push(`The ${k[F].child} records that come back with ${g} could not be read (${T.reason}): Undo may not send those ${s} records back to the recycle bin.`)}})}l=[];for(let[g,w]of h)l.push({objectApiName:g,cascades:await this.cascadesUnder(g),ids:w})}for(let[h,g]of f)await e.withParent(h,g,u.get(h),{carriers:a});if(a)for(let h of o.values())for(let g of h)this.carried.add(g);return{byParent:o,under:d}}cascadesUnder(e){let t=this.cascadesOfObject.get(e);return t||(t=this.cascadesOf(e).catch(n=>(this.notes.push(`The records that come back with ${e} records could not be told (${Q(n)}): Undo may not send them back to the recycle bin.`),[])),this.cascadesOfObject.set(e,t)),t}async undeleteStamps(e,t,n){let s={},r=de(e);try{for(let a of ge(t,Y)){let o=await this.org.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${a})`);for(let d of o.records)if(!(typeof d.Id!="string"||typeof d.LastModifiedDate!="string")){s[d.Id]=d.LastModifiedDate;for(let c of n.get(O(d.Id))??[])s[c]=d.LastModifiedDate}}}catch(a){this.notes.push(`What bringing back ${e} records left on them could not be read (${Q(a)}): the second pass may read them as changed by someone else.`)}return s}async giveBack(e,t,n,s,r,a,o,d){let{checkpoint:c,folder:p}=this.request;for(let{objectApiName:f,count:u}of n.objects){if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:u,notReached:u}),o.cancelled=!0;continue}let l=r(f),h=await st.read(p,c.snapshotId,f),g=t.giveBack.heldBy.find(y=>y.objectApiName===f),w=l.find(y=>y.toLowerCase()==="status");for await(let y of n.pages(f,Se)){let m=y.filter(j=>!h.retired(j));if(m.length===0)continue;if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:m.length,notReached:m.length}),o.cancelled=!0;continue}let k=async(j,z,q,x)=>{let A=await Ye({org:this.org,plan:[{objectApiName:f,backup:c.snapshotId,ids:[...j]}],backups:Hi(h.chunk(j),f,z,q,this.leftFields),fields:{[f]:[...z]},changedAfter:t.restore.changedAfter,ownWriters:rt(c.takenBy,this.userId),includeChanged:!1,stamps:{...t.restore.stamps,...this.stamps},keep:e.keep,stampsFor:()=>!0,...x?{counted:x}:{},...this.signal?{signal:this.signal}:{}});return d(A.stamps),A.wrote&&(o.wrote=!0,await e.wrote()),A.cancelled&&(o.cancelled=!0),A};if(f==="Order"&&w!==void 0&&(await k(m,[w],j=>j[w]==="Draft"),o.cancelled))continue;let L=s==="before"?m.filter(j=>a.has(j)):[];if(L.length>0&&(await k(L,l),o.cancelled))continue;let S=L.length>0?m.filter(j=>!a.has(j)):m;if(S.length===0)continue;let T={restored:[],alreadyGone:[]},F=await k(S,l,void 0,(j,z)=>{this.comesBack.has(j)&&T[z].push(j)});for(let j of F.objects)o.restore(j,T);o.leftBy("restore",f,F.left);let P=F.objects[0];if(s==="after"&&g&&P&&P.refused+(P.restoredWithout??0)>0){let j=o.heldInPlace.get(f)??{reason:rs(f,g.by),ids:new E};for(let z of F.left)j.ids.add(z);o.heldInPlace.set(f,j)}}}}async residualOf(e,t,n,s,r){let a=new Map,o=(u,l,h,g={})=>{let w=`${u}\0${l}\0${g.by??""}\0${g.message??""}`,y=a.get(w);y||(y={objectApiName:u,reason:l,...g.by!==void 0?{by:g.by}:{},count:0,ids:[],...g.message!==void 0?{message:g.message}:{}},a.set(w,y)),y.count++,y.ids.length<Ws&&y.ids.push(h)},d=n[n.length-1],c=r?[r,s]:[s],p=[...this.request.checkpoint.objects].sort((u,l)=>u.readOrder-l.readOrder),f=await this.throughCarriers(e.dir);for(let u of p){let l=u.objectApiName;if(this.picked!==void 0&&!this.picked.has(l))continue;let h=[];for(let m of _s)for await(let k of se(ye(e.dir,l,m)))typeof k.Id=="string"&&(m==="comesBackWithParent"&&f.has(k.Id)||h.push({cls:m,id:k.Id}));if(h.length===0)continue;let g=await this.whoChanged(e.dir,l,h),w=this.keptOf(d,l),y=new E;for await(let m of se(ye(t.dir,l,"goneForGood")))typeof m.Id=="string"&&y.add(m.Id);for(let{cls:m,id:k}of h){if(y.has(k))continue;if(m==="goneForGood"){o(l,"goneForGood",k);continue}let L=pi[m];if(L!==void 0){o(l,"kept",k,{message:L});continue}let S=g.get(O(k)),T=pt(S?.at)>this.before,F=T&&this.isOwn(k,S);if(T&&!F){o(l,"changedDuringRewind",k,S?.by?{by:S.by}:{});continue}let P=n.map(({plan:A})=>A.limited?.why.get(O(k))).find(A=>A!==void 0);if(P!==void 0){o(l,"kept",k,{message:P});continue}if(!n.some(({acted:A})=>A.get(l)?.has(k)===!0)){o(l,F?"automation":"changedSincePreview",k);continue}let z=w(k,m);if(z!==void 0){o(l,"kept",k,{message:z});continue}if(m==="withParent"&&c.some(A=>A.left.restore.get(l)?.has(k)===!0)){o(l,"refused",k,{message:this.refusalOf(c,"restore",l,k)});continue}if(F){o(l,"automation",k);continue}if(ft[m]==="undelete"||m==="toRecreate"){if(c.some(B=>B.outOfReach.get(l)?.has(k)===!0)){o(l,"kept",k,{message:Jt});continue}if(c.some(B=>B.lost.get(l)?.has(k)===!0)){o(l,"goneForGood",k);continue}let A=c.map(B=>B.notAsked.get(O(k))).find(B=>B!==void 0);if(A!==void 0){o(l,"kept",k,{message:A});continue}if(c.some(B=>B.notInBin.get(l)?.has(k)===!0)){o(l,"notInBin",k);continue}}let q=ft[m]==="undelete"&&c.some(A=>A.left.recreate.get(l)?.has(k)===!0)?"recreate":ft[m],x=q==="removal"?this.keptForDependents(c,l,k):void 0;if(x!==void 0){o(l,"kept",k,{message:hi(x)});continue}o(l,"refused",k,{message:q?this.refusalOf(c,q,l,k):_t})}}return await this.linksStillDiffering(e.dir,n,c,o),[...a.values()]}async linksStillDiffering(e,t,n,s){if(this.request.checkpoint.files===void 0||this.picked!==void 0&&!this.picked.has(Ae))return;let r=d=>`${O(d.ContentDocumentId)}:${O(d.LinkedEntityId)}`,a=new Set;for(let{plan:d}of t)for(let{file:c}of[d.links.unlink,d.links.relink,d.links.share])for await(let p of se(c)){let f=we.safeParse(p);f.success&&a.add(r(f.data))}let o=new Map;for(let d of[...n].reverse())for(let c of["unlink","relink","share"])for(let{id:p,reason:f}of d.links[c].left)o.set(O(p),f);for(let d of["linkAdded","linkRemoved","linkChanged"])for await(let c of se(Lt(e,d))){let p=we.safeParse(c);if(!p.success)continue;let f=p.data,u=d==="linkChanged"?Nt.safeParse(c):void 0;if(u?.success===!0&&u.data.now.Visibility===f.Visibility&&u.data.now.ShareType!==f.ShareType&&f.LinkedEntityId.startsWith(ki)){s(ne,"kept",f.Id,{message:it});continue}if(d==="linkAdded"&&f.LinkedEntityId.startsWith(bi)){s(ne,"kept",f.Id,{message:Bt});continue}if(!a.has(r(f))){s(ne,"changedSincePreview",f.Id);continue}s(ne,"refused",f.Id,{message:o.get(O(f.Id))??_t})}}async throughCarriers(e){let t=new E,n=this.request.checkpoint.objects;for(let{objectApiName:s}of n)for await(let r of se(ye(e,s,"carrier")))typeof r.Id=="string"&&t.add(r.Id);for(let s=t.size>0;s;){s=!1;for(let r of n){let a=new E;for await(let o of se(ye(e,r.objectApiName,"comesBackWithParent")))typeof o.Id=="string"&&a.add(o.Id);if(a.size!==0)for await(let o of se(nt(e,r.objectApiName)))typeof o.Id!="string"||!a.has(o.Id)||t.has(o.Id)||r.cascadeParents.some(d=>t.has(o[d]))&&(t.add(o.Id),s=!0)}}return t}async whoChanged(e,t,n){let s=new Set(n.map(({id:a})=>O(a))),r=new Map;for(let a of[Mn(e,t),nt(e,t)])for await(let o of se(a))typeof o.Id!="string"||!s.has(O(o.Id))||r.set(O(o.Id),{...typeof o.LastModifiedById=="string"?{by:o.LastModifiedById}:{},...typeof o.LastModifiedDate=="string"?{at:o.LastModifiedDate}:{}});return r}isOwn(e,t){return t?.by!==void 0&&this.owners.has(O(t.by))?!0:pt(t?.at)<=(this.stampOf.get(O(e))??Number.NaN)}addStamps(e){for(let[t,n]of Object.entries(e)){this.stamps[t]=n;let s=pt(n),r=O(t);Number.isFinite(s)&&!((this.stampOf.get(r)??Number.NEGATIVE_INFINITY)>s)&&this.stampOf.set(r,s)}}keptOf(e,t){let n=e.plan.left.filter(s=>s.objectApiName===t&&Wt[s.reason]!==void 0);return(s,r)=>{if(n.length===0)return;let a=n.find(o=>o.ids.some(d=>O(d)===O(s)));if(a)return Wt[a.reason];if(ft[r]==="removal"&&!e.plan.deletes.has(O(s)))return Wt[n[0].reason]}}keptForDependents(e,t,n){for(let s of e){if(s.left.removal.get(t)?.has(n)!==!0)continue;let r=s.deleted.get(t);return r&&r.refused===0&&r.keptDependents>0&&r.heldBy.length>0?r.heldBy:void 0}}refusalOf(e,t,n,s){let r=t==="restore"?e.map(a=>a.heldInPlace.get(n)).find(a=>a?.ids.has(s)===!0)?.reason:void 0;for(let a of e){if(a.left[t].get(n)?.has(s)!==!0)continue;let d=(t==="restore"?a.restored.get(n)?.reasons:t==="undelete"?a.undeleted.get(n)?.reasons:t==="recreate"?a.recreated.get(n)?.reasons:a.deleted.get(n)?.reasons)?.find(c=>c!==r);if(d!==void 0)return r?`${d} \u2014 ${r}`:d}return r??_t}};function Hi(i,e,t,n,s){return{batches:async(r,a,o)=>{let d=await i.batches(r,a,o);return d?{async*[Symbol.asyncIterator](){for await(let c of d){let p=c.filter(f=>n?.(f)??!0).map(f=>tr(et(e,f,t),typeof f.Id=="string"?s?.get(O(f.Id)):void 0));p.length>0&&(yield p)}}}:null}}}function tr(i,e){if(e===void 0)return i;for(let t of Object.keys(i))t!=="Id"&&e.has(t.toLowerCase())&&delete i[t];return i}var Vi=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function Gt(i){return(Array.isArray(i)?i:[i]).map(t=>{let n=Vi.safeParse(t);if(!n.success)return{success:!1};let{success:s,id:r,errors:a}=n.data,o=(a??[]).map(d=>typeof d=="string"?d:[d.statusCode,d.message].filter(c=>c).join(": ")).filter(d=>d!=="");return{success:s,...typeof r=="string"?{id:r}:{},...o.length>0?{error:o.join("; ")}:{}}})}export{wo as a,mo as b,yo as c,Fo as d,Ws as e,fi as f,Jt as g,gi as h,wi as i,ya as j,Oi as k,Pi as l,qe as m,$i as n,Wi as o,Js as p,Ki as q,ka as r};
11
+ `).join(""))),{count:e.length,pages:async function*(){if(e.length===0)return;let n=[];for await(let s of nt(i))n.push(t(s)),n.length>=J&&(yield n,n=[]);n.length>0&&(yield n)}}}async function Hr(i,e){let t=new Map,n=new Map,s=new Map,r=new Set,a=new Set,o=new Set,d=new Set;await ke(i,u=>{switch(u.kind){case"unlinking":for(let l of u.links)t.has(W(l.Id))||t.set(W(l.Id),l);break;case"unlinkLeft":for(let l of u.ids)t.delete(W(l));break;case"relinked":for(let l of u.ids)n.set(W(l),{Id:l});break;case"linksUpdating":r=new Set;for(let l of u.links)s.has(W(l.Id))||(s.set(W(l.Id),l),r.add(W(l.Id)));break;case"linksUpdateLeft":for(let l of u.ids)r.has(W(l))&&s.delete(W(l));break;case"linksUndone":{let l=u.part==="reinserted"?a:u.part==="removed"?o:d;for(let h of u.ids)l.add(W(h));break}default:break}});for(let u of[...n.keys()])t.has(u)&&(n.delete(u),t.delete(u));let c=[...t].filter(([u])=>!a.has(u)).map(([,u])=>u),p=[...n].filter(([u])=>!o.has(u)).map(([,u])=>u),f=[...s].filter(([u])=>!d.has(u)).map(([,u])=>u);if(c.length+p.length+f.length!==0)return{reinsert:await Ft(ee(e,"links.reinsert.ndjson"),c,u=>we.parse(u)),remove:await Ft(ee(e,"links.remove.ndjson"),p,u=>({Id:_({Id:Ps}).parse(u).Id})),share:await Ft(ee(e,"links.share.ndjson"),f,u=>Ls.parse(u))}}function ys(i,e){let t=new Map(i.map(s=>[s.objectApiName,s.readOrder])),n=s=>t.get(s)??-1;return s=>[...s].sort((r,a)=>e?n(a.objectApiName)-n(r.objectApiName):n(r.objectApiName)-n(a.objectApiName))}async function $t(i,e,t){let n=ee(i,Te),s=ee(i,`undo-${ks(4).toString("hex")}`),r=()=>vs(s,{recursive:!0,force:!0});try{let a=b=>{if(b===void 0)return()=>!0;let R=new E;for(let C of b)R.add(C);return C=>R.has(C)},o=a(e.undo.removalLeft),d=a(e.undo.undeleteLeft),c=a(e.undo.restoreLeft),p=new E,f=new Set,u=new Map,l=new E,h=new Map,g=new E,w=new Set,y=new Map;await ke(n,b=>{switch(b.kind){case"bringBackLeft":for(let R of b.ids)w.add(W(R));break;case"bringingBack":case"withParent":case"recreated":for(let R of b.ids)p.add(R),w.size>0&&w.delete(W(R));b.kind==="withParent"&&b.carriers===!0&&b.parents&&b.ids.forEach((R,C)=>{let te=b.parents?.[C];te!==void 0&&!y.has(W(R))&&y.set(W(R),{objectApiName:b.objectApiName,id:R,parent:W(te)})});break;case"givingBack":for(let R of b.ids)g.add(R);break;case"deleteLeft":{let R=u.get(b.step)??new E;for(let C of b.ids)R.add(C);u.set(b.step,R);break}case"deleted":f.add(b.step);break;case"heldInPlace":{for(let C of b.ids)l.add(C);let R=h.get(b.objectApiName)??new Set;for(let C of b.by)R.add(C);h.set(b.objectApiName,R);break}default:break}});let m=b=>p.has(b)&&!w.has(b),k=new E,L=new Be(ee(s,"bringBack"));await ke(n,async b=>{if(b.kind!=="deleting")return;let R=f.has(b.step)?u.get(b.step):void 0;for(let C of b.ids){if(R?.has(C)===!0)continue;let te=W(C);m(te)?k.add(C):d(te)&&await L.add(b.objectApiName,C)}});let S=new E;for(let b=y.size>0;b;){b=!1;for(let{id:R,parent:C}of y.values())S.has(R)||g.has(R)||(k.has(C)||S.has(C))&&(S.add(R),b=!0)}let T=b=>k.has(b)||S.has(b),F=b=>!w.has(b)&&!T(b)&&o(b),P=new E,j=new E;await ke(n,b=>{b.kind!=="withParent"||b.parents===void 0||b.ids.forEach((R,C)=>{if(!j.add(R))return;let te=W(b.parents?.[C]??"");F(W(R))&&m(te)&&F(te)&&P.add(R)})});let z=new E,q=new Map;for(let{objectApiName:b,id:R,parent:C}of y.values())!F(W(R))||P.has(R)||!g.has(R)||F(C)&&y.has(C)||(z.add(R),q.set(b,(q.get(b)??0)+1));let x=new Be(ee(s,"remove")),A=new Be(ee(s,"giveBack")),B=new E,G=new Map,v=await Mt.written(ee(s,"goesWithParent"),async b=>{await ke(n,async R=>{if(R.kind==="givingBack"){for(let C of R.ids)c(W(C))&&await A.add(R.objectApiName,C);return}if(R.kind==="recreated"){for(let C of R.ids)!F(W(C))||!await x.add(R.objectApiName,C)||(B.add(C),G.set(R.objectApiName,(G.get(R.objectApiName)??0)+1));return}if(!(R.kind!=="bringingBack"&&R.kind!=="withParent"))for(let[C,te]of R.ids.entries()){let fe=W(te);if(!F(fe))continue;let Oe=R.parents?.[C];P.has(fe)?Oe!==void 0&&await b(R.objectApiName,{id:te,parent:Oe}):await x.add(R.objectApiName,te)}})}),N=await A.finish(),M=await Hr(n,s),K=new E,U=new Map;for(let{objectApiName:b}of N.objects)for await(let R of N.pages(b))for(let C of R)l.has(C)&&(K.add(C),U.set(b,(U.get(b)??0)+1));return{remove:await En.of(x,ys(t,!1)),bringBack:await L.finish(ys(t,!0)),giveBack:N,giveBackKeys:A.keys,backup:e.head.backup,held:{keys:K,objects:[...U].map(([b,R])=>({objectApiName:b,count:R,by:[...h.get(b)??[]]}))},goesWithParent:v,remade:{keys:B,objects:[...G].map(([b,R])=>({objectApiName:b,count:R}))},compensated:{has:b=>T(W(String(b)))},carriedAlone:{keys:z,objects:[...q].map(([b,R])=>({objectApiName:b,count:R}))},...M?{links:M}:{},dispose:r}}catch(a){throw await r(),a}}async function mo(i,e,t){let n=await We(i,e);if(!n)throw new H("notFound","No journal of this rewind is kept.");return $t(n.dir,n.facts,t)}function yo(i){let e=new Map,t=s=>{let r=e.get(s);return r||(r={objectApiName:s,deleted:0,broughtBack:0,givenBack:0},e.set(s,r)),r};for(let{objectApiName:s,count:r}of i.bringBack.objects)r>0&&(t(s).deleted+=r);for(let{objectApiName:s,count:r}of i.remove.objects)r>0&&(t(s).broughtBack+=r);for(let{objectApiName:s,count:r}of i.giveBack.objects)r>0&&(t(s).givenBack+=r);for(let{objectApiName:s,count:r}of i.held.objects){let a=t(s);a.givenBackHeld=(a.givenBackHeld??0)+r}let n=i.links;if(n){let s=t(ne);s.deleted+=n.reinsert.count,s.broughtBack+=n.remove.count,s.givenBack+=n.share.count}return[...e.values()]}var Vr=50,Yr=/Entity is not in the recycle bin/,Zr="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own, then a record it hangs from was deleted after it, it can no longer come back, with that record or without; deleted with a record still in the bin, it comes back only with that record (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin')",Xr=100;function re(i){return i.slice(0,15)}var Qr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ei(i,e){return{batches:async(t,n,s)=>{let r=await i.batches(t,n,s);return r?{async*[Symbol.asyncIterator](){for await(let a of r)yield a.map(o=>Object.fromEntries(Object.entries(o).filter(([d,c])=>d==="Id"||typeof c!="string"||!Qr.test(c)||!e.has(c))))}}:null}}}function ti(i){return{objects:[],cancelled:i,gone:[],stamps:{},left:async function*(){}}}function Ds(i,e){if(e){i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}}async function*Ms(i,e,t,n=()=>!0){let s=[];for await(let r of i.pages(e,t))for(let a of r)n(re(a))&&(s.push(a),s.length>=t&&(yield s,s=[]));s.length>0&&(yield s)}function ni(i){let e=i.bringBack.objects.filter(({count:r})=>r>0).map(({objectApiName:r})=>r),t=new Set(i.held.objects.flatMap(({by:r})=>r)),n=e.findIndex(r=>t.has(r)),s=n<0||i.held.keys.size===0?e.length:n;return{bringFirst:e.slice(0,s),bringAfter:e.slice(s),held:r=>i.held.keys.has(r)}}function si(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}function ri(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);s?si(s,n):t.push({...n,reasons:[...n.reasons]})}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}function ii(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);if(!s){t.push(n);continue}s.planned+=n.planned,Ds(s,n)}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}async function zt(i,e,t,n){if(e.cancelled)return e;let s=new Set(e.left.map(re)),r=new Set,a=[];for(let o of e.objects){let d=o.reasons.find(l=>Yr.test(l));if(d===void 0||o.refused===0){a.push(o);continue}let c=t.filter(({objectApiName:l})=>l===o.objectApiName).flatMap(l=>l.ids.filter(h=>s.has(re(h)))),p=0;try{let l=de(o.objectApiName);for(let h of ge(c,Y)){let g=await i.query(`SELECT Id FROM ${l} WHERE Id IN (${h})`);for(let w of g.records)typeof w.Id!="string"||r.has(re(w.Id))||(r.add(re(w.Id)),p++)}}catch(l){n.push(`Whether the ${o.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${Q(l)}): they are counted refused.`),a.push(o);continue}let f=Math.min(p,o.refused),u=o.refused-f;a.push({...o,refused:u,alreadyBack:o.alreadyBack+f,reasons:u===0?o.reasons.filter(l=>l!==d):o.reasons.map(l=>l===d?Zr:l)})}return{...e,objects:a,left:e.left.filter(o=>!r.has(re(o)))}}async function oi(i,e,t,n){let s=new Map(n.map(o=>[re(o),o])),r=new Map,a=await i.batches(e,t,Y);for await(let o of a??[])for(let d of o){if(typeof d.Id!="string")continue;let c=s.get(re(d.Id));if(c===void 0)continue;let p=r.get(re(c))??{id:c,values:{}};for(let[f,u]of Object.entries(d))f!=="Id"&&!(f in p.values)&&(p.values[f]=u);r.set(re(c),p)}return r}async function ai(i,e,t,n,s){let r=[],a=e.backup;for(let{objectApiName:o}of e.giveBack.objects){let d=de(o),c={objectApiName:o,count:0,ids:[],by:{}};try{for await(let p of Ms(e.giveBack,o,Se,f=>!n.has(f))){let f=await oi(t,a,o,p);if(f.size===0)continue;let u=new Set;for(let{values:w}of f.values())for(let y of Object.keys(w))u.add(de(y));let l=["Id","LastModifiedById",...u],h=l.length>Xr?Y/4:Y,g=async w=>(await i.query(w)).records;for(let w of ge([...f.values()].map(y=>y.id),h)){let y=await He(`SELECT ${l.join(", ")} FROM ${d} WHERE Id IN (${w})`,g);for(let m of y){if(typeof m.Id!="string")continue;let k=f.get(re(m.Id));if(!k||!Object.entries(k.values).some(([T,F])=>!wn(F,m[T])))continue;c.count++,c.ids.length<Vr&&c.ids.push(k.id);let S=typeof m.LastModifiedById=="string"?m.LastModifiedById:"unknown";c.by[S]=(c.by[S]??0)+1}}}}catch(p){s.push(`The ${o} records the undo gave back could not be read again (${Q(p)}): whether they all hold their values from before the rewind was not checked.`)}c.count>0&&r.push(c)}return r}async function di(i,e,t,n,s){let r=new Map(Object.entries(n).map(([o,d])=>[re(o),Date.parse(d)])),a=new E;for(let{objectApiName:o}of e.objects){let d=de(o);for await(let c of e.pages(o))for(let p of ge(c,Y)){if(s?.aborted)return a;let f;try{f=(await i.query(`SELECT Id, LastModifiedDate FROM ${d} WHERE Id IN (${p})`)).records}catch{continue}for(let u of f){if(typeof u.Id!="string")continue;let l=re(u.Id),h=Date.parse(String(u.LastModifiedDate??""));(h<=t||h<=(r.get(l)??Number.NaN))&&a.add(u.Id)}}}return a}async function Fo(i){let e=await Ts(i.folder,i.rewindId,i.lock);try{let t=await e.facts(),n=await $t(e.dir,t,i.objects);try{return await ci(e,t,n,i)}finally{await n.dispose()}}finally{await e.close()}}async function ci(i,e,t,n){let{org:s,signal:r}=n,a=t.goesWithParent,o=ei(i.values,t.compensated),d={remove:t.remove.spool.count+a.count,bringBack:t.bringBack.count,giveBack:t.giveBack.count},c=[],p={...e.rewind.removalStamps,...e.undo.removalStamps},f=Object.keys(p).length>0?p:void 0,u=[...e.rewind.removalSpans??[],...e.undo.removalSpans??[]],l=mn(s),h,g=new E,w={},y=new Set(n.objects.filter(I=>I.customSetting!==void 0).map(I=>I.objectApiName)),m=I=>!y.has(I),k=ni(t),L,S,T=new Map,F=async I=>{for(let D of I)for await(let $ of t.bringBack.pages(D)){let oe=(L?.cancelled??!1)||r?.aborted===!0?{objects:[{objectApiName:D,planned:$.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,notReached:$.length,reasons:[]}],left:[...$],wrote:!1,cancelled:!0,stamps:{}}:await Ze({org:s,plan:[{objectApiName:D,ids:$}],undelete:n.undelete,...r?{signal:r}:{}});T.set(D,[...T.get(D)??[],...oe.left]),L=ri(L,oe)}return!(L?.cancelled??!1)&&r?.aborted!==!0},P=async(I,D=m)=>{for(let{objectApiName:$}of t.giveBack.objects){if(!D($))continue;let ie=de($),oe={objectApiName:$,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]},ce={objects:[oe],left:[],wrote:!1,cancelled:!1,stamps:{}};for await(let ve of Ms(t.giveBack,$,Se,I)){if(oe.planned+=ve.length,(S?.cancelled??!1)||ce.cancelled||r?.aborted){ce.cancelled=!0,oe.notReached=(oe.notReached??0)+ve.length,ce.left.push(...ve);continue}if(h!==void 0){let ir=ve.filter(or=>g.has(or));Object.assign(w,await kn(s,ie,ir,h,l))}let Vt={...p,...w},Ee=await Ye({org:s,plan:[{objectApiName:$,backup:t.backup,ids:ve}],backups:o,...e.lastWriteAt!==void 0?{lastWriteAt:e.lastWriteAt}:{},includeChanged:!1,...Object.keys(Vt).length>0?{stamps:Vt}:{},...r?{signal:r}:{}});Ds(oe,Ee.objects[0]),ce.left.push(...Ee.left),ce.wrote||=Ee.wrote,ce.cancelled||=Ee.cancelled,Object.assign(ce.stamps,Ee.stamps)}oe.planned>0&&(S=ii(S,ce))}return!(S?.cancelled??!1)&&r?.aborted!==!0},j=async()=>{if(t.bringBack.count>0&&t.giveBack.count>0){let D=await yn(s);h=Date.now()+D-vt;let $=Date.parse(e.lastWriteAt??""),ie=Number.isFinite($)?$+D+vt:Number.NEGATIVE_INFINITY;g=await di(s,t.giveBack,ie,p,r)}return await F(k.bringFirst.filter(m))&&await P(k.held)&&await F(k.bringAfter.filter(m))&&(L&&(L=await zt(s,L,[...T].map(([D,$])=>({objectApiName:D,ids:$})),c)),await P(D=>!k.held(D))),(L?.wrote??!1)||(S?.wrote??!1)},z,q=(I,D)=>{if(typeof I.Id!="string"||!a.keys.has(I.Id))return!1;if(z===void 0){let oe=new E;for(let ce of S?.left??[])oe.add(ce);z={stamps:new Map(Object.entries({...p,...w}).map(([ce,ve])=>[re(ce),Date.parse(ve)])),notGiven:oe}}let $=Date.parse(String(I.LastModifiedDate??I.SystemModstamp??"")),ie=re(I.Id);return $<=D||$<=(z.stamps.get(ie)??Number.NaN)?!0:t.giveBackKeys.has(ie)&&S!==void 0&&!z.notGiven.has(ie)},x=t.links,A={removed:ue(),reinserted:ue(),shared:ue()};if(x&&x.remove.count>0&&!r?.aborted)for await(let I of x.remove.pages())Fe(A.removed,await at(s,I,{after:async({done:D})=>{D.length>0&&await i.linksUndone("removed",D.map($=>$.Id))},stopped:()=>r?.aborted===!0}));let B;if(t.remove.spool.count>0?B=await Ve(s,t.remove,{...n.splitting?{splitting:n.splitting}:{},runStartedAt:new Date(e.head.startedAt),...e.lastWriteAt!==void 0?{runRecordedAt:new Date(e.lastWriteAt)}:{},...f?{removalStamps:f}:{},...u.length>0?{removalSpans:u}:{},includeChanged:!1,...a.count>0?{goesWithParent:q,goesWithParentReadBelow:!0}:{},...t.bringBack.count>0||t.giveBack.count>0?{sweep:j}:{},...n.onUndeletable?{onUndeletable:n.onUndeletable}:{},...r?{signal:r}:{},...n.onProgress?{onProgress:n.onProgress}:{}}):(r?.aborted||await j(),B=ti(r?.aborted===!0&&!L&&!S)),y.size>0&&!B.stoppedForUndeletable&&(await P(()=>!0,I=>y.has(I)),await F([...k.bringFirst,...k.bringAfter].filter(I=>y.has(I)))),x&&!B.stoppedForUndeletable&&!r?.aborted){let I=s.create?.bind(s);for await(let D of x.reinsert.pages()){if(!I){A.reinserted.refused+=D.length,A.reinserted.reasons.push("The links the rewind removed could not be inserted again: this connection inserts no record.");continue}Fe(A.reinserted,await dt({create:I},D,{after:async({made:$})=>{$.length>0&&await i.linksUndone("reinserted",$.map(ie=>ie.from))},stopped:()=>r?.aborted===!0}))}for await(let D of x.share.pages())Fe(A.shared,await ct(s,D.map($=>({...$,now:{ShareType:"",Visibility:""}})),{after:async({done:$})=>{$.length>0&&await i.linksUndone("shared",$.map(ie=>ie.Id))},stopped:()=>r?.aborted===!0}))}let G=x?{unlinked:A.removed.done,relinked:A.reinserted.done,linksUpdated:A.shared.done,linksRefused:A.removed.refused+A.reinserted.refused+A.shared.refused}:void 0;for(let I of[...A.removed.reasons,...A.reinserted.reasons,...A.shared.reasons])c.includes(I)||c.push(`A link between a file and a record: ${I}`);let v=new Date().toISOString();if(B.stoppedForUndeletable)return{rewindId:n.rewindId,status:"cancelled",deleted:[],restored:[],undeleted:[],residual:[],planned:d,notes:[],stoppedForUndeletable:!0,finishedAt:v};let N=[],M=new E,K=new Map,U=new Map;for await(let{objectApiName:I,ids:D}of B.left())for(let $ of D)M.add($),N.push($),t.remade.keys.has($)&&K.set(I,(K.get(I)??0)+1),t.carriedAlone.keys.has($)&&U.set(I,(U.get(I)??0)+1);let b=t.remade.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(K.get(I)??0)})).filter(({count:I})=>I>0),R=t.carriedAlone.objects.map(({objectApiName:I,count:D})=>({objectApiName:I,count:D-(U.get(I)??0)})).filter(({count:I})=>I>0),C=[];for(let{objectApiName:I}of a.objects){let D=0;for await(let $ of a.pages(I))for(let{id:ie,parent:oe}of $)M.has(oe)?N.push(ie):D++;D!==0&&C.push({objectApiName:I,planned:D,deleted:D,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})}let te=[...C,...B.objects],fe=bn(Rn(hn(te,B.cancelled),te,S),te,S,L),Oe=[];if(S&&fe!=="cancelled"){let I=new E;for(let D of S.left)I.add(D);Oe=await ai(s,t,o,I,c)}Oe.length>0&&fe==="success"&&(fe="partial"),(G?.linksRefused??0)>0&&fe==="success"&&(fe="partial");let nr=t.remove.spool.count>0,sr=S?.objects.some(I=>I.restored+(I.restoredWithout??0)>0)===!0,Ht={...w,...B.stamps},rr={...Object.keys(Ht).length>0?{removalStamps:Ht}:{},...B.span?{removalSpans:[B.span]}:{},...nr?{removalLeft:N}:{},...S?{restoreLeft:S.left}:{},...sr?{restoredAt:v}:{},...L?{undeleteLeft:L.left}:{},...L&&!L.cancelled?{undeletedAt:v}:{}};try{await i.undone(rr,fe)}catch(I){c.push(`What this undo did could not be kept in the rewind\u2019s journal (${Q(I)}): an undo after it may set out to take back what it took back already.`)}return{rewindId:n.rewindId,status:fe,deleted:te,...b.length>0?{remade:b}:{},...R.length>0?{carriedAlone:R}:{},...C.length>0?{wentAlong:C.map(({objectApiName:I,deleted:D})=>({objectApiName:I,count:D}))}:{},restored:S?.objects??[],undeleted:L?.objects??[],...G?{files:G}:{},residual:Oe,planned:d,notes:c,finishedAt:v}}var li=1e3,ui=Cn*24*60*6e4,Ws=50,Ks=5,Hs=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],_s=[...Hs.filter(i=>i!=="carrier"),"goneForGood","convertedLead","activatedContract","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach"],fi="Left in the recycle bin: deleted since by another user, which only a user with View All Data and Modify All Data restores. Not made again: it is there still.",Jt="Left as it is: out of the user's reach. Without View All Data and Modify All Data, nothing proves the user sees what others deleted of this object in the recycle bin, so it may be there out of sight, and it is never made again.",pi={convertedLead:"Left converted: Salesforce can't unconvert a lead, and refuses any update of a converted one.",activatedContract:"Left activated: Salesforce won't set an activated contract back to Draft, so it is not given back.",deletedWithCreatedParent:"Left in the recycle bin: deleted with a record created since that Salesforce does not undelete on its own, it comes back with that record only.",deletedWithParentOutside:"Left in the recycle bin: deleted with its parent, a record of an object the checkpoint does not hold, it comes back with that record only. A checkpoint that holds that object brings it back.",deletedByOther:fi,outOfReach:Jt},ft={createdSince:"removal",broughtBackSince:"removal",comesBackWithParent:"removal",giveBack:"restore",inBin:"undelete",withParent:"undelete",deletedWhileTaken:"undelete",toRecreate:"recreate",carrier:"undelete"},Wt={outsideNotAccepted:"Kept: records outside the checkpoint created since hang from it, and their deletion was not accepted.",holdsLeft:"Kept: a record the rewind left hangs from it, and its deletion would take that record along.",noUndoNotAccepted:"Kept: Undo couldn't bring it back once deleted on its own, and that was not accepted.",beforeParentNotAccepted:"Kept: Undo couldn't bring it back once deleted before a record it points at, which the rewind deletes next, and that was not accepted.",keyTaken:"Kept in the recycle bin: a row of this custom setting made or changed since holds its owner or its name, and brought back beside it the setting would hold two. It comes back once that row is gone."};function hi(i){return`Kept: records it does not delete hang from it (${i.join(", ")}), and its deletion would take them along.`}var _t="It still differs from the checkpoint once the org was read again.",_e=/Entity is not in the recycle bin/,gi="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin'). Make them again, with new Ids, or --accept-recreate on the command line, makes it again with a new Id.",Ie="No record was written.",qs=4;function wi(i,e,t){let n=e.some(o=>Ke[o]!==void 0)?"as it is created or given its status back":"as it is created",s=[...new Set(t.fired.map(o=>`${o.objectApiName}: '${o.name}'`))],r=s.length-qs;return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and ${s.length>0?`making it again runs what ${i} runs ${n} (${s.slice(0,qs).join(", ")}${r>0?` and ${r} more`:""})`:`what ${i} runs ${n} could not all be read`}, which this rewind did not ask about. Rewind again: its preview counts it to make again, and asks.`}var mi="Account",yi="Contact",ki="001",bi="005",Ri=_({sobjects:le(_({name:X(),queryable:De().optional()}).loose())}).loose(),vi=/No such column 'IsDeleted'/;function qt(i){return i.toLowerCase()===ne.toLowerCase()}function Si(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];if(typeof r!="object"||r===null)return!1;let{success:a,errors:o}=r;return a===!0?!1:(Array.isArray(o)?o:[o]).some(d=>{let c=typeof d=="string"?d:typeof d=="object"&&d!==null?String(d.message??""):"";return _e.test(c)})})}function Ii(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];return typeof r=="object"&&r!==null&&r.success===!1})}function ya(i){let e=Yn(i),t=pn(i,"Checkpoint rewind"),n=t.bulkDestroy;return{get version(){return e.version},request:s=>e.request(s),query:async(s,r)=>await i.query(s,{scanAll:r?.scanAll===!0}),queryMore:s=>e.queryMore(s),describeGlobal:()=>e.describeGlobal(),serverTime:()=>e.serverTime(),userId:()=>e.userId(),describe:s=>t.describe(s),update:(s,r)=>t.update(s,r),create:(s,r)=>i.sobject(s).create(r,{headers:tn()}),destroy:(s,r)=>t.destroy(s,r),queryDeleted:s=>t.queryDeleted(s),...n?{bulkDestroy:(s,r,a)=>n(s,r,a)}:{}}}async function Oi(i,e,t){if(!i||!e)return e?{automation:e}:{};try{let n=await i(e,bt(t));return{automation:n.automation??e,mute:n}}catch(n){if(!St(n))throw n;let s=Sn(e,bt(t));return{refusal:{code:"MUTE",message:`${n.message} ${Ie}`},automation:s.automation,plan:s.plan}}}async function Pi(i,e,t,n){let s=i?.prepared?await i.prepared.acquire(e):void 0;i&&!s&&n(i.muted);let r;try{r=await t(s)}catch(a){if(!s)throw a;let o=await s.release();throw n(o),Object.assign(a instanceof Error?a:new Error(String(a)),{mutedAutomation:o})}return s&&n(await s.release()),r}var qe=class extends Error{constructor(){super("The rewind was stopped before it wrote anything to the org."),this.name="RewindStopped"}};function O(i){return i.slice(0,15)}function pt(i){let e=cn(i);return e===null?Number.NaN:Date.parse(e)}async function*se(i){try{for await(let e of nt(i))yield e}catch(e){if(e.code!=="ENOENT")throw e}}async function xs(i,e){let t=[];for await(let n of se(i)){let s=we.safeParse(n);if(!s.success)throw new Error(`A line of ${i} names no ${e} link: the plan is not whole.`);t.push(s.data)}return t}async function Ai(i){let e=[];for await(let t of se(i)){let n=Nt.safeParse(t);if(!n.success)throw new Error(`A line of ${i} names no link: the plan is not whole.`);e.push(n.data)}return e}var ji=_({sobjects:le(_({name:X(),keyPrefix:X().nullish()}).loose())}).loose();function Li(i){return{query:e=>i.query(e),queryMore:e=>i.queryMore(e)}}function Ni(i,e){return{rewound:!1,refusal:{code:i,message:e}}}function Gs(i,e){return{rewound:!1,refusal:i,...e.length>0?{alsoRefused:[...e]}:{}}}function Bi(i,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${i} is being taken`:e.operation==="rewind"?`A rewind is writing to ${i}`:e.operation==="undo"?`An undo is writing to ${i}`:e.operation==="empty"?`An emptying of its objects is writing to ${i}`:`SandForge is deleting checkpoints of ${i}`} (process ${e.pid} on ${e.host}): rewind once it has ended. No record was read or written.`}}var Vs=new Set(["noUndoNotAccepted","beforeParentNotAccepted"]),Ci={noUndoNotAccepted:"Salesforce undeletes them only with their parent, which stays",beforeParentNotAccepted:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"};function Fi(i){return{code:"NO_UNDO",message:`${[...Vs].flatMap(t=>{let n=i.filter(a=>a.reason===t);if(n.length===0)return[];let s=n.reduce((a,o)=>a+o.count,0),r=[...new Set(n.map(a=>a.objectApiName))].join(", ");return[`Undo couldn't bring back ${s} ${r} record(s) this rewind deletes: ${Ci[t]??""}.`]}).join(" ")} Rewind refused; accept that Undo couldn't bring them back to rewind all the same. ${Ie}`}}function Ti(i){let e=i.reduce((n,s)=>n+s.count,0),t=[...new Set(i.map(n=>n.objectApiName))].join(", ");return{code:"RECREATE",message:`${e} ${t} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; accept that they get new Ids to rewind all the same. ${Ie}`}}function Ei(i,e){return{code:"UNSEEN",message:`${e.map(({objectApiName:n,children:s,records:r})=>`Deleting ${r} ${n} record(s) created since also deletes what ${i} can't see under them in ${s.join(", ")}: Rewind can't count those.`).join(" ")} Rewind refused; accept that it deletes what ${i} can't see to rewind all the same. ${Ie}`}}function Di(i,e){return(i.unseen??[]).flatMap(t=>{let n=e.objects.find(r=>r.objectApiName===t.objectApiName),s=(n?.deleted??0)+(n?.withParentDeleted??0);return s>0?[{...t,records:s}]:[]})}function Mi(i,e){if(e.kind==="org")return[];if(i.access.kind==="org")return["View All Data and Modify All Data"];let t=new Set(i.unread.map(n=>n.objectApiName));return[...e.notHeld].filter(([n])=>!t.has(n)).map(([n,s])=>`${n}: ${s}`)}function Ui(i,e){return{code:"PERMISSIONS",message:`The preview read ${i} with permissions its user no longer has (${e.join("; ")}). Preview the rewind again: it reads the org as the user can now. ${Ie}`}}var $i="accept that it runs to rewind all the same";function zi(i,e,t,n){let s=kt(e,t),r=[...new Set(s.map(d=>d.objectApiName))],a=(t.recreate??[]).length>0?"makes them again, ":"",o=s.length>0?`${ds(s)} flow(s), trigger(s) or rule(s) of ${r.join(", ")} run as the rewind brings records back, ${a}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${i}: ${o}. ${jn("rewind",n)}Rewind refused; ${$i}. ${Ie}`}}function Wi(i,e){return{objectsRead:[...i],objects:[],unread:["flows","triggers","processes","workflowRules"].map(t=>({part:t,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Js(i){return i.replace(/the value from before is no longer taken/g,"the checkpoint's value is no longer taken").replace(/left as the run wrote it\b/g,"left as it is").replace(/left as the run wrote them\b/g,"left as they are").replace(/^The values from before the run could not be read:/,"The checkpoint's values could not be read:").replace(/record\(s\) of the run stay, and were not sent\./,"record(s) the rewind would delete stay, and were not sent.")}function me(i,e){i.length<Ks&&!i.includes(e)&&i.push(e)}function ht(i,e,t){let n=t;for(let s of e){if(n<=0)return;let r=Number(i[s]??0),a=Math.min(r,n);i[s]=r-a,n-=a}}function wt(i){return{objectApiName:i,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}function Ys(i,e){i.planned+=e.planned,i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)me(i.reasons,t)}function mt(i){return{objectApiName:i,planned:0,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]}}function Zs(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Re(i){return{objectApiName:i,planned:0,created:0,refused:0,reasons:[]}}function Xs(i,e){i.planned+=e.planned,i.created+=e.created,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)me(i.reasons,t)}function Qs(i,e){i.planned+=e.planned,i.deleted+=e.deleted,i.alreadyGone+=e.alreadyGone,i.keptChanged+=e.keptChanged,i.keptDependents+=e.keptDependents,i.refused+=e.refused,e.notVisible&&(i.notVisible=(i.notVisible??0)+e.notVisible),e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.heldBy)i.heldBy.includes(t)||i.heldBy.push(t);for(let t of e.unchecked)i.unchecked.includes(t)||i.unchecked.push(t);for(let t of e.reasons)me(i.reasons,t);e.filesLeft&&(i.filesLeft={count:(i.filesLeft?.count??0)+e.filesLeft.count,names:[...i.filesLeft?.names??[],...e.filesLeft.names].slice(0,Ks)})}var xe=class{restored=new Map;undeleted=new Map;recreated=new Map;deleted=new Map;left={restore:new Map,undelete:new Map,recreate:new Map,removal:new Map};heldInPlace=new Map;notInBin=new Map;notAsked=new Map;draftsLeft=new Map;lost=new Map;outOfReach=new Map;links={unlink:ue(),relink:ue(),share:ue()};wrote=!1;cancelled=!1;leftBy(e,t,n){let s=this.left[e].get(t);s||(s=new E,this.left[e].set(t,s));for(let r of n)s.add(r)}mark(e,t,n){let s=this[e].get(t);s||(s=new E,this[e].set(t,s)),s.add(n)}cameBackGiven=new Map;cameBackRestored=0;restore(e,t){let n=this.restored.get(e.objectApiName)??wt(e.objectApiName),s=t?.restored.length??0,r=t?.alreadyGone.length??0;if(Ys(n,{...e,planned:e.planned-s-r,restored:e.restored-s,alreadyGone:e.alreadyGone-r,reasons:e.reasons.map(Js)}),this.restored.set(e.objectApiName,n),s+r===0||!t)return;let a=this.cameBackGiven.get(e.objectApiName)??new E;for(let o of[...t.restored,...t.alreadyGone])a.add(o);this.cameBackGiven.set(e.objectApiName,a),this.cameBackRestored+=s}undelete(e){let t=this.undeleted.get(e.objectApiName)??mt(e.objectApiName);Zs(t,e),this.undeleted.set(e.objectApiName,t)}recreate(e){let t=this.recreated.get(e.objectApiName)??Re(e.objectApiName);Xs(t,e),this.recreated.set(e.objectApiName,t)}delete(e){for(let t of e){let n=this.deleted.get(t.objectApiName),s={...t,reasons:t.reasons.map(Js)};n?Qs(n,s):this.deleted.set(t.objectApiName,structuredClone(s))}}};async function _i(i){let e=new Map;for(let t of i)for(let{objectApiName:n}of t.objects){let s=e.get(n)??new E;for await(let r of t.pages(n))for(let a of r)s.add(a);e.set(n,s)}return e}async function gt(i,e,t){let n=await _i(e),s=new Map,r=new Map;for(let a of i)for(let{objectApiName:o}of a.objects){let d=n.get(o);if(!d)continue;let c=s.get(o)??new E;s.set(o,c);let p=t?.get(o);for await(let f of a.pages(o))for(let u of f)d.has(u)&&p?.has(u)!==!0&&c.add(u)&&r.set(o,(r.get(o)??0)+1)}return r}async function qi(i,e){let t=i.tally,n=new Map([...t.deleted].map(([o,d])=>[o,structuredClone(d)])),s=new Map([...t.restored].map(([o,d])=>[o,structuredClone(d)])),r=new Map([...t.undeleted].map(([o,d])=>[o,structuredClone(d)])),a=new Map([...t.recreated].map(([o,d])=>[o,structuredClone(d)]));if(e){let{tally:o,plan:d}=e,c=await gt([d.giveBack.beforeDeletes,d.giveBack.afterDeletes],[i.plan.giveBack.beforeDeletes,i.plan.giveBack.afterDeletes],t.cameBackGiven);for(let[l,h]of o.restored){let g=s.get(l)??wt(l),w=c.get(l)??0;ht(g,["refused","notReached","notKept","keptChanged","restoredWithout","alreadyGone","restored"],w),g.planned-=Math.min(w,g.planned),Ys(g,h),s.set(l,g)}let p=await gt([d.bringBack],[i.plan.bringBack]);for(let[l,h]of o.undeleted){let g=r.get(l)??mt(l),w=p.get(l)??0;ht(g,["refused","notReached","goneForGood","alreadyBack","undeleted"],w),g.planned-=Math.min(w,g.planned),Zs(g,h),r.set(l,g)}let f=await gt([d.recreate],[i.plan.recreate]);for(let[l,h]of o.recreated){let g=a.get(l)??Re(l),w=f.get(l)??0;ht(g,["refused","notReached","created"],w),g.planned-=Math.min(w,g.planned),Xs(g,h),a.set(l,g)}let u=await gt([d.deletes.spool],[i.plan.deletes.spool]);for(let[l,h]of o.deleted){let g=n.get(l);if(!g){n.set(l,structuredClone(h));continue}let w=u.get(l)??0;ht(g,["refused","keptDependents","keptChanged","notVisible","alreadyGone","deleted"],w),g.planned-=Math.min(w,g.planned),Qs(g,h)}}for(let[o,{reason:d}]of[...t.heldInPlace,...e?.tally.heldInPlace??[]]){let c=s.get(o);c&&me(c.reasons,d)}return{deleted:[...n.values()],restored:[...s.values()],undeleted:[...r.values()],recreated:[...a.values()]}}function xi(i){let e=new Map;return{bodies:e,reader:{lane:()=>i.lane(),tooling:t=>i.tooling(t),calls:()=>i.calls(),describe:async(t,n)=>{let s=await i.describe(t,n);return"body"in s&&e.set(t,s.body),s}}}}function Gi(i){let e=i.objects,t=e.filter(n=>n.deleted+n.withParentDeleted+n.nextPassDeleted>0).map(n=>n.objectApiName);return{bringBack:e.filter(n=>n.broughtBack+n.backWithParent+(n.carriers??0)>0).map(n=>n.objectApiName),recreate:e.filter(n=>n.recreated>0).map(n=>n.objectApiName),giveBack:e.filter(n=>n.givenBackFirst+n.givenBackAfter+n.givenBackNextPass+On(n)>0).map(n=>n.objectApiName),setToDraft:e.filter(n=>In(n)>0).map(n=>n.objectApiName),delete:t}}function Ji(i){let e=Gi(i),{unlink:t,relink:n,share:s,unlinkFrom:r}=i.links,a=(o,d)=>d?[...o??[],ne]:[...o??[]];return{...e,delete:a(e.delete,t.count+r.count>0),recreate:a(e.recreate,n.count>0),giveBack:a(e.giveBack,s.count>0)}}function er(i){let{unlink:e,relink:t,share:n,unlinkFrom:s}=i.links;return e.count+t.count+n.count+s.count}function xt(i){return i.deletes.spool.count+i.bringBack.count+i.recreate.count+i.giveBack.beforeDeletes.count+i.giveBack.afterDeletes.count+er(i)>0}function Ki(i,e){let t=0,n=r=>(t++,r()),s=i.bulkDestroy?.bind(i);return{org:{get version(){return i.version},request:r=>n(()=>i.request(r)),query:(r,a)=>n(()=>i.query(r,a)),queryMore:r=>n(()=>i.queryMore(r)),describeGlobal:()=>n(()=>i.describeGlobal()),serverTime:()=>n(()=>i.serverTime()),userId:()=>n(()=>i.userId()),describe:r=>n(()=>i.describe(r)),update:(r,a)=>n(()=>i.update(r,a)),create:(r,a)=>n(()=>i.create(r,a)),destroy:(r,a)=>n(()=>i.destroy(r,a)),queryDeleted:r=>n(()=>i.queryDeleted(r)),...s?{bulkDestroy:async(r,a,o)=>{let d=1;try{let c=await s(r,a,o);return d=c.requests??1,c}finally{t+=d}}}:{}},undelete:r=>n(()=>e(r)),used:()=>t,add:r=>{t+=r}}}async function ka(i,e){let{checkpoint:t,orgName:n}=e;if(e.reusesPreview&&e.reusesPreview.previewId!==e.previewId)throw new Error("A rewind acts on the preview it names: the one given is another.");let s=Ki(i.org,i.undelete),r,a=await Vn(Li(s.org),{act:"rewind",orgName:n,registered:e.registered,username:e.username,organizationId:t.org.organizationId,customSettings:dn(t)},{userId:async()=>r=await s.org.userId()});if(!a.allowed)return{rewound:!1,refusal:a.refusal};let o=i.store.lock(t.org.organizationId,"rewind",t.checkpointId);if("busy"in o)return{rewound:!1,refusal:Bi(n,o.busy)};let d=new Kt(i,e,s,o.lock,a.queryAllFiles,{grants:a.grants,...r!==void 0?{userId:r}:{}});try{let c=await i.runWriting?.(a.org.id);return c!==void 0?Ni("RUN_WRITING",c):await d.go()}finally{await d.cleanUp(),o.lock.release()}}var Kt=class{constructor(e,t,n,s,r,a){this.deps=e;this.request=t;this.count=n;this.lock=s;this.queryAllFiles=r;this.user=a;this.org=this.clock.watched(n.org),this.signal=e.signal,this.now=e.now??(()=>new Date),this.kept=xi(Ot(this.org,this.signal)),this.picked=t.objects!==void 0?new Set(t.objects):void 0}deps;request;count;lock;queryAllFiles;user;org;signal;now;notes=[];ownDirs=[];ended=!1;kept;global;cascadesOfObject=new Map;lifecycles=new Map;unqueried;noBin=new Set;splitting=Rt();stamps={};stampOf=new Map;spans=[];userId="";owners=new Set;carried=new E;comesBack=new E;before=Number.NaN;clock=new ls(()=>this.now().getTime());access=es;picked;leftFields=new Map;asked;emailsCounted;stopped(){return this.signal?.aborted===!0}progress(e,t,n,s){this.deps.onProgress?.({phase:e,pass:t,percentage:n,step:s})}describeGlobal(){return this.global??=this.org.describeGlobal()}async diff(e){let t=$e("pv",this.now()),n=Ue(this.request.folder,t);return this.ownDirs.push(n),{diff:await ss({checkpoint:this.request.checkpoint,folder:this.request.folder,reader:this.kept.reader,describeGlobal:()=>this.describeGlobal(),previewId:t,readAt:e,queryAllFiles:this.queryAllFiles,access:this.access,...this.signal?{signal:this.signal}:{}}),dir:n}}async plan(e,t,n,s){let r=await is({checkpoint:this.request.checkpoint,pass:e,confirmedDir:t,freshDir:n.dir,readAt:s,ownWriters:rt(this.request.checkpoint.takenBy,this.userId),acceptOutside:this.request.acceptOutside,acceptNoUndo:this.request.acceptNoUndo,acceptRecreate:this.request.acceptRecreate,...e===2&&Object.keys(this.stamps).length>0?{removalStamps:{...this.stamps}}:{},...e===2&&this.spans.length>0?{removalSpans:[...this.spans]}:{},...e===2?{recreated:await Ne.read(this.request.folder)}:{},...this.picked!==void 0?{objects:this.picked,heldRows:as(this.request.checkpoint,this.request.folder)}:{},dir:zs(n.dir,`plan${e}-${Us(4).toString("hex")}`),...this.signal?{signal:this.signal}:{}}),a=new Map;for(let{objectApiName:o}of this.request.checkpoint.objects){let d=new E;for(let c of Hs){let p=c==="inBin"||c==="withParent";for await(let f of se(ye(r.dir,o,c)))typeof f.Id=="string"&&(d.add(f.Id),p&&this.comesBack.add(f.Id))}d.size>0&&a.set(o,d)}return{plan:r,acted:a}}async relationships(){let e=this.global,t=e?new Set((await ln({describeGlobal:()=>e})).keys()):void 0,n=new Set(this.request.checkpoint.objects.map(({objectApiName:r})=>r.toLowerCase()));if(this.request.checkpoint.files!==void 0)for(let r of[ne,an])n.add(r.toLowerCase());let s=new Map;for(let[r,a]of this.kept.bodies)s.set(r,Dn(a,{inCheckpoint:n,...t?{worked:t}:{}}));return s}async go(){let{checkpoint:e,orgName:t,folder:n}=this.request,s=await Un(this.org,t);if(this.stopped())throw new qe;this.progress("reading",1,5,`Reading ${t} again`);let r=this.request.reusesPreview,a,o,d;try{this.access=await ts({grants:this.user.grants,...this.user.userId!==void 0?{userId:this.user.userId}:{},username:this.request.username,checkpoint:e,reader:this.kept.reader});let U=r?Mi(r,this.access):[];if(U.length>0)return{rewound:!1,refusal:Ui(t,U)};if(a=r?r.readAt:await this.org.serverTime(),this.before=Date.parse(a)-li,!Number.isFinite(this.before))throw new Error(`Not a date: ${a}`);o=r?{diff:r,dir:Ue(n,this.request.previewId)}:await this.diff(a),d=await this.plan(1,Ue(n,this.request.previewId),o,a)}catch(U){throw U instanceof Me||this.stopped()?new qe:U}let c=[],p=d.plan.left.filter(U=>Vs.has(U.reason));p.length>0&&c.push(Fi(p));let f=d.plan.left.filter(U=>U.reason==="recreateNotAccepted");f.length>0&&c.push(Ti(f));let u=Di(o.diff,d.plan);u.length>0&&!this.request.acceptUnseen&&c.push(Ei(this.request.username,u));let l=zn("rewind",await this.bringBackFiles(d.plan,o.dir),s.fileStorage?.remaining,t);l&&c.push(l);let h=e.lastRewind,g=h!==void 0&&h.endedAt===void 0&&h.undoneAt===void 0,w=xt(d.plan);if(!w){let[U,...b]=c;if(U)return Gs(U,b);if(!g)return this.wroteNothing(o,d,s.remaining)}let y=Ji(d.plan),m;if(w&&this.deps.readAutomation){let U=[...new Set([...y.bringBack??[],...y.recreate??[],...y.giveBack??[],...y.setToDraft??[],...y.delete??[]])];try{m=await this.deps.readAutomation(U)}catch(b){m=Wi(U,Q(b))}this.count.add(m.requests)}let k=m,L=w?await Oi(this.deps.mute,m,y):{},S="refusal"in L?L:void 0,T="refusal"in L?void 0:L.mute;S&&c.push(S.refusal),L.automation&&(m=L.automation);let F=S?S.plan:T?.plan,P=this.request.acceptEmails===!0,j=w&&k?await Nn({act:"rewind",orgName:t,automation:k,steps:y,...F?{plan:F}:{},accepted:P,mayMute:this.deps.mute===void 0&&this.request.canMute===!0,read:()=>vn(this.org)}):void 0,z=Mn({objects:e.objects,diff:os(o.diff,this.picked),automationRequests:0,relationships:await this.relationships(),...r?{reusesPreview:!0}:{}}),q=Zn(j?.ofRun),x=$n("rewind",{run:this.count.used()-(q.deliverability??0)+z.apiRequests,...q},s,t);w&&x&&c.push(x),this.splitting=Rt(un(s.remaining,this.count.used()+z.apiRequests));let A=Pn(d.plan.objects),B=m?Ln("rewind",Xe(A,m,s.emails),t):void 0;w&&B&&c.push(B);let G=m?An(A,m):void 0;m&&!this.request.acceptAutomation&&(kt(m,y).length>0||sn(m.unread)||G!==void 0)&&c.push(zi(t,m,y,G)),w&&j?.refusal&&c.push(j.refusal);let[v,...N]=c;if(v)return Gs(v,N);if(m&&(this.asked={automation:m,steps:y,accepted:this.request.acceptAutomation},this.emailsCounted={written:[...A],limits:s.emails}),this.stopped())throw new qe;this.userId=await this.org.userId(),this.owners=new Set(rt(e.takenBy,this.userId).map(O));let M=await Fs({folder:n,lock:this.lock,startedAt:a,userId:this.userId,...e.takenBy.automatedProcessUserId!==void 0?{automatedProcessUserId:e.takenBy.automatedProcessUserId}:{},now:this.now}),K;try{let U=await Pi(T,`rewind ${e.checkpointId} ${a}`,R=>{let C=R&&F&&k&&j?Bn({act:"rewind",orgName:t,automation:k,steps:y,plan:F,held:R.outcome,planned:j.ofRun.senders,...j.ofRun.read?{reading:j.ofRun.read.reading}:{},accepted:P}):void 0;return C?Promise.resolve({rewound:!1,refusal:C}):this.passes(M,a,o,d,s.remaining)},R=>{K=R}).catch(R=>{if(St(R))return{rewound:!1,refusal:{code:"MUTE",message:`${R.message} ${Ie}`}};throw R}),b=j?.gate.audit;return U.rewound?{...U,...K?{result:{...U.result,mutedAutomation:K}}:{},...b!==void 0?{deliverability:b}:{}}:U}finally{await M.close()}}async wroteNothing(e,t,n){let s=await this.residualOf(e,e,[t],new xe),r=this.pickedOnly(e.diff.unread),a=await this.scopeOf(e,e);return this.ended=!0,{rewound:!0,result:this.resultOf({rewindId:$e("rw",this.now()),status:s.length>0||r.length>0?"partial":"success",tally:{deleted:[],restored:[],undeleted:[],recreated:[]},residual:s,unread:r,passes:1,leftToday:n,...a?{scope:a}:{}}),notes:this.notes}}async passes(e,t,n,s,r){let{checkpoint:a}=this.request,o=await e.read();this.addStamps(o.rewind.removalStamps??{}),this.spans.push(...o.rewind.removalSpans??[]);for(let{ids:v}of o.did.carried??[])for(let N of v)this.carried.add(N);let d=new Date(Date.parse(o.head.startedAt)+ui).toISOString(),c;await this.deps.store.update(a.checkpointId,v=>(v.lastRewind?.rewindId!==e.rewindId&&(c=v.lastRewind),{...v,lastRewind:{rewindId:e.rewindId,undoUntil:d}}));let p=xt(s.plan),f=p?await this.pass(e,s.plan,n.diff,1):new xe,u=[s],l,h,g=f.cancelled;try{if(!g&&f.wrote){this.progress("reading",2,70,`Reading ${this.request.orgName} again`);let v=await this.diff(await this.org.serverTime()),N=await this.plan(2,s.plan.dir,v,t);if(u.push(N),h=v,xt(N.plan)){let M=await this.pass(e,N.plan,v.diff,2);l={tally:M,plan:N.plan},g=M.cancelled,!g&&M.wrote&&(this.progress("checking",2,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime()))}}else!g&&p?(this.progress("checking",1,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime())):g||(h=n)}catch(v){if(!(v instanceof Me)&&!this.stopped())throw v;g=!0}this.stopped()&&(g=!0);let w=await qi({tally:f,plan:s.plan},l),y=!g&&h?await this.residualOf(h,n,u,f,l?.tally):[],m=!g&&h?this.pickedOnly(h.diff.unread):[],k=await this.scopeOf(g?void 0:h,n),L=w.deleted.some(v=>v.deleted>0)||w.restored.some(v=>v.restored+(v.restoredWithout??0)>0)||w.undeleted.some(v=>v.undeleted>0)||w.recreated.some(v=>v.created>0)||f.cameBackRestored+(l?.tally.cameBackRestored??0)>0,S=g?"cancelled":y.some(v=>v.reason==="changedDuringRewind")?"unstable":y.length>0||m.length>0?L?"partial":"failure":"success",T=this.filesOf(y,[f,...l?[l.tally]:[]]),F=(T?.unlinked??0)+(T?.relinked??0)+(T?.linksUpdated??0),P=L||F>0||(g||e.resumed)&&(await e.facts()).lastWriteAt!==void 0,j=[];if(g&&!P)try{await this.deps.store.update(a.checkpointId,v=>(delete v.lastRewind,c?{...v,lastRewind:c}:v))}catch(v){this.notes.push(`The checkpoint could not be told the rewind stopped before it wrote anything (${Q(v)}): its list may not offer to undo the rewind before it.`)}if(!g){await e.end(),this.ended=!0;let v=h?.diff.readAt??this.now().toISOString(),N=P?{rewindId:e.rewindId,endedAt:v,undoUntil:d}:c;try{await this.deps.store.update(a.checkpointId,M=>(delete M.lastRewind,N?{...M,lastRewind:N}:M))}catch(M){this.notes.push(P?`The checkpoint could not be told when the rewind ended (${Q(M)}): its list may not offer to undo it.`:`The checkpoint could not be told the rewind wrote nothing (${Q(M)}): its list may not offer to undo the rewind before it.`)}try{P&&(j=await Es(this.deps.store,this.lock,{checkpointId:a.checkpointId,rewindId:e.rewindId}))}catch(M){this.notes.push(`The journals of the earlier rewinds of ${this.request.orgName} could not be deleted (${Q(M)}): they stay until their checkpoint goes.`)}}let z=await e.read(),q=this.undoCannotOf(z),x=(z.did.carriers??[]).map(({objectApiName:v,ids:N})=>({objectApiName:v,count:N.length}));if(g){let v=new Set(z.did.deleted.flatMap(({ids:M})=>M.map(O))),N=(z.did.carriers??[]).map(({objectApiName:M,ids:K})=>({objectApiName:M,count:K.filter(U=>!v.has(O(U))).length})).filter(({count:M})=>M>0);N.length>0&&this.notes.push(`Stopped with ${N.map(({objectApiName:M,count:K})=>`${K} ${M}`).join(", ")} record(s) brought back for a moment still in the org: they had taken records of the checkpoint along. Rewind again to delete them, with what came back with them.`)}let A=new Map;for(let v of[f,...l?[l.tally]:[]])for(let[N,M]of v.draftsLeft)A.set(N,[...A.get(N)??[],...M]);let B=[...A].map(([v,N])=>({objectApiName:v,count:N.length,ids:N.slice(0,Ws)})),G={rewound:!0,result:this.resultOf({rewindId:e.rewindId,status:S,tally:w,residual:y,unread:m,passes:l?2:1,leftToday:r,...P?{undo:{until:d,cannot:q}}:{},removedJournals:j,carriers:x,draftsLeft:B,...T?{files:T}:{},...k?{scope:k}:{}}),notes:this.notes};if(L||z.lastWriteAt!==void 0&&(g||e.resumed)){let v=await us({folder:this.request.folder,lock:this.lock,checkpoint:a,result:G.result,startedAt:t,...!g&&h?{endedAt:h.diff.readAt}:{},clock:this.clock});v!==void 0&&this.notes.push(v)}if(!P){await e.close();try{await $s(je(this.request.folder,e.rewindId),{recursive:!0,force:!0})}catch(v){this.notes.push(`The journal of this rewind, which wrote nothing, could not be deleted (${Q(v)}): it stays until a later rewind that writes ends, or its checkpoint goes.`)}}return G}filesOf(e,t){if(this.request.checkpoint.files===void 0)return;let n=r=>t.reduce((a,o)=>a+o.links[r].done,0),s={unlinked:n("unlink"),relinked:n("relink"),linksUpdated:n("share"),linksRefused:e.filter(r=>r.objectApiName===ne&&r.reason==="refused").reduce((r,a)=>r+a.count,0)};return s.unlinked+s.relinked+s.linksUpdated+s.linksRefused>0?s:void 0}async bringBackFiles(e,t){let n=new E;for await(let r of e.bringBack.pages(Ae))for(let a of r)n.add(a);if(n.size===0)return{files:0,bytes:0};let s=new Map;for await(let r of se(st(t,Ae)))typeof r.Id=="string"&&typeof r.ContentSize=="number"&&n.has(r.Id)&&s.set(O(r.Id),r.ContentSize);if(s.size<n.size&&this.request.checkpoint.files!==void 0)for await(let r of Hn(this.request.folder))n.has(r.Id)&&!s.has(O(r.Id))&&r.ContentSize!==null&&s.set(O(r.Id),r.ContentSize);return{files:n.size,bytes:[...s.values()].reduce((r,a)=>r+a,0)}}undoCannotOf(e){let t=new Set(this.request.checkpoint.objects.filter(a=>!a.undeletable).map(a=>a.objectApiName)),n=new Set(e.did.broughtBack.flatMap(({ids:a})=>a.map(O))),s=new Set((e.did.deletedBeforeParent??[]).flatMap(({ids:a})=>a.map(O))),r=[];for(let{objectApiName:a,ids:o}of e.did.deleted){let d=o.map(O).filter(f=>!n.has(f)),c=d.filter(f=>s.has(f)).length,p=t.has(a)?d.length-c:0;p>0&&r.push({objectApiName:a,count:p}),c>0&&r.push({objectApiName:a,count:c,reason:"deletedBeforeParent"})}return r}resultOf(e){let t=this.count.used();return{checkpointId:this.request.checkpoint.checkpointId,rewindId:e.rewindId,status:e.status,deleted:e.tally.deleted,restored:e.tally.restored.filter(n=>n.planned>0),undeleted:e.tally.undeleted.filter(n=>n.planned>0),...e.tally.recreated.length>0?{recreated:e.tally.recreated}:{},...(e.carriers??[]).length>0?{carriers:e.carriers}:{},...(e.draftsLeft??[]).length>0?{draftsLeft:e.draftsLeft}:{},residual:e.residual,...e.unread.length>0?{unread:[...e.unread]}:{},passes:e.passes,...e.undo?{undo:e.undo}:{},...(e.removedJournals??[]).length>0?{removedJournals:e.removedJournals}:{},...e.files?{files:e.files}:{},apiRequests:{used:t,leftToday:Math.max(0,e.leftToday-t)},finishedAt:this.now().toISOString(),...e.scope?{scope:e.scope}:{}}}pickedOnly(e){let t=this.picked;return t===void 0?[...e]:e.filter(n=>t.has(n.objectApiName))}async scopeOf(e,t){let n=this.picked;if(n===void 0)return;let{checkpoint:s}=this.request,r=s.objects.map(({objectApiName:d})=>d).filter(d=>n.has(d)),a=[],o=0;if(e!==void 0){let d=[...s.objects].sort((c,p)=>c.readOrder-p.readOrder);for(let{objectApiName:c}of d){if(n.has(c))continue;let p=new E;for await(let u of se(ye(t.dir,c,"goneForGood")))typeof u.Id=="string"&&p.add(u.Id);let f=new E;for(let u of _s)for await(let l of se(ye(e.dir,c,u)))typeof l.Id!="string"||p.has(l.Id)||f.add(l.Id);f.size>0&&(a.push(c),o+=f.size)}if(s.files!==void 0&&!n.has(Ae)){let c=new E;for(let p of["linkAdded","linkRemoved","linkChanged"])for await(let f of se(Lt(e.dir,p)))typeof f.Id=="string"&&c.add(f.Id);c.size>0&&(a.push(ne),o+=c.size)}}return{objects:r,notRewound:{objects:a,records:o}}}async readLeftFields(e){let t=e.limited?.leftFields;if(!(t===void 0||t.count===0))for await(let n of se(t.file)){if(typeof n.Id!="string"||!Array.isArray(n.fields))continue;let s=this.leftFields.get(O(n.Id))??new Set;for(let r of n.fields)typeof r=="string"&&s.add(r.toLowerCase());this.leftFields.set(O(n.Id),s)}}async cleanUp(){let e=[...this.ownDirs];this.ended&&e.push(Ue(this.request.folder,this.request.previewId));for(let t of e)await $s(t,{recursive:!0,force:!0}).catch(()=>{})}async pass(e,t,n,s){let r=new xe;await this.readLeftFields(t);let a={},o=l=>{Object.assign(a,l),this.addStamps(l)},d=this.allowLists(n),c=new E;for(let{objectApiName:l}of t.giveBack.afterDeletes.objects){let h=t.giveBack.heldBy.find(g=>g.objectApiName===l)?.by;for await(let g of t.giveBack.afterDeletes.pages(l)){for(let w of g)c.add(w);h&&await e.heldInPlace(l,h,g)}}await this.keepFirst(e,t.giveBack.afterDeletes,d);let p=this.request.acceptRecreate?new Be(zs(t.dir,`remake-${Us(4).toString("hex")}`)):void 0,f=async()=>{t.bringBack.count>0&&(this.progress("bringingBack",s,s===1?25:80,"Bringing back what was deleted since"),await this.bringBack(e,t.bringBack,t.carriers,r,o,p));let l=p&&p.objects.length>0?await this.withPlanned(p,t.recreate):t.recreate;if(!r.cancelled&&!this.stopped()&&l.count>0)this.progress("recreating",s,s===1?32:81,"Making again what the recycle bin no longer holds"),await this.recreate(e,l,r);else if(l.count>0){for(let{objectApiName:h,count:g}of l.objects)r.recreate({...Re(h),planned:g,notReached:g});r.cancelled=!0}return!r.cancelled&&!this.stopped()&&t.giveBack.beforeDeletes.count>0&&(this.progress("givingBack",s,s===1?40:82,"Giving back what was changed since"),await this.giveBack(e,t,t.giveBack.beforeDeletes,"before",d,c,r,o)),r.wrote},u;if(t.deletes.spool.count>0){this.progress("deleting",s,s===1?55:85,"Deleting what was created since");for(let{objectApiName:w,file:y}of t.beforeParent){let m=[];for await(let k of se(y)){let L=Array.isArray(k.parents)?k.parents:[];for(let S of L)typeof k.Id=="string"&&typeof S=="string"&&m.push({id:k.Id,parent:S});m.length>=J&&await e.beforeParent(w,m.splice(0))}m.length>0&&await e.beforeParent(w,m)}await e.deleting(t.deletes);let l={...this.stamps,...t.removal.removalStamps},h=[...this.spans,...t.removal.removalSpans??[]].filter((w,y,m)=>m.findIndex(k=>JSON.stringify(k)===JSON.stringify(w))===y),g=(w,y)=>{if(typeof w.Id!="string"||!this.carried.has(w.Id)&&!t.goesAlong.has(w.Id))return!1;let m=pt(w.LastModifiedDate??w.SystemModstamp);return m<=y||m<=(this.stampOf.get(O(w.Id))??Number.NaN)};u=await Ve(this.org,t.deletes,{splitting:this.splitting,runStartedAt:t.removal.runStartedAt,runEndedAt:t.removal.runEndedAt,includeChanged:t.removal.includeChanged,alongAccepted:!0,...Object.keys(l).length>0?{removalStamps:l}:{},...h.length>0?{removalSpans:h}:{},...this.carried.size+t.carriers.size+t.goesAlong.size>0?{goesWithParent:g}:{},...t.alongToDraft.spool.count>0?{alongToDraft:t.alongToDraft}:{},...t.bringBack.count+t.recreate.count+t.giveBack.beforeDeletes.count>0?{sweep:f}:{},...this.deps.onUndeletable?{onUndeletable:this.deps.onUndeletable}:{},...this.signal?{signal:this.signal}:{},onProgress:(w,y,m)=>this.progress("deleting",s,s===1?55:85,`Deleting ${m}: ${w} / ${y}`)}),await e.deleted(u),r.delete(u.objects);for await(let{objectApiName:w,ids:y}of u.left())r.leftBy("removal",w,y);u.cancelled&&(r.cancelled=!0),(u.objects.some(w=>w.deleted>0)||u.span)&&(r.wrote=!0),o(u.stamps),u.span&&this.spans.push(u.span)}else this.stopped()?r.cancelled=!0:await f();return!r.cancelled&&!this.stopped()&&t.giveBack.afterDeletes.count>0&&(this.progress("givingBack",s,s===1?65:88,"Giving back what the deleted records held in place"),await this.giveBack(e,t,t.giveBack.afterDeletes,"after",d,c,r,o)),!r.cancelled&&!this.stopped()&&er(t)>0&&(this.progress("givingBack",s,s===1?68:89,"Putting back the links between files and records"),await this.writeLinks(e,t,r)),this.stopped()&&(r.cancelled=!0),await e.removal({removalStamps:a,removalSpans:u?.span?[u.span]:[]}),r}async writeLinks(e,t,n){let s=()=>this.stopped(),r=async d=>{d!==0&&(n.wrote=!0,await e.wrote())},a=await xs(t.links.unlink.file,"linkAdded"),o=new Set(a.map(d=>O(d.Id)));for(let d of await this.heldLinksOf(t.links.unlinkFrom,t))o.has(O(d.Id))||a.push(d);if(n.links.unlink=await at(this.org,a,{before:d=>e.unlinking(d),after:async({done:d,left:c})=>{c.length>0&&await e.unlinkLeft(c),await r(d.length)},stopped:s}),n.links.unlink.cancelled&&(n.cancelled=!0),!n.cancelled&&t.links.relink.count>0){let d=await Ne.read(this.request.folder);n.links.relink=await dt(this.org,await xs(t.links.relink.file,"linkRemoved"),{after:async({made:c})=>{c.length>0&&await e.relinked(c),await r(c.length)},stopped:s},c=>d.currentOf(O(c))??c),n.links.relink.cancelled&&(n.cancelled=!0)}if(!n.cancelled&&t.links.share.count>0){let d=await Ai(t.links.share.file),c=new Map(d.map(p=>[O(p.Id),p.now]));n.links.share=await ct(this.org,d,{before:p=>e.linksUpdating(p.map(f=>({...f,...c.get(O(f.Id))??{}}))),after:async({done:p,left:f})=>{f.length>0&&await e.linksUpdateLeft(f),await r(p.length)},stopped:s}),n.links.share.cancelled&&(n.cancelled=!0)}}async heldLinksOf(e,t){if(e.count===0)return[];let n=ji.safeParse(await this.describeGlobal()),s=Jn(n.success?n.data.sobjects:[],this.request.checkpoint.objects.map(({objectApiName:a})=>a)),r=[];for await(let a of e.pages(Ae,jt))for(let o of ge(a,jt)){let d=await this.org.query(`SELECT ${Gn.join(", ")} FROM ${ne} WHERE ContentDocumentId IN (${o})`);for(;;){for(let c of d.records){let p=we.safeParse(c);!p.success||Kn(p.data,s)===void 0||t.deletes.has(O(p.data.LinkedEntityId))||r.push(p.data)}if(d.done||!d.nextRecordsUrl)break;d=await this.org.queryMore(d.nextRecordsUrl)}}return r}allowLists(e){let t=new Map(e.objects.map(s=>[s.objectApiName,new Set(s.notCompared.map(r=>r.toLowerCase()))])),n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s]));return s=>{let r=n.get(s),a=t.get(s);return At(s,r?.fields??[],this.request.checkpoint.ignoredFields).filter(o=>!a?.has(o.toLowerCase()))}}async keepFirst(e,t,n){for(let{objectApiName:s}of t.objects){let r=n(s);if(r.length===0)continue;let a=de(s),d=this.request.checkpoint.objects.find(f=>f.objectApiName===s)?.fields.some(f=>f===Ce)===!0,c=["Id",...r.map(de),...d?[Ce]:[]],p=async f=>(await this.org.query(f)).records;try{for await(let f of t.pages(s))for(let u of ge(f,Y)){if(this.stopped())return;let h=(await He(`SELECT ${c.join(", ")} FROM ${a} WHERE Id IN (${u})`,p)).map(g=>tt(s,g,r));h.length>0&&await e.keep(s,h)}}catch(f){if(f instanceof Me)return;this.notes.push(`What the ${s} records given back after the deletions held could not be kept before the rewind wrote (${Q(f)}): Undo gives them back what they held once the deletions were through.`)}}}async cascadesOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let o=await this.kept.reader.describe(e);t="body"in o?o.body:void 0}let n=Pt.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=e===mi&&n.data.fields.some(o=>o.name===Ce),r=(n.data.childRelationships??[]).filter(o=>o.cascadeDelete===!0);if(r.length===0)return[];let a=await this.unqueriedObjects();return r.filter(o=>!a.has(o.childSObject)).map(o=>({child:o.childSObject,field:o.field,...s&&o.childSObject===yi&&o.field==="AccountId"?{persons:!0}:{}}))}unqueriedObjects(){return this.unqueried??=this.describeGlobal().then(e=>{let t=Ri.safeParse(e);return t.success?new Set(t.data.sobjects.filter(n=>n.queryable===!1).map(n=>n.name)):new Set},()=>(this.global=void 0,new Set)),this.unqueried}async insertFieldsOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let d=await this.kept.reader.describe(e);t="body"in d?d.body:void 0}let n=Pt.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=new Map(n.data.fields.map(d=>[d.name.toLowerCase(),d])),r=this.request.checkpoint.objects.find(d=>d.objectApiName===e),a=At(e,r?.fields??[],this.request.checkpoint.ignoredFields).filter(d=>s.get(d.toLowerCase())?.createable===!0),o=a.filter(d=>s.get(d.toLowerCase())?.type==="reference");return{fields:a.map(de),lookups:o}}async withPlanned(e,t){for(let{objectApiName:s}of t.objects)for await(let r of t.pages(s))for(let a of r)await e.add(s,a);let n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s.readOrder]));return e.finish(s=>[...s].sort((r,a)=>(n.get(a.objectApiName)??0)-(n.get(r.objectApiName)??0)))}async recreate(e,t,n){let{checkpoint:s,folder:r}=this.request,a=new E;for(let{objectApiName:u}of t.objects)for await(let l of t.pages(u))for(let h of l)a.add(h);let o=await Ne.read(r),d=new Set,c=u=>o.originalOf(u.slice(0,15))??u.slice(0,15),p=[],f=new Map;for(let{objectApiName:u,count:l}of t.objects){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:l,notReached:l}),n.cancelled=!0;continue}let h;try{h=await this.insertFieldsOf(u)}catch(y){if(y instanceof Me){n.cancelled=!0,n.recreate({...Re(u),planned:l,notReached:l});continue}let m=Q(y);n.recreate({...Re(u),planned:l,refused:l,reasons:[m]});for await(let k of t.pages(u))n.leftBy("recreate",u,k);continue}let g=h.fields.find(y=>y.toLowerCase()==="status"),w=g!==void 0?await this.lifecycleOf(u):void 0;for await(let y of t.pages(u,Se)){if(n.cancelled||this.stopped()){n.recreate({...Re(u),planned:y.length,notReached:y.length}),n.cancelled=!0;continue}let m=await et.read(r,s.snapshotId,u,o),k=[],L=await m.chunk(y).batches(s.snapshotId,u,Y);for await(let P of L??[])k.push(...P);let S={...Re(u),planned:y.length},T=new E;for(let P of k)typeof P.Id=="string"&&T.add(P.Id);let F=y.filter(P=>!T.has(P));F.length>0&&(S.refused+=F.length,me(S.reasons,"The checkpoint holds no values of it."),n.leftBy("recreate",u,F));for(let P=0;P<k.length;P+=Y){if(this.stopped()){let G=k.length-P;S.notReached=(S.notReached??0)+G,n.leftBy("recreate",u,k.slice(P).map(v=>String(v.Id))),n.cancelled=!0;break}let j=k.slice(P,P+Y),z=j.map(G=>m.snapshotIdOf(String(G.Id))),q=new Map,x=j.map((G,v)=>{let N=tt(u,G,h.fields);delete N.Id;let M=g!==void 0&&w?on(N[g],w):void 0;g!==void 0&&M!==void 0&&(q.set(v,String(N[g])),N[g]=M),tr(N,this.leftFields.get(O(z[v])));for(let K of h.lookups){let U=N[K];if(typeof U!="string"||U.length<15||!a.has(U))continue;let b=c(U),R=d.has(b)?o.currentOf(b):void 0;if(R!==void 0){N[K]=R;continue}p.push({objectApiName:u,from:z[v].slice(0,15),field:K,target:b}),N[K]=null}return N});await e.recreating(u,z);let A=Gt(await this.org.create(u,x)),B=[];if(j.forEach((G,v)=>{let N=A[v];if(N?.success===!0&&typeof N.id=="string"){B.push({objectApiName:u,from:z[v],to:N.id});let M=q.get(v);if(g!==void 0&&M!==void 0){let K=f.get(u)??[];K.push({id:N.id,field:g,status:M}),f.set(u,K)}return}S.refused++,me(S.reasons,N?.error??"The org gave no answer for it."),n.leftBy("recreate",u,[String(G.Id)])}),B.length>0){await Ne.add(r,B),await e.recreated(u,B.map(G=>({from:G.from,id:G.to}))),await e.wrote(),n.wrote=!0,S.created+=B.length;for(let G of B)d.add(G.from.slice(0,15));o=await Ne.read(r)}}n.recreate(S)}}await this.fillOwed(p,o,d,n),await this.giveStatusesBack(f,n)}lifecycleOf(e){let t=Ke[e];if(t===void 0)return Promise.resolve(void 0);let n=this.lifecycles.get(e);return n||(n=rn(async s=>(await this.org.query(s)).records,t),this.lifecycles.set(e,n)),n}async giveStatusesBack(e,t){let n=[...e];for(let[s,[r,a]]of n.entries())for(let o=0;o<a.length;o+=Y){if(this.stopped()){let f=[[r,a.slice(o)],...n.slice(s+1)];for(let[u,l]of f)l.length!==0&&t.draftsLeft.set(u,[...t.draftsLeft.get(u)??[],...l.map(({id:h})=>h)]);return}let d=a.slice(o,o+Y),c=Gt(await this.org.update(r,d.map(({id:f,field:u,status:l})=>({Id:f,[u]:l})))),p=t.recreated.get(r);d.forEach(({id:f},u)=>{let l=c[u];l?.success!==!0&&(p&&me(p.reasons,`Made again as a draft, but its status was refused: ${l?.error??"the org gave no answer for it."}`),t.leftBy("recreate",r,[f]))})}}async fillOwed(e,t,n,s){let r=new Map;for(let{objectApiName:a,from:o,field:d,target:c}of e){if(!n.has(o)||!n.has(c))continue;let p=t.currentOf(o),f=t.currentOf(c);if(p===void 0||f===void 0)continue;let u=r.get(a)??new Map;u.set(p,{...u.get(p),Id:p,[d]:f}),r.set(a,u)}for(let[a,o]of r){let d=[...o.values()];for(let c=0;c<d.length;c+=Y){if(this.stopped())return;let p=d.slice(c,c+Y),f=Gt(await this.org.update(a,p)),u=s.recreated.get(a);f.forEach((l,h)=>{l.success||(u&&me(u.reasons,`Made again, but a lookup to a record made after it was refused: ${l.error}`),s.leftBy("recreate",a,[String(p[h].Id)]))})}}}async bringBack(e,t,n,s,r,a){let o=Ot(this.org),d=this.makesAgain();for(let{objectApiName:c,count:p}of t.objects){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:p,notReached:p}),s.cancelled=!0;continue}let f;try{f=await this.cascadesOf(c)}catch(l){f=[],this.notes.push(`The records that come back with ${c} could not be told (${Q(l)}): Undo may not send those ${c} records back to the recycle bin.`)}let u=async function*(){for await(let l of t.pages(c,Se)){let h=l.filter(w=>n.has(w));h.length>0&&(yield{ids:h,asCarriers:!0});let g=h.length>0?l.filter(w=>!n.has(w)):l;g.length>0&&(yield{ids:g,asCarriers:!1})}};for await(let{ids:l,asCarriers:h}of u()){if(s.cancelled||this.stopped()){s.undelete({...mt(c),planned:l.length,notReached:l.length}),s.cancelled=!0;continue}let g=e.bringingBack([{objectApiName:c,ids:l}],this.count.undelete,{carriers:h}),w=new Map,y=new Map,m=async S=>{let{byParent:T,under:F}=await this.nameChildren(e,o,f,c,S,h),P=await g(S);r(await this.undeleteStamps(c,S,T));for(let j of Si(P,S))w.set(O(j),F.get(O(j))??[]);for(let j of Ii(P,S))y.set(O(j),{id:j,under:F.get(O(j))??[]});return P},k=await zt(this.org,await Ze({org:this.org,plan:[{objectApiName:c,ids:l}],undelete:m,...this.signal?{signal:this.signal}:{}}),[{objectApiName:c,ids:l}],this.notes);await this.notBroughtBack(e,c,y,k.left);let L=await this.settleGone(c,k,w,s,a,d);for(let S of L.objects)s.undelete(S);s.leftBy("undelete",c,L.left),L.wrote&&(s.wrote=!0,await e.wrote()),L.cancelled&&(s.cancelled=!0)}}}makesAgain(){let e=new Map,{checkpoint:t,folder:n}=this.request;return async(s,r)=>{let a=t.objects.find(d=>d.objectApiName===s);if(!a||!ns(a))return!1;let o=e.get(s);return o||(o=et.read(n,t.snapshotId,s).catch(()=>{}),e.set(s,o)),(await o)?.has(r)===!0}}remakeUnaskedWords(e){let t=this.asked;if(!t)return;let n=[...new Set(e)],s=cs(t.automation,t.steps,n,t.accepted);if(!(s.fired.length===0&&!s.blind))return wi(this.request.orgName,n,s)}remakeEmailsWords(e){let t=this.emailsCounted,n=this.asked;if(!t||!n)return;let s=e.flatMap(c=>[{objectApiName:c,write:"insert",records:1},...Ke[c]!==void 0?[{objectApiName:c,write:"update",records:1}]:[]]),r=Xe(t.written,n.automation,t.limits),o=Xe([...t.written,...s],n.automation,t.limits).filter(c=>c.verdict==="exceeds");if(o.length===0){t.written.push(...s);return}return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and making it again sends ${o.map(c=>{let p=c.emails-(r.find(f=>f.limit===c.limit)?.emails??0);return`${It(p,c.limit)} more than the ${It(c.emails-p,c.limit)} it counted, past the ${c.remaining??0} of ${c.max??0} ${this.request.orgName} has left today`}).join("; ")}. Rewind again: its preview counts it to make again, and its emails.`}async settleGone(e,t,n,s,r,a){let o=t.left.filter(h=>n.has(O(h)));if(o.length===0)return t;let d=new Set,c=0,p=0,f,u=h=>this.access.heldAs(h)==="parent";await this.keepNotInBin(e,o);for(let h of o){if(u(e)){p++,s.mark("outOfReach",e,h);for(let m of n.get(O(h))??[])s.mark("outOfReach",m.objectApiName,m.id);continue}if(!await a(e,h)){s.mark("lost",e,h);continue}let g=[];for(let m of n.get(O(h))??[])u(m.objectApiName)?s.mark("outOfReach",m.objectApiName,m.id):await a(m.objectApiName,m.id)&&g.push(m);let w=[e,...g.map(m=>m.objectApiName)],y=r?this.remakeUnaskedWords(w)??this.remakeEmailsWords(w):void 0;if(r&&y===void 0){await r.add(e,h);for(let m of g)await r.add(m.objectApiName,m.id);d.add(O(h));continue}if(y!==void 0){f=y,s.notAsked.set(O(h),y);for(let m of g)s.notAsked.set(O(m.id),y);continue}c++,s.mark("notInBin",e,h);for(let m of g)s.mark("notInBin",m.objectApiName,m.id)}let l=o.length-d.size;return{...t,objects:t.objects.map(h=>{if(h.objectApiName!==e)return h;let g=l===0?h.reasons.filter(w=>!_e.test(w)):c>0?h.reasons.map(w=>_e.test(w)?gi:w):f!==void 0?h.reasons.map(w=>_e.test(w)?f??w:w):p>0?h.reasons.map(w=>_e.test(w)?Jt:w):h.reasons;return{...h,planned:h.planned-d.size,refused:Math.max(0,h.refused-d.size),reasons:g}}),left:t.left.filter(h=>!d.has(O(h)))}}async notBroughtBack(e,t,n,s){if(n.size===0)return;let r=new Set(s.map(O)),a=new Map,o=(d,c)=>{let p=a.get(d)??[];p.push(c),a.set(d,p)};for(let[d,{id:c,under:p}]of n)if(r.has(d)){o(t,c);for(let f of p)o(f.objectApiName,f.id)}try{for(let[d,c]of a)await e.bringBackLeft(d,c)}catch(d){this.notes.push(`Which ${t} records ${this.request.orgName} refused to bring back could not be kept in the rewind\u2019s journal (${Q(d)}): its undo may count them among what it sends back to the recycle bin.`)}}async keepNotInBin(e,t){try{await Tn.add(this.request.folder,e,t)}catch(n){this.notes.push(`The ${e} records ${this.request.orgName} answered are no longer in the recycle bin could not be kept with the checkpoint (${Q(n)}): a later preview counts them to bring back again.`)}}async nameChildren(e,t,n,s,r,a=!1){let o=new Map,d=new Map,c=new Set(r.map(O)),p=new Map(r.map(h=>[O(h),O(h)])),f=new Map,u=new Map,l=[{objectApiName:s,cascades:n,ids:[...r]}];for(;l.length>0;){let h=new Map;for(let{objectApiName:g,cascades:w,ids:y}of l)for(let m of ge(y,Y)){let k=w.filter(({child:T})=>!this.noBin.has(T));if(k.length===0)break;let L=k.map(({child:T,field:F,persons:P})=>({objectApiName:T,soql:`SELECT Id, ${de(F)}${P?`, ${Ce}`:""}${qt(T)?", IsDeleted":""} FROM ${de(T)} WHERE ${F} IN (${m})${qt(T)?"":" AND IsDeleted = true"}`,scanAll:!0}));(await qn(t,L,(T,F)=>{let{child:P,field:j,persons:z}=k[T];for(let q of F){let x=q[j];if(typeof q.Id!="string"||typeof x!="string"||qt(P)&&q.IsDeleted!==!0)continue;let A=O(q.Id),B=p.get(O(x));B===void 0||c.has(A)||(c.add(A),p.set(A,B),o.set(B,[...o.get(B)??[],q.Id]),!(z&&q[Ce]===!0)&&(d.set(B,[...d.get(B)??[],{objectApiName:P,id:q.Id}]),f.set(P,[...f.get(P)??[],q.Id]),u.set(P,[...u.get(P)??[],a?O(x):B]),h.set(P,[...h.get(P)??[],q.Id])))}})).forEach((T,F)=>{if(!T.read){if(vi.test(T.reason)){this.noBin.add(k[F].child);return}this.notes.push(`The ${k[F].child} records that come back with ${g} could not be read (${T.reason}): Undo may not send those ${s} records back to the recycle bin.`)}})}l=[];for(let[g,w]of h)l.push({objectApiName:g,cascades:await this.cascadesUnder(g),ids:w})}for(let[h,g]of f)await e.withParent(h,g,u.get(h),{carriers:a});if(a)for(let h of o.values())for(let g of h)this.carried.add(g);return{byParent:o,under:d}}cascadesUnder(e){let t=this.cascadesOfObject.get(e);return t||(t=this.cascadesOf(e).catch(n=>(this.notes.push(`The records that come back with ${e} records could not be told (${Q(n)}): Undo may not send them back to the recycle bin.`),[])),this.cascadesOfObject.set(e,t)),t}async undeleteStamps(e,t,n){let s={},r=de(e);try{for(let a of ge(t,Y)){let o=await this.org.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${a})`);for(let d of o.records)if(!(typeof d.Id!="string"||typeof d.LastModifiedDate!="string")){s[d.Id]=d.LastModifiedDate;for(let c of n.get(O(d.Id))??[])s[c]=d.LastModifiedDate}}}catch(a){this.notes.push(`What bringing back ${e} records left on them could not be read (${Q(a)}): the second pass may read them as changed by someone else.`)}return s}async giveBack(e,t,n,s,r,a,o,d){let{checkpoint:c,folder:p}=this.request;for(let{objectApiName:f,count:u}of n.objects){if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:u,notReached:u}),o.cancelled=!0;continue}let l=r(f),h=await et.read(p,c.snapshotId,f),g=t.giveBack.heldBy.find(y=>y.objectApiName===f),w=l.find(y=>y.toLowerCase()==="status");for await(let y of n.pages(f,Se)){let m=y.filter(j=>!h.retired(j));if(m.length===0)continue;if(o.cancelled||this.stopped()){o.restore({...wt(f),planned:m.length,notReached:m.length}),o.cancelled=!0;continue}let k=async(j,z,q,x)=>{let A=await Ye({org:this.org,plan:[{objectApiName:f,backup:c.snapshotId,ids:[...j]}],backups:Hi(h.chunk(j),f,z,q,this.leftFields),fields:{[f]:[...z]},changedAfter:t.restore.changedAfter,ownWriters:rt(c.takenBy,this.userId),includeChanged:!1,stamps:{...t.restore.stamps,...this.stamps},keep:e.keep,stampsFor:()=>!0,...x?{counted:x}:{},...this.signal?{signal:this.signal}:{}});return d(A.stamps),A.wrote&&(o.wrote=!0,await e.wrote()),A.cancelled&&(o.cancelled=!0),A};if(f==="Order"&&w!==void 0&&(await k(m,[w],j=>j[w]==="Draft"),o.cancelled))continue;let L=s==="before"?m.filter(j=>a.has(j)):[];if(L.length>0&&(await k(L,l),o.cancelled))continue;let S=L.length>0?m.filter(j=>!a.has(j)):m;if(S.length===0)continue;let T={restored:[],alreadyGone:[]},F=await k(S,l,void 0,(j,z)=>{this.comesBack.has(j)&&T[z].push(j)});for(let j of F.objects)o.restore(j,T);o.leftBy("restore",f,F.left);let P=F.objects[0];if(s==="after"&&g&&P&&P.refused+(P.restoredWithout??0)>0){let j=o.heldInPlace.get(f)??{reason:rs(f,g.by),ids:new E};for(let z of F.left)j.ids.add(z);o.heldInPlace.set(f,j)}}}}async residualOf(e,t,n,s,r){let a=new Map,o=(u,l,h,g={})=>{let w=`${u}\0${l}\0${g.by??""}\0${g.message??""}`,y=a.get(w);y||(y={objectApiName:u,reason:l,...g.by!==void 0?{by:g.by}:{},count:0,ids:[],...g.message!==void 0?{message:g.message}:{}},a.set(w,y)),y.count++,y.ids.length<Ws&&y.ids.push(h)},d=n[n.length-1],c=r?[r,s]:[s],p=[...this.request.checkpoint.objects].sort((u,l)=>u.readOrder-l.readOrder),f=await this.throughCarriers(e.dir);for(let u of p){let l=u.objectApiName;if(this.picked!==void 0&&!this.picked.has(l))continue;let h=[];for(let m of _s)for await(let k of se(ye(e.dir,l,m)))typeof k.Id=="string"&&(m==="comesBackWithParent"&&f.has(k.Id)||h.push({cls:m,id:k.Id}));if(h.length===0)continue;let g=await this.whoChanged(e.dir,l,h),w=this.keptOf(d,l),y=new E;for await(let m of se(ye(t.dir,l,"goneForGood")))typeof m.Id=="string"&&y.add(m.Id);for(let{cls:m,id:k}of h){if(y.has(k))continue;if(m==="goneForGood"){o(l,"goneForGood",k);continue}let L=pi[m];if(L!==void 0){o(l,"kept",k,{message:L});continue}let S=g.get(O(k)),T=pt(S?.at)>this.before,F=T&&this.isOwn(k,S);if(T&&!F){o(l,"changedDuringRewind",k,S?.by?{by:S.by}:{});continue}let P=n.map(({plan:A})=>A.limited?.why.get(O(k))).find(A=>A!==void 0);if(P!==void 0){o(l,"kept",k,{message:P});continue}if(!n.some(({acted:A})=>A.get(l)?.has(k)===!0)){o(l,F?"automation":"changedSincePreview",k);continue}let z=w(k,m);if(z!==void 0){o(l,"kept",k,{message:z});continue}if(m==="withParent"&&c.some(A=>A.left.restore.get(l)?.has(k)===!0)){o(l,"refused",k,{message:this.refusalOf(c,"restore",l,k)});continue}if(F){o(l,"automation",k);continue}if(ft[m]==="undelete"||m==="toRecreate"){if(c.some(B=>B.outOfReach.get(l)?.has(k)===!0)){o(l,"kept",k,{message:Jt});continue}if(c.some(B=>B.lost.get(l)?.has(k)===!0)){o(l,"goneForGood",k);continue}let A=c.map(B=>B.notAsked.get(O(k))).find(B=>B!==void 0);if(A!==void 0){o(l,"kept",k,{message:A});continue}if(c.some(B=>B.notInBin.get(l)?.has(k)===!0)){o(l,"notInBin",k);continue}}let q=ft[m]==="undelete"&&c.some(A=>A.left.recreate.get(l)?.has(k)===!0)?"recreate":ft[m],x=q==="removal"?this.keptForDependents(c,l,k):void 0;if(x!==void 0){o(l,"kept",k,{message:hi(x)});continue}o(l,"refused",k,{message:q?this.refusalOf(c,q,l,k):_t})}}return await this.linksStillDiffering(e.dir,n,c,o),[...a.values()]}async linksStillDiffering(e,t,n,s){if(this.request.checkpoint.files===void 0||this.picked!==void 0&&!this.picked.has(Ae))return;let r=d=>`${O(d.ContentDocumentId)}:${O(d.LinkedEntityId)}`,a=new Set;for(let{plan:d}of t)for(let{file:c}of[d.links.unlink,d.links.relink,d.links.share])for await(let p of se(c)){let f=we.safeParse(p);f.success&&a.add(r(f.data))}let o=new Map;for(let d of[...n].reverse())for(let c of["unlink","relink","share"])for(let{id:p,reason:f}of d.links[c].left)o.set(O(p),f);for(let d of["linkAdded","linkRemoved","linkChanged"])for await(let c of se(Lt(e,d))){let p=we.safeParse(c);if(!p.success)continue;let f=p.data,u=d==="linkChanged"?Nt.safeParse(c):void 0;if(u?.success===!0&&u.data.now.Visibility===f.Visibility&&u.data.now.ShareType!==f.ShareType&&f.LinkedEntityId.startsWith(ki)){s(ne,"kept",f.Id,{message:it});continue}if(d==="linkAdded"&&f.LinkedEntityId.startsWith(bi)){s(ne,"kept",f.Id,{message:Bt});continue}if(!a.has(r(f))){s(ne,"changedSincePreview",f.Id);continue}s(ne,"refused",f.Id,{message:o.get(O(f.Id))??_t})}}async throughCarriers(e){let t=new E,n=this.request.checkpoint.objects;for(let{objectApiName:s}of n)for await(let r of se(ye(e,s,"carrier")))typeof r.Id=="string"&&t.add(r.Id);for(let s=t.size>0;s;){s=!1;for(let r of n){let a=new E;for await(let o of se(ye(e,r.objectApiName,"comesBackWithParent")))typeof o.Id=="string"&&a.add(o.Id);if(a.size!==0)for await(let o of se(st(e,r.objectApiName)))typeof o.Id!="string"||!a.has(o.Id)||t.has(o.Id)||r.cascadeParents.some(d=>t.has(o[d]))&&(t.add(o.Id),s=!0)}}return t}async whoChanged(e,t,n){let s=new Set(n.map(({id:a})=>O(a))),r=new Map;for(let a of[xn(e,t),st(e,t)])for await(let o of se(a))typeof o.Id!="string"||!s.has(O(o.Id))||r.set(O(o.Id),{...typeof o.LastModifiedById=="string"?{by:o.LastModifiedById}:{},...typeof o.LastModifiedDate=="string"?{at:o.LastModifiedDate}:{}});return r}isOwn(e,t){return t?.by!==void 0&&this.owners.has(O(t.by))?!0:pt(t?.at)<=(this.stampOf.get(O(e))??Number.NaN)}addStamps(e){for(let[t,n]of Object.entries(e)){this.stamps[t]=n;let s=pt(n),r=O(t);Number.isFinite(s)&&!((this.stampOf.get(r)??Number.NEGATIVE_INFINITY)>s)&&this.stampOf.set(r,s)}}keptOf(e,t){let n=e.plan.left.filter(s=>s.objectApiName===t&&Wt[s.reason]!==void 0);return(s,r)=>{if(n.length===0)return;let a=n.find(o=>o.ids.some(d=>O(d)===O(s)));if(a)return Wt[a.reason];if(ft[r]==="removal"&&!e.plan.deletes.has(O(s)))return Wt[n[0].reason]}}keptForDependents(e,t,n){for(let s of e){if(s.left.removal.get(t)?.has(n)!==!0)continue;let r=s.deleted.get(t);return r&&r.refused===0&&r.keptDependents>0&&r.heldBy.length>0?r.heldBy:void 0}}refusalOf(e,t,n,s){let r=t==="restore"?e.map(a=>a.heldInPlace.get(n)).find(a=>a?.ids.has(s)===!0)?.reason:void 0;for(let a of e){if(a.left[t].get(n)?.has(s)!==!0)continue;let d=(t==="restore"?a.restored.get(n)?.reasons:t==="undelete"?a.undeleted.get(n)?.reasons:t==="recreate"?a.recreated.get(n)?.reasons:a.deleted.get(n)?.reasons)?.find(c=>c!==r);if(d!==void 0)return r?`${d} \u2014 ${r}`:d}return r??_t}};function Hi(i,e,t,n,s){return{batches:async(r,a,o)=>{let d=await i.batches(r,a,o);return d?{async*[Symbol.asyncIterator](){for await(let c of d){let p=c.filter(f=>n?.(f)??!0).map(f=>tr(tt(e,f,t),typeof f.Id=="string"?s?.get(O(f.Id)):void 0));p.length>0&&(yield p)}}}:null}}}function tr(i,e){if(e===void 0)return i;for(let t of Object.keys(i))t!=="Id"&&e.has(t.toLowerCase())&&delete i[t];return i}var Vi=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function Gt(i){return(Array.isArray(i)?i:[i]).map(t=>{let n=Vi.safeParse(t);if(!n.success)return{success:!1};let{success:s,id:r,errors:a}=n.data,o=(a??[]).map(d=>typeof d=="string"?d:[d.statusCode,d.message].filter(c=>c).join(": ")).filter(d=>d!=="");return{success:s,...typeof r=="string"?{id:r}:{},...o.length>0?{error:o.join("; ")}:{}}})}export{wo as a,mo as b,yo as c,Fo as d,Ws as e,fi as f,Jt as g,gi as h,wi as i,ya as j,Oi as k,Pi as l,qe as m,$i as n,Wi as o,Js as p,Ki as q,ka as r};
@@ -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{a as R}from"./chunk-CE6ZDGBB.mjs";import{E as g,F as u,J as w,M as m,N as I,O as k}from"./chunk-CGWXQX75.mjs";import{g as T}from"./chunk-SIOZXPFG.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{vb as y}from"./chunk-B45CNPUX.mjs";var b="Opportunity",v=new Set(["Id","OpportunityId",u,"IsPrimary"]),O=200,l=s=>s.slice(0,15);function S(s){return`The contact roles the platform wrote with the run's opportunities were not looked up, so written as generated: an opportunity may hold the role of its contact twice. ${s}`}var P=class{constructor(e){this.deps=e}deps;sentWith=new Map;untold;linkedIds=[];said;unread;alike=0;opportunitiesWritten(e,d){let r=t=>{let n=t?.[u];return typeof n=="string"&&n!==""?n:void 0},o=d.rows&&(d.rows.length===e.length||d.stopped)?d.rows:void 0;if(!o){d.successIds.length>0&&e.some(t=>r(t))&&(this.untold??="The opportunities' insert did not say which record each id it answered is.");return}o.forEach((t,n)=>{let a=r(e[n]);if(!(!t.id||a===void 0)){if(t.unmatched){this.untold??="The opportunities' insert did not say which record each id it answered is.";return}this.sentWith.set(l(t.id),a)}})}async link(e){if(e.length>0&&this.untold!==void 0&&(this.unread??=this.untold),this.sentWith.size===0||e.length===0)return new Map;let d=e.map(i=>({OpportunityId:i.OpportunityId,[u]:i[u],IsPrimary:i.IsPrimary})),r=i=>this.sentWith.get(l(i)),o=this.deps.readTarget;if(!o)return W(d,r)&&(this.unread??="This run cannot read the target."),new Map;let t;try{t=await k(o,d,r,A(e))}catch(i){return this.unread??=h(i),new Map}let{found:n,alike:a}=t;this.alike+=a.length;for(let i of[...n.keys(),...a])this.sentWith.delete(l(String(e[i].OpportunityId)));return n.size>0&&await this.give(e,n),n}async give(e,d){let r=this.said??={records:0,given:0},o=[];for(let[n,a]of d){let i=String(a.Id);this.linkedIds.push(i),r.records++;let p=Object.entries(e[n]??{}).filter(([f,c])=>!v.has(f)&&c!==null&&c!==void 0&&String(a[f]??"")!==String(c));p.length>0&&o.push({Id:i,...Object.fromEntries(p)})}if(o.length===0)return;let t=n=>{r.refusal??=n};if(!this.deps.update)return t("This run cannot update the target.");for(let n=0;n<o.length;n+=O){if(this.deps.stopped())return t("The run was stopped before they were given them.");let a=o.slice(n,n+O),i;try{i=await this.deps.update(this.deps.orgId,g,a)}catch(p){t(h(p));continue}a.forEach((p,f)=>{let c=i[f];c?.success?r.given++:t(c?.error??"The org gave no answer for it.")})}}resultOf(e){return e!==g?{linkedIds:[],notes:[]}:{linkedIds:this.linkedIds,...this.said?{writtenByThePlatform:{...this.said}}:{},notes:[...this.unread!==void 0?[S(this.unread)]:[],...this.alike>0?[m(this.alike,"generated")]:[]]}}};function A(s){return[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>!v.has(e))}function W(s,e){return s.some(d=>{let r=d.OpportunityId,o=d[u];if(typeof r!="string"||typeof o!="string")return!1;let t=e(r);return t!==void 0&&l(t)===l(o)})}function j(){let s=new Map,e=0;return{inserted(d,r,o){d===b&&r.forEach((t,n)=>{let a=t[u],i=o[n];i!==void 0&&typeof a=="string"&&a!==""&&s.set(i,a)})},readTarget:async d=>{let r=w(d);if(!r)throw new Error("A dry run reads nothing else of the target here.");let o=new Date().toISOString();return r.opportunities.flatMap(t=>{let n=s.get(t);return n===void 0?[]:[I({...Object.fromEntries(r.fields.map(a=>[a,null])),Id:`dry-role-${e++}`,OpportunityId:t,[u]:n,...r.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},o)]})},update:async(d,r,o)=>o.map(()=>({success:!0}))}}function _(s){if(s)return`${s.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${s.given} given the fields the seed generated for ${s.given===1?"it":"them"}`+(s.refusal!==void 0?`, the others left as the platform wrote them (${s.refusal}).`:".")}function B(s){return{readTarget:e=>R(s,e),update:async(e,d,r)=>{let o=await s.sobject(d).update(r,{allOrNone:!1,headers:y()}),t=Array.isArray(o)?o:[o];return r.map((n,a)=>{let i=t[a];return i?.success===!0?{success:!0}:{success:!1,error:(i?.errors??[]).length>0?T(i?.errors):"The org gave no answer for it."}})}}}export{b as a,S as b,P as c,j as d,_ as e,B as f};
7
+ import{a as R}from"./chunk-CE6ZDGBB.mjs";import{F as g,G as u,K as w,N as m,O as I,P as k}from"./chunk-55LQD3Y3.mjs";import{g as T}from"./chunk-3B5H24ZG.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{Yb as y}from"./chunk-DPYTG6DM.mjs";var b="Opportunity",v=new Set(["Id","OpportunityId",u,"IsPrimary"]),O=200,l=s=>s.slice(0,15);function S(s){return`The contact roles the platform wrote with the run's opportunities were not looked up, so written as generated: an opportunity may hold the role of its contact twice. ${s}`}var P=class{constructor(e){this.deps=e}deps;sentWith=new Map;untold;linkedIds=[];said;unread;alike=0;opportunitiesWritten(e,d){let r=t=>{let n=t?.[u];return typeof n=="string"&&n!==""?n:void 0},o=d.rows&&(d.rows.length===e.length||d.stopped)?d.rows:void 0;if(!o){d.successIds.length>0&&e.some(t=>r(t))&&(this.untold??="The opportunities' insert did not say which record each id it answered is.");return}o.forEach((t,n)=>{let a=r(e[n]);if(!(!t.id||a===void 0)){if(t.unmatched){this.untold??="The opportunities' insert did not say which record each id it answered is.";return}this.sentWith.set(l(t.id),a)}})}async link(e){if(e.length>0&&this.untold!==void 0&&(this.unread??=this.untold),this.sentWith.size===0||e.length===0)return new Map;let d=e.map(i=>({OpportunityId:i.OpportunityId,[u]:i[u],IsPrimary:i.IsPrimary})),r=i=>this.sentWith.get(l(i)),o=this.deps.readTarget;if(!o)return W(d,r)&&(this.unread??="This run cannot read the target."),new Map;let t;try{t=await k(o,d,r,A(e))}catch(i){return this.unread??=h(i),new Map}let{found:n,alike:a}=t;this.alike+=a.length;for(let i of[...n.keys(),...a])this.sentWith.delete(l(String(e[i].OpportunityId)));return n.size>0&&await this.give(e,n),n}async give(e,d){let r=this.said??={records:0,given:0},o=[];for(let[n,a]of d){let i=String(a.Id);this.linkedIds.push(i),r.records++;let p=Object.entries(e[n]??{}).filter(([f,c])=>!v.has(f)&&c!==null&&c!==void 0&&String(a[f]??"")!==String(c));p.length>0&&o.push({Id:i,...Object.fromEntries(p)})}if(o.length===0)return;let t=n=>{r.refusal??=n};if(!this.deps.update)return t("This run cannot update the target.");for(let n=0;n<o.length;n+=O){if(this.deps.stopped())return t("The run was stopped before they were given them.");let a=o.slice(n,n+O),i;try{i=await this.deps.update(this.deps.orgId,g,a)}catch(p){t(h(p));continue}a.forEach((p,f)=>{let c=i[f];c?.success?r.given++:t(c?.error??"The org gave no answer for it.")})}}resultOf(e){return e!==g?{linkedIds:[],notes:[]}:{linkedIds:this.linkedIds,...this.said?{writtenByThePlatform:{...this.said}}:{},notes:[...this.unread!==void 0?[S(this.unread)]:[],...this.alike>0?[m(this.alike,"generated")]:[]]}}};function A(s){return[...new Set(s.flatMap(e=>Object.keys(e)))].filter(e=>!v.has(e))}function W(s,e){return s.some(d=>{let r=d.OpportunityId,o=d[u];if(typeof r!="string"||typeof o!="string")return!1;let t=e(r);return t!==void 0&&l(t)===l(o)})}function j(){let s=new Map,e=0;return{inserted(d,r,o){d===b&&r.forEach((t,n)=>{let a=t[u],i=o[n];i!==void 0&&typeof a=="string"&&a!==""&&s.set(i,a)})},readTarget:async d=>{let r=w(d);if(!r)throw new Error("A dry run reads nothing else of the target here.");let o=new Date().toISOString();return r.opportunities.flatMap(t=>{let n=s.get(t);return n===void 0?[]:[I({...Object.fromEntries(r.fields.map(a=>[a,null])),Id:`dry-role-${e++}`,OpportunityId:t,[u]:n,...r.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},o)]})},update:async(d,r,o)=>o.map(()=>({success:!0}))}}function _(s){if(s)return`${s.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${s.given} given the fields the seed generated for ${s.given===1?"it":"them"}`+(s.refusal!==void 0?`, the others left as the platform wrote them (${s.refusal}).`:".")}function B(s){return{readTarget:e=>R(s,e),update:async(e,d,r)=>{let o=await s.sobject(d).update(r,{allOrNone:!1,headers:y()}),t=Array.isArray(o)?o:[o];return r.map((n,a)=>{let i=t[a];return i?.success===!0?{success:!0}:{success:!1,error:(i?.errors??[]).length>0?T(i?.errors):"The org gave no answer for it."}})}}}export{b as a,S as b,P as c,j as d,_ as e,B as f};