sandforge 1.85.0 → 1.86.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.
- package/README.md +1 -1
- package/lib/{chunk-THYQOG24.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-U4S27YRP.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-MRN72UEO.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-YZKE6D3K.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-3OKDWZ32.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-32ZB5ICW.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-JFVY66BS.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-ULEYGOZU.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GHUA6OQQ.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-SF52ZSIV.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-FBYFCKPG.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-A3QNSALB.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-TWYNQ2OO.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-JRI6A24G.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-VPGX5Z5D.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-CI2O7WBH.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-5T3LFDJ5.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/{chunk-F2424IKX.mjs → chunk-6ROL3KBM.mjs} +1 -1
- package/lib/{chunk-7ZYCRIHE.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-MQLTEXB7.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-73SLYGWD.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-JBOGAUGH.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-C2MHMI7U.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-VLAU5QQT.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-KYLHS74X.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-A7YP27GQ.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-ZDMSTL2L.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-LY6EPMIP.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-LOO42EW5.mjs → chunk-C7CKDZMC.mjs} +62 -62
- package/lib/{chunk-ZP3WJGS3.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-7L6FE5PP.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-S6BMJSLD.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-YXOPKGDX.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-PGG4ULEW.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-FG4Y4ZVL.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-YGE4AUXG.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-DCJBP3LE.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-ROTDZKOE.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-SES5HPBZ.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-QAXKUEJT.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-AX3YF7SC.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-57QRXYAZ.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-FCZDWGQI.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-74HZ274R.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-G6IYOZEH.mjs → chunk-FV6MOSHD.mjs} +1 -1
- package/lib/chunk-FYG47CNA.mjs +7 -0
- package/lib/chunk-GB6W4Q56.mjs +7 -0
- package/lib/chunk-GEV2DCMK.mjs +7 -0
- package/lib/{chunk-NZJXEULY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-EFHDE7W4.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-P6A22FMQ.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-BRN42U26.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-GNCEHAJY.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-GUYEXPJ4.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-3GATEVHC.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-55VBV2WK.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-HV3TDLFR.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-WZX6VCIT.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-RY7WUJXH.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-OUWR5M5G.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-F44EHXLI.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-IZ2M2RGO.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-VKA5OZBJ.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-FM5ESRH6.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-4D6OHSX3.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-BY42YL4D.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-A6IJUOLB.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-FZF6FB65.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-2UUSF32M.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-LUNGNCM3.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-YTBM3TSW.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-P3OYE2FS.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-TSTCHIBU.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-6HAKOS6W.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-OXIIKAUZ.mjs → chunk-O7YIEFG7.mjs} +1 -1
- package/lib/chunk-OCUVAA5E.mjs +7 -0
- package/lib/chunk-OLCS7JCT.mjs +14 -0
- package/lib/chunk-ON7Y63FK.mjs +9 -0
- package/lib/{chunk-K2WOT75I.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-3EOIAC2M.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-BK5SRDAD.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-DCZYWMSA.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-LU7M5URW.mjs → chunk-PIQ2I67B.mjs} +1 -1
- package/lib/chunk-PKYDNZJK.mjs +7 -0
- package/lib/chunk-PVZ72OOQ.mjs +7 -0
- package/lib/chunk-QACFTHJM.mjs +8 -0
- package/lib/{chunk-LNAZHI3J.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-4RNP65FV.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-OTKXTBTX.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-IVDBVWKK.mjs → chunk-RPTEEI4R.mjs} +1 -1
- package/lib/chunk-RQW5S67A.mjs +7 -0
- package/lib/chunk-RTCMYMED.mjs +7 -0
- package/lib/chunk-RWVX7XSD.mjs +7 -0
- package/lib/{chunk-2UUS4IGB.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-RC25QQVF.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-Z354SAEF.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-45375WT5.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-BGJBYDRW.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/{chunk-B5A4JHNN.mjs → chunk-TICZXC53.mjs} +1 -1
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-W6SLQZKQ.mjs → chunk-TMIV3IWH.mjs} +1 -1
- package/lib/chunk-TQ6HEJ73.mjs +11 -0
- package/lib/chunk-TTU5EQZ6.mjs +7 -0
- package/lib/chunk-TYUYPFDJ.mjs +7 -0
- package/lib/chunk-TZXYVMZC.mjs +7 -0
- package/lib/{chunk-4N425UJC.mjs → chunk-UCUFLFNK.mjs} +1 -1
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-SKGAERV4.mjs → chunk-UM2B4GR7.mjs} +1 -1
- package/lib/chunk-UZFTTNOP.mjs +7 -0
- package/lib/chunk-V3AXSKSU.mjs +7 -0
- package/lib/chunk-VA6EEI6X.mjs +21 -0
- package/lib/{chunk-LSEM2BZH.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-EYFP3NA6.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-TIVI2KGB.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-J3FJ3BWE.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-UX4AOSMU.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-CUOWQMGW.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-JHJDDQDE.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-IZREPWYQ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-XZRON54U.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-N2MXYD67.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-GG5I52UT.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-3QCUSZIZ.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-MN3XBJPE.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-SBDF4AE5.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-SQM32AOQ.mjs → chunk-YJ27WHKR.mjs} +1 -1
- package/lib/chunk-YRULC27A.mjs +7 -0
- package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
- package/lib/chunk-YTOTMJTY.mjs +15 -0
- package/lib/{chunk-SU24AE3H.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-LJNRN7MY.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-NMF55UBQ.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-6ZWY36LK.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-YV7JYHJP.mjs → chunk-ZIKLQZBG.mjs} +1 -1
- package/lib/chunk-ZVU7MD2S.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +33 -27
- package/lib/sandforge-backup.mjs +19 -19
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +29 -16
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -13
- package/lib/sandforge-env.mjs +105 -105
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +2 -2
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +13 -13
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +13 -15
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/dataops.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-26EGXYZ4.mjs +0 -21
- package/lib/chunk-2JRVBXJL.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-3XU7CEJQ.mjs +0 -7
- package/lib/chunk-4BQPAVMP.mjs +0 -14
- package/lib/chunk-4KMKOE77.mjs +0 -156
- package/lib/chunk-4RPA7Z52.mjs +0 -7
- package/lib/chunk-5C7LQXYS.mjs +0 -7
- package/lib/chunk-5EESNYE3.mjs +0 -8
- package/lib/chunk-6ZW6BLV5.mjs +0 -7
- package/lib/chunk-AAOMUI7S.mjs +0 -15
- package/lib/chunk-AIUAEBHR.mjs +0 -7
- package/lib/chunk-BD724WOH.mjs +0 -7
- package/lib/chunk-CRPLDXJU.mjs +0 -48
- package/lib/chunk-CSSOLHE3.mjs +0 -7
- package/lib/chunk-D63HEQ3B.mjs +0 -7
- package/lib/chunk-DN7YBILC.mjs +0 -21
- package/lib/chunk-DNE7JI3A.mjs +0 -11
- package/lib/chunk-EFHM2U4D.mjs +0 -7
- package/lib/chunk-EINEGS6E.mjs +0 -7
- package/lib/chunk-EM5EFMHA.mjs +0 -272
- package/lib/chunk-FH5UR35W.mjs +0 -7
- package/lib/chunk-FN7TOBJR.mjs +0 -7
- package/lib/chunk-HGJFATSI.mjs +0 -10
- package/lib/chunk-HOEE3PE5.mjs +0 -7
- package/lib/chunk-HV63UGL5.mjs +0 -7
- package/lib/chunk-JKFCGYJE.mjs +0 -7
- package/lib/chunk-KATBU46O.mjs +0 -7
- package/lib/chunk-LD34JNCC.mjs +0 -7
- package/lib/chunk-LPN4WYTP.mjs +0 -478
- package/lib/chunk-MAOUFJ47.mjs +0 -7
- package/lib/chunk-MB2DG66I.mjs +0 -13
- package/lib/chunk-NCASRA7L.mjs +0 -9
- package/lib/chunk-NEKNAILD.mjs +0 -7
- package/lib/chunk-NN2IO4WE.mjs +0 -7
- package/lib/chunk-O3ZQSWDN.mjs +0 -10
- package/lib/chunk-OFQOKSEW.mjs +0 -7
- package/lib/chunk-PP7PJXRJ.mjs +0 -341
- package/lib/chunk-PT2E2HFD.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QBYK5XIT.mjs +0 -8
- package/lib/chunk-RFD6NPWJ.mjs +0 -8
- package/lib/chunk-RIIJJRGF.mjs +0 -7
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-RM5G4IP6.mjs +0 -19
- package/lib/chunk-RTPNK7OB.mjs +0 -7
- package/lib/chunk-RZXEO5IE.mjs +0 -7
- package/lib/chunk-SAHGDSZQ.mjs +0 -37
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-SVNSAHG3.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TE2W76II.mjs +0 -10
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TFGJDZFE.mjs +0 -7
- package/lib/chunk-TG52WNGV.mjs +0 -10
- package/lib/chunk-TQONVFI3.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UZMLPKW6.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WQO7RXEB.mjs +0 -926
- package/lib/chunk-X3MBY2RX.mjs +0 -7
- package/lib/chunk-XMJRXXUN.mjs +0 -7
- package/lib/chunk-YNMU5I7P.mjs +0 -7
- package/lib/chunk-YSQJKIO6.mjs +0 -7
- package/lib/chunk-YVVPJRZC.mjs +0 -7
- package/lib/chunk-ZLQHBI6V.mjs +0 -9
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{i as Ps,l as Os}from"./chunk-GFB2DNCB.mjs";import{f as Is,g as As}from"./chunk-JFXQZPRY.mjs";import{a as ms,b as ws,c as ke,d as ys,e as ks,f as ft,g as bs,h as Rs,i as Ss,j as vs}from"./chunk-BBZUGKBZ.mjs";import{c as us}from"./chunk-P4YOHLZ4.mjs";import{b as ls}from"./chunk-BLMJ4WVI.mjs";import{a as Mt,b as os,c as Se,d as Ut,e as $t,f as as,g as ds,m as cs}from"./chunk-XBYXT74L.mjs";import{d as Dt,f as Ue,l as Ft,n as ct}from"./chunk-4VLP6RHC.mjs";import{a as hs,b as gs}from"./chunk-FV6MOSHD.mjs";import{Lc as ot,Pc as Tn,Qc as Dn}from"./chunk-CJAWKLAL.mjs";import{a as Nn,b as Bn,c as En,e as it,f as Cn,h as ss,i as rs}from"./chunk-VKREON6Q.mjs";import{a as Ct,d as zn,f as Wn,h as _n,j as qn,k as xn,l as at,m as Jn,p as Gn,q as Kn}from"./chunk-CL75DEMQ.mjs";import{A as Xn,C as Qn,F as es,G as ts,H as ns,e as jn}from"./chunk-7O6EFNQS.mjs";import{G as se,H as An,I as Bt,J as Pn,M as On,O as rt}from"./chunk-3LRFPGYZ.mjs";import{l as Ln}from"./chunk-KWUS7UAV.mjs";import{a as Nt,b as In}from"./chunk-YDXMTWAT.mjs";import{B as $e,E as is,F as ut,i as Je,j as Tt,l as Ne,p as Fe,q as Yn,r as dt,z as lt}from"./chunk-DLSU66MY.mjs";import{b as N,e as Me,g as Zn}from"./chunk-ATQML7ZK.mjs";import{A as Ge,H as K,N as Vn,d as Pe,g as Hn,x as Le,y as De,z as ye}from"./chunk-4CSBZZAL.mjs";import{b as V,d as ge,e as Sn}from"./chunk-GP5J3DGS.mjs";import{c as Fn}from"./chunk-ZVU7MD2S.mjs";import{bb as fs,k as Et,o as Mn,p as Un,q as $n,vc as ps}from"./chunk-OLCS7JCT.mjs";import{i as st}from"./chunk-INIT2UKJ.mjs";import{E as vn}from"./chunk-4XROG5CT.mjs";import{g as Te,h as ie,i as bn,q as Rn}from"./chunk-DAUX63UB.mjs";import{da as nt,ja as yn,ka as kn}from"./chunk-SZOJ7BEJ.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{$c as mn,Cc as gn,Ua as pn,Wa as tt,Xa as hn,ae as wn,ie as jt,le as Lt}from"./chunk-J347SPU6.mjs";import{b as X,e as Qe,f as xe,i as Ot,k as me,l as q,o as et,p as ln,s as un,u as Ce,v as Q,z as fn}from"./chunk-WZQEK4WT.mjs";import{randomBytes as cr}from"node:crypto";import{rm as lr}from"node:fs/promises";import{join as ur}from"node:path";var Er=5,Cr="005",Tr=new Set(["001"]),Wt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",pt="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 we(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function ze(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)ht(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ht(i,e){i.length<Er&&!i.includes(e)&&i.push(e)}var Dr=q({success:xe(),id:X().nullish(),errors:me(et([X(),q({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function Fr(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=Dr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:o,id:a,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,l=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(f=>f).join(": ")).filter(u=>u!=="").join("; ");return{success:o,...typeof a=="string"?{id:a}:{},...p!==void 0?{code:p}:{},...l!==""?{words:l}:{}}})}function Mr(i){let e=[];for(let t=0;t<i.length;t+=V)e.push(i.slice(t,t+V));return e}async function _t(i,e,t,n){let s=we();for(let r of Mr(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 o=Fr(await t(r),r.length),a={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=o[c],l=n(p);if(l==="done"){s.done++,a.done.push(d),p.id!==void 0&&a.made.push({from:d.Id,id:p.id});return}if(a.left.push(d.Id),l==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ht(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...a.made),await e.after?.(a)}return s}function js(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ht(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function gt(i,e,t={}){let n=we(),s=js(e,o=>o.LinkedEntityId?.startsWith(Cr)===!0,Wt,n),r=await _t(s,t,o=>i.destroy(ie,o.map(a=>a.Id)),o=>o.success?"done":o.code==="ENTITY_IS_DELETED"||o.code==="NOT_FOUND"?"already":"refused");return ze(r,n),r}async function mt(i,e,t={},n=s=>s){return _t(e,t,s=>i.create(ie,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 wt(i,e,t={}){let n=d=>Tr.has(d.LinkedEntityId.slice(0,3)),s=we(),r=new Map,o=js(e,d=>d.Visibility===d.now.Visibility&&n(d),pt,s);for(let d of o){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ht(s.reasons,pt),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let a=await _t(o,t,d=>i.update(ie,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return ze(s,a),s}import{randomBytes as Ts}from"node:crypto";import{closeSync as Ur,createReadStream as Ds,fsyncSync as $r,openSync as zr,readFileSync as Wr,renameSync as _r,writeSync as qr}from"node:fs";import{open as bt,readdir as Fs,rm as Ms,stat as xr,truncate as Us}from"node:fs/promises";import{dirname as $s,join as te}from"node:path";import{createInterface as zs}from"node:readline";var We="journal.ndjson",Jr="before.json",J=2e3,Ws=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),xt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),Ie=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Y=fn.datetime({offset:!0}),ce=me(Ws).min(1).max(J),Kt=Qe().int().positive(),_s=q({kind:Q("head"),version:Q(1),rewindId:tt,checkpointId:pn,organizationId:hn,startedAt:Y,userId:xt,automatedProcessUserId:xt.optional(),backup:X().min(1).max(200),at:Y}),Gr=q({kind:Q("resumed"),startedAt:Y,userId:xt,at:Y}),Kr=q({kind:Ce(["bringingBack","withParent","givingBack"]),objectApiName:Ie,ids:ce,parents:ce.optional(),carriers:Q(!0).optional(),at:Y}),Hr=q({kind:Q("bringBackLeft"),objectApiName:Ie,ids:ce,at:Y}),Vr=q({kind:Q("recreating"),objectApiName:Ie,ids:ce,at:Y}),Yr=q({kind:Q("recreated"),objectApiName:Ie,ids:ce,from:ce,at:Y}),Zr=q({kind:Ce(["deleting","deleteLeft"]),step:Kt,objectApiName:Ie,ids:ce,at:Y}),Xr=q({kind:Q("heldInPlace"),objectApiName:Ie,by:me(Ie).min(1).max(100),ids:ce,at:Y}),Qr=q({kind:Q("beforeParent"),objectApiName:Ie,ids:ce,parents:ce,at:Y}),ei=q({kind:Q("goingAlong"),step:Kt,objectApiName:Ie,ids:ce,parents:ce,at:Y}),ti=q({kind:Q("deleted"),step:Kt,at:Y}),ni=q({kind:Q("removal"),state:Ot(),at:Y}),si=q({kind:Q("unlinking"),links:me(Se).min(1).max(J),at:Y}),ri=q({kind:Ce(["unlinkLeft","linksUpdateLeft"]),ids:ce,at:Y}),ii=q({kind:Q("relinked"),ids:ce,from:ce,at:Y}),qs=Se.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),oi=q({kind:Q("linksUpdating"),links:me(qs).min(1).max(J),at:Y}),ai=q({kind:Q("linksUndone"),part:Ce(["reinserted","removed","shared"]),ids:ce,at:Y}),di=q({kind:Q("wrote"),at:Y}),ci=q({kind:Q("end"),at:Y}),li=q({kind:Q("undo"),state:Ot(),status:Ce(["success","partial","failure","cancelled"]),at:Y}),ui=ln("kind",[_s,Gr,Kr,Hr,Xr,Qr,Vr,Yr,Zr,ei,ti,ni,si,ri,ii,oi,ai,di,ci,li]),fi=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","goingAlong","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Jt(i){let e;try{e=await bt(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ht(i,e){let t=await bt(i,"a",Pe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function pi(i,e){let t=`${i}.${process.pid}-${Ts(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=zr(t,"wx",Pe);try{for(let r=0;r<n.length;)r+=qr(s,n,r,n.length-r);$r(s)}finally{Ur(s)}_r(t,i)}function hi(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,pi(i,`${JSON.stringify({version:1,openings:e})}
|
|
8
|
+
`)}}}function W(i){return i.slice(0,15)}function be(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*gi(i){if(!Pn(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 yt=class i{constructor(e,t,n,s,r,o){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=o;this.rewindId=e.rewindId,this.backup=e.backup;let a=new Set,d=new rs({...ss(t),appendFile:async(p,l)=>{await Ht(p,l),a.has(p)||(a.add(p),await Jt($s(p)))}}),c={begin:()=>ye(te(t,"backups")),append:(p,l,u)=>d.append(p,l,u)};if(this.kept=gs({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:hi(te(t,Jr)),now:o}),this.kept.id!==e.backup)throw new K("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,l)=>{await this.kept.keep(p,l);let u=l.flatMap(f=>typeof f.Id=="string"?[f.Id]:[]);for(let f of be(u))await this.append({kind:"givingBack",objectApiName:p,ids:f})}}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 o=await bt(te(e,We),"a",Pe);try{return new i(t,e,n,o,s,r)}catch(a){throw await o.close(),a}}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 be(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:o}of e){let[a]=o;a!==void 0&&s.set(a.slice(0,3),r)}return async r=>{let o=new Set(r.map(d=>s.get(d.slice(0,3)))),[a]=[...o];if(o.size!==1||a===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",a,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 o=0;o<t.length;o+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(o,o+J),parents:n.slice(o,o+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of be(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of be(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 be(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 gi(e))for(let r of be(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async goingAlong(e,t){let n=this.openStep;if(n===void 0)throw new Error("No removal was named to the journal before it.");for(let s=0;s<t.length;s+=J){let r=t.slice(s,s+J);await this.append({kind:"goingAlong",step:n,objectApiName:e,ids:r.map(({id:o})=>o),parents:r.map(({parent:o})=>o)})}}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 be(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 be(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 be(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of be(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,xs(te(this.dir,We))}async facts(){return await this.queue,wi(te(this.dir,We))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ve(i,e){let t=(await xr(i)).size,n=t===0;if(t>0){let p=await bt(i,"r");try{let l=Buffer.alloc(1);await p.read(l,0,1,t-1),n=l[0]===10}finally{await p.close()}}let s=0,r=0,o=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let l;try{l=JSON.parse(p)}catch{l=void 0}let u=ui.safeParse(l);if(!u.success)throw new K("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);mi(u.data),s++,await e(u.data)},a=Ds(i,{encoding:"utf8"}),d=zs({input:a,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await o(c),c=p}finally{d.close(),a.destroy()}return c!==void 0&&n&&await o(c),{count:s,whole:r,size:t}}function mi(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new K("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 K("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="goingAlong"&&i.parents.length!==i.ids.length)throw new K("damaged","The rewind\u2019s journal names records that went with a parent without it.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new K("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 K("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var Re=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 Ls(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 Ns(i){let e=Ln(i);if(e===void 0)throw new K("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var Ke=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 K("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(fi.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 K("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(Ns(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(Ns(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 K("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:Ls(this.rewindStates),undo:Ls(this.undoStates),undos:this.undos}}},Gt=class{broughtBack=new Re;recreated=new Re;carriers=new Re;carried=new Map;givenBack=new Re;held=new Re;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new Re,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 Re;for(let{deleting:u,left:f,answered:h}of this.steps.values())for(let{objectApiName:m,ids:g}of u.list(k=>!h||!f.has(k)))e.add(m,g);let t=this.held.list().map(({objectApiName:u,ids:f})=>({objectApiName:u,ids:f,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new Re;for(let{objectApiName:u,id:f,parent:h}of this.beforeParent){let m=W(h);n.has(W(f))&&(n.has(m)||!s.has(m))&&r.add(u,[f])}let o=r.list(),a=u=>{let f=new Map;for(let{objectApiName:h,id:m,parent:g}of u){let k=f.get(h)??{objectApiName:h,ids:[],parents:[]};k.ids.push(m),k.parents.push(g),f.set(h,k)}return[...f.values()]},d=a(this.withParents.values()),c=a(this.carried.values()),p=this.carriers.list(),l=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...o.length>0?{deletedBeforeParent:o}:{},...d.length>0?{withParents:d}:{},...l.length>0?{recreated:l}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function xs(i){let e=new Ke,t=new Gt;try{await ve(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof K?n:new K("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function wi(i){let e=new Ke;try{await ve(i,t=>e.line(t))}catch(t){throw t instanceof K?t:new K("notFound","No journal of this rewind is kept.")}return e.result()}function yi(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 K("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function ea(i,e){let t=await He(i,e);if(!t)throw new K("notFound","No journal of this rewind is kept.");return xs(t.file)}function Js(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new K("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function He(i,e){let t=De(i,e),n=te(t,We),s=new Ke,r;try{r=await ve(n,a=>s.line(a))}catch(a){if(a instanceof K)throw a;return}if(r.count===0||s.head===void 0)return;let o=s.result();return yi(o,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:o}}async function Gs(i,e){return i.whole<i.size&&await Us(i.file,i.whole),yt.opened(i.dir,i.head,!0,i.step,e)}var Bs=18;async function ki(i){let e;try{e=(await Fs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&tt.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,Bs)===t.slice(0,Bs))}async function Ks(i){let{folder:e}=i;Js(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await ki(e)){let c=await He(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Gs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(l){throw await p.close(),l}return p}let s=n??Ge("rw",t()),r=De(e,s);await ye(r),await ye(te(r,"backups")),await Us(te(r,We),0).catch(()=>{});let o=_s.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:hs(s),at:t().toISOString()});if(!o.success)throw new K("invalid",`Not a rewind to journal: ${o.error.message}`);let a=await yt.opened(r,o.data,!1,0,t);try{await a.append(o.data),await Jt(r),await Jt(e.rewindsDir)}catch(d){throw await a.close(),d}return a}async function Hs(i,e,t,n=()=>new Date){Js(t,i);let s=await He(i,e);if(!s)throw new K("notFound","No journal of this rewind is kept.");return Gs(s,n)}async function Vs(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=Vn(n),r=[],o=[...n].sort((a,d)=>a.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:a,checkpoint:d}of o){if(d===void 0)continue;let c;try{c=(await Fs(a.rewindsDir,{withFileTypes:!0})).filter(l=>l.isDirectory()&&tt.safeParse(l.name).success).map(l=>l.name).sort()}catch{continue}let p=(l,u)=>u?.checkpointId===a.checkpointId&&u.rewindId===l;for(let l of c){if(p(l,t)||p(l,s))continue;let u=await He(a,l).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await Ms(De(a,l),{recursive:!0,force:!0}),r.push({checkpointId:a.checkpointId,name:d.name,rewindId:l}))}}return r}var kt=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 ye(e);let n=new N,s=new Map,r=new Map,o=async a=>{let d=r.get(a)??[];d.length!==0&&(await Ht(Es(e,a),d.join("")),r.set(a,[]))};await t(async(a,{id:d,parent:c})=>{if(!n.add(d))return;s.set(a,(s.get(a)??0)+1);let p=r.get(a)??[];p.push(`${d} ${c}
|
|
10
|
+
`),r.set(a,p),p.length>=J&&await o(a)});for(let a of s.keys())await o(a);return new i(e,[...s].map(([a,d])=>({objectApiName:a,count:d})),n)}async*pages(e,t=J){if(!this.objects.some(o=>o.objectApiName===e))return;let n=Ds(Es(this.dir,e),{encoding:"utf8"}),s=zs({input:n,crlfDelay:1/0}),r=[];try{for await(let o of s){let[a,d]=o.split(" ");a===void 0||d===void 0||(r.push({id:a,parent:d}),r.length>=t&&(yield r,r=[]))}}finally{s.close(),n.destroy()}r.length>0&&(yield r)}};function Es(i,e){return te(i,`${mn(e)}.pairs`)}async function qt(i,e,t){return e.length>0&&(await ye($s(i)),await Ht(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 $e(i))n.push(t(s)),n.length>=J&&(yield n,n=[]);n.length>0&&(yield n)}}}async function bi(i,e){let t=new Map,n=new Map,s=new Map,r=new Set,o=new Set,a=new Set,d=new Set;await ve(i,u=>{switch(u.kind){case"unlinking":for(let f of u.links)t.has(W(f.Id))||t.set(W(f.Id),f);break;case"unlinkLeft":for(let f of u.ids)t.delete(W(f));break;case"relinked":for(let f of u.ids)n.set(W(f),{Id:f});break;case"linksUpdating":r=new Set;for(let f of u.links)s.has(W(f.Id))||(s.set(W(f.Id),f),r.add(W(f.Id)));break;case"linksUpdateLeft":for(let f of u.ids)r.has(W(f))&&s.delete(W(f));break;case"linksUndone":{let f=u.part==="reinserted"?o:u.part==="removed"?a:d;for(let h of u.ids)f.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])=>!o.has(u)).map(([,u])=>u),p=[...n].filter(([u])=>!a.has(u)).map(([,u])=>u),l=[...s].filter(([u])=>!d.has(u)).map(([,u])=>u);if(c.length+p.length+l.length!==0)return{reinsert:await qt(te(e,"links.reinsert.ndjson"),c,u=>Se.parse(u)),remove:await qt(te(e,"links.remove.ndjson"),p,u=>({Id:q({Id:Ws}).parse(u).Id})),share:await qt(te(e,"links.share.ndjson"),l,u=>qs.parse(u))}}function Cs(i,e){let t=new Map(i.map(s=>[s.objectApiName,s.readOrder])),n=s=>t.get(s)??-1;return s=>[...s].sort((r,o)=>e?n(o.objectApiName)-n(r.objectApiName):n(r.objectApiName)-n(o.objectApiName))}async function Vt(i,e,t){let n=te(i,We),s=te(i,`undo-${Ts(4).toString("hex")}`),r=()=>Ms(s,{recursive:!0,force:!0});try{let o=R=>{if(R===void 0)return()=>!0;let S=new N;for(let L of R)S.add(L);return L=>S.has(L)},a=o(e.undo.removalLeft),d=o(e.undo.undeleteLeft),c=o(e.undo.restoreLeft),p=new N,l=new Set,u=new Map,f=new N,h=new Map,m=new N,g=new Set,k=new Map;await ve(n,R=>{switch(R.kind){case"bringBackLeft":for(let S of R.ids)g.add(W(S));break;case"bringingBack":case"withParent":case"recreated":for(let S of R.ids)p.add(S),g.size>0&&g.delete(W(S));R.kind==="withParent"&&R.carriers===!0&&R.parents&&R.ids.forEach((S,L)=>{let Z=R.parents?.[L];Z!==void 0&&!k.has(W(S))&&k.set(W(S),{objectApiName:R.objectApiName,id:S,parent:W(Z)})});break;case"givingBack":for(let S of R.ids)m.add(S);break;case"deleteLeft":{let S=u.get(R.step)??new N;for(let L of R.ids)S.add(L);u.set(R.step,S);break}case"deleted":l.add(R.step);break;case"heldInPlace":{for(let L of R.ids)f.add(L);let S=h.get(R.objectApiName)??new Set;for(let L of R.by)S.add(L);h.set(R.objectApiName,S);break}default:break}});let y=R=>p.has(R)&&!g.has(R),v=new N,w=new Me(te(s,"bringBack"));await ve(n,async R=>{if(R.kind!=="deleting")return;let S=l.has(R.step)?u.get(R.step):void 0;for(let L of R.ids){if(S?.has(L)===!0)continue;let Z=W(L);y(Z)?v.add(L):d(Z)&&await w.add(R.objectApiName,L)}});let I=new N,C=await kt.written(te(s,"comesWithParent"),async R=>{await ve(n,async S=>{if(S.kind!=="goingAlong")return;let L=l.has(S.step)?u.get(S.step):void 0;for(let[Z,he]of S.ids.entries()){let le=S.parents[Z];L?.has(le)===!0||w.keys.has(he)||!I.add(he)||w.keys.has(le)&&await R(S.objectApiName,{id:he,parent:le})}})}),j=new N;for(let R=k.size>0;R;){R=!1;for(let{id:S,parent:L}of k.values())j.has(S)||m.has(S)||(v.has(L)||j.has(L))&&(j.add(S),R=!0)}let B=R=>v.has(R)||j.has(R),A=R=>!g.has(R)&&!B(R)&&a(R),x=new N,_=new N;await ve(n,R=>{R.kind!=="withParent"||R.parents===void 0||R.ids.forEach((S,L)=>{if(!_.add(S))return;let Z=W(R.parents?.[L]??"");A(W(S))&&y(Z)&&A(Z)&&x.add(S)})});let H=new N,G=new Map;for(let{objectApiName:R,id:S,parent:L}of k.values())!A(W(S))||x.has(S)||!m.has(S)||A(L)&&k.has(L)||(H.add(S),G.set(R,(G.get(R)??0)+1));let U=new Me(te(s,"remove")),T=new Me(te(s,"giveBack")),E=new N,b=new Map,M=await kt.written(te(s,"goesWithParent"),async R=>{await ve(n,async S=>{if(S.kind==="givingBack"){for(let L of S.ids)c(W(L))&&await T.add(S.objectApiName,L);return}if(S.kind==="recreated"){for(let L of S.ids)!A(W(L))||!await U.add(S.objectApiName,L)||(E.add(L),b.set(S.objectApiName,(b.get(S.objectApiName)??0)+1));return}if(!(S.kind!=="bringingBack"&&S.kind!=="withParent"))for(let[L,Z]of S.ids.entries()){let he=W(Z);if(!A(he))continue;let le=S.parents?.[L];x.has(he)?le!==void 0&&await R(S.objectApiName,{id:Z,parent:le}):await U.add(S.objectApiName,Z)}})}),D=await T.finish(),re=await bi(n,s),oe=new N,$=new Map;for(let{objectApiName:R}of D.objects)for await(let S of D.pages(R))for(let L of S)f.has(L)&&(oe.add(L),$.set(R,($.get(R)??0)+1));return{remove:await Zn.of(U,Cs(t,!1)),bringBack:await w.finish(Cs(t,!0)),giveBack:D,giveBackKeys:T.keys,backup:e.head.backup,held:{keys:oe,objects:[...$].map(([R,S])=>({objectApiName:R,count:S,by:[...h.get(R)??[]]}))},goesWithParent:M,comesWithParent:C,remade:{keys:E,objects:[...b].map(([R,S])=>({objectApiName:R,count:S}))},compensated:{has:R=>B(W(String(R)))},carriedAlone:{keys:H,objects:[...G].map(([R,S])=>({objectApiName:R,count:S}))},...re?{links:re}:{},dispose:r}}catch(o){throw await r(),o}}async function ta(i,e,t){let n=await He(i,e);if(!n)throw new K("notFound","No journal of this rewind is kept.");return Vt(n.dir,n.facts,t)}function na(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 o=t(s);o.givenBackHeld=(o.givenBackHeld??0)+r}let n=i.links;if(n){let s=t(ie);s.deleted+=n.reinsert.count,s.broughtBack+=n.remove.count,s.givenBack+=n.share.count}return[...e.values()]}import{readFile as Ri,writeFile as Si}from"node:fs/promises";import{join as Zs}from"node:path";var Yt="DuplicateRecordItem",Ys=1e3,vi=["createdSince","broughtBackSince"],Xs="duplicate-record-sets.ids";function _e(i){return i.slice(0,15)}async function Zt(i,e,t){let n=Date.parse(t.takenAt),s=Date.parse(t.readAt);if(!Number.isFinite(n)||!Number.isFinite(s))return[];let r=(Math.floor(n/Ys)+1)*Ys;return An(i,{has:o=>e.has(o),start:r,end:s,madeFrom:r})}async function fa(i,e,t,n){let s=new Map;for(let o of e.objects){if(o.toDelete.createdSince+o.toDelete.broughtBackSince===0||!o.outside.some(({objectApiName:d})=>d===Yt))continue;let a=new N;for(let d of vi)if(o.toDelete[d]!==0)for await(let c of $e(ke(t,o.objectApiName,d)))typeof c.Id=="string"&&a.add(c.Id);a.size>0&&s.set(o.objectApiName,a)}if(s.size===0)return 0;let r=await Zt(i,{has:o=>[...s.values()].some(a=>a.has(o))},{takenAt:n,readAt:e.readAt});if(r.length===0)return 0;for(let o of e.objects){let a=s.get(o.objectApiName);if(!a)continue;let d=r.filter(p=>p.names.some(l=>a.has(l)));if(d.length===0)continue;let c=new Set(d.flatMap(p=>p.names.filter(l=>a.has(l))));o.outside=[...o.outside.filter(({objectApiName:p})=>p!==se),{objectApiName:se,count:d.length,parents:c.size}].sort((p,l)=>p.objectApiName<l.objectApiName?-1:1)}return await ye(t),await Si(Zs(t,Xs),r.map(o=>`${o.id}
|
|
12
|
+
`).join(""),{encoding:"utf8",mode:Pe}),r.length}function pa(i){return i.objects.reduce((e,t)=>e+t.outside.filter(({objectApiName:n})=>n===se).reduce((n,{count:s})=>n+s,0),0)}async function Qs(i){let e;try{e=await Ri(Zs(i,Xs),"utf8")}catch(t){if(t.code==="ENOENT")return new Set;throw t}return new Set(e.split(`
|
|
13
|
+
`).filter(t=>/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(t)).map(_e))}async function Rt(i,e){let t=new Map;for(let n of ge([...e])){let{records:s}=await i.query(`SELECT Id FROM ${se} WHERE Id IN (${n})`);for(let r of s)typeof r.Id=="string"&&t.set(_e(r.Id),{id:r.Id,items:0})}for(let n of ge([...t.values()].map(s=>s.id))){let{records:s}=await i.query(`SELECT DuplicateRecordSetId FROM ${Yt} WHERE DuplicateRecordSetId IN (${n})`);for(let r of s){let o=typeof r.DuplicateRecordSetId=="string"?t.get(_e(r.DuplicateRecordSetId)):void 0;o&&o.items++}}return[...t.values()]}async function er(i,e){let t=new Set,n=[];for(let s of ge([...e])){let{records:r}=await i.queryDeleted(`SELECT Id, DuplicateRecordSetId FROM ${Yt} WHERE DuplicateRecordSetId IN (${s}) AND IsDeleted = true`);for(let o of r)typeof o.Id=="string"&&(n.push(o.Id),typeof o.DuplicateRecordSetId=="string"&&t.add(_e(o.DuplicateRecordSetId)))}return{sets:t.size,items:n}}function tr(i,e){if(e.length===0)return i;let t=new Set(e.map(_e));return{objects:[{objectApiName:se,count:e.length},...i.objects],pages:n=>n===se?(async function*(){yield[...e]})():i.pages(n),has:n=>t.has(_e(n))||i.has(n)}}var nr=50,Ii=/Entity is not in the recycle bin/,Ai="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')",Pi=100;function fe(i){return i.slice(0,15)}var Oi=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ji(i,e){return{batches:async(t,n,s)=>{let r=await i.batches(t,n,s);return r?{async*[Symbol.asyncIterator](){for await(let o of r)yield o.map(a=>Object.fromEntries(Object.entries(a).filter(([d,c])=>d==="Id"||typeof c!="string"||!Oi.test(c)||!e.has(c))))}}:null}}}function Li(i){return{objects:[],cancelled:i,gone:[],stamps:{},left:async function*(){}}}function sr(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*rr(i,e,t,n=()=>!0){let s=[];for await(let r of i.pages(e,t))for(let o of r)n(fe(o))&&(s.push(o),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 ir(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 Bi(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?ir(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 Ei(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,sr(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 Xt(i,e,t,n){if(e.cancelled)return e;let s=new Set(e.left.map(fe)),r=new Set,o=[];for(let a of e.objects){let d=a.reasons.find(f=>Ii.test(f));if(d===void 0||a.refused===0){o.push(a);continue}let c=t.filter(({objectApiName:f})=>f===a.objectApiName).flatMap(f=>f.ids.filter(h=>s.has(fe(h)))),p=0;try{let f=de(a.objectApiName);for(let h of ge(c,V)){let m=await i.query(`SELECT Id FROM ${f} WHERE Id IN (${h})`);for(let g of m.records)typeof g.Id!="string"||r.has(fe(g.Id))||(r.add(fe(g.Id)),p++)}}catch(f){n.push(`Whether the ${a.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${ee(f)}): they are counted refused.`),o.push(a);continue}let l=Math.min(p,a.refused),u=a.refused-l;o.push({...a,refused:u,alreadyBack:a.alreadyBack+l,reasons:u===0?a.reasons.filter(f=>f!==d):a.reasons.map(f=>f===d?Ai:f)})}return{...e,objects:o,left:e.left.filter(a=>!r.has(fe(a)))}}async function Ci(i,e,t,n){let s=new Map(n.map(a=>[fe(a),a])),r=new Map,o=await i.batches(e,t,V);for await(let a of o??[])for(let d of a){if(typeof d.Id!="string")continue;let c=s.get(fe(d.Id));if(c===void 0)continue;let p=r.get(fe(c))??{id:c,values:{}};for(let[l,u]of Object.entries(d))l!=="Id"&&!(l in p.values)&&(p.values[l]=u);r.set(fe(c),p)}return r}async function Ti(i,e,t,n){let s=new N;for(let d of t.get(se)??[])s.add(d);let r=[];for await(let d of e.pages(se))for(let c of d)s.has(c)||r.push(c);if(r.length===0)return;let o,a;try{o=(await Rt(i,r)).filter(d=>d.items===0).map(d=>d.id),a=o.length>0?(await er(i,o)).items.length:0}catch(d){n.push(`Whether the ${se} records the undo brought back came back with their items could not be read (${ee(d)}).`);return}if(o.length!==0)return{objectApiName:se,count:o.length,ids:o.slice(0,nr),by:{},reason:"notBack",...a>0?{message:`${a} of their items`}:{}}}async function Di(i,e,t,n,s){let r=[],o=e.backup;for(let{objectApiName:a}of e.giveBack.objects){let d=de(a),c={objectApiName:a,count:0,ids:[],by:{}};try{for await(let p of rr(e.giveBack,a,Ne,l=>!n.has(l))){let l=await Ci(t,o,a,p);if(l.size===0)continue;let u=new Set;for(let{values:g}of l.values())for(let k of Object.keys(g))u.add(de(k));let f=["Id","LastModifiedById",...u],h=f.length>Pi?V/4:V,m=async g=>(await i.query(g)).records;for(let g of ge([...l.values()].map(k=>k.id),h)){let k=await st(`SELECT ${f.join(", ")} FROM ${d} WHERE Id IN (${g})`,m);for(let y of k){if(typeof y.Id!="string")continue;let v=l.get(fe(y.Id));if(!v||!Object.entries(v.values).some(([C,j])=>!Nn(j,y[C])))continue;c.count++,c.ids.length<nr&&c.ids.push(v.id);let I=typeof y.LastModifiedById=="string"?y.LastModifiedById:"unknown";c.by[I]=(c.by[I]??0)+1}}}}catch(p){s.push(`The ${a} records the undo gave back could not be read again (${ee(p)}): whether they all hold their values from before the rewind was not checked.`)}c.count>0&&r.push(c)}return r}async function Fi(i,e,t,n,s){let r=new Map(Object.entries(n).map(([a,d])=>[fe(a),Date.parse(d)])),o=new N;for(let{objectApiName:a}of e.objects){let d=de(a);for await(let c of e.pages(a))for(let p of ge(c,V)){if(s?.aborted)return o;let l;try{l=(await i.query(`SELECT Id, LastModifiedDate FROM ${d} WHERE Id IN (${p})`)).records}catch{continue}for(let u of l){if(typeof u.Id!="string")continue;let f=fe(u.Id),h=Date.parse(String(u.LastModifiedDate??""));(h<=t||h<=(r.get(f)??Number.NaN))&&o.add(u.Id)}}}return o}async function La(i){let e=await Hs(i.folder,i.rewindId,i.lock);try{let t=await e.facts(),n=await Vt(e.dir,t,i.objects);try{return await Mi(e,t,n,i)}finally{await n.dispose()}}finally{await e.close()}}async function Mi(i,e,t,n){let{org:s,signal:r}=n,o=t.goesWithParent,a=ji(i.values,t.compensated),d={remove:t.remove.spool.count+o.count,bringBack:t.bringBack.count,giveBack:t.giveBack.count},c=[],p={...e.rewind.removalStamps,...e.undo.removalStamps},l=Object.keys(p).length>0?p:void 0,u=[...e.rewind.removalSpans??[],...e.undo.removalSpans??[]],f=Bn(s),h,m=new N,g={},k=new Set(n.objects.filter(O=>O.customSetting!==void 0).map(O=>O.objectApiName)),y=O=>!k.has(O),v=Ni(t),w,I,C=new Map,j=await Ui(t.comesWithParent),B=new N,A=async O=>{for(let F of O)for await(let z of t.bringBack.pages(F)){let ae=(w?.cancelled??!1)||r?.aborted===!0;if(!ae&&j.size>0)for(let ue of z)j.has(ue)&&B.add(ue);let pe=ae?{objects:[{objectApiName:F,planned:z.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,notReached:z.length,reasons:[]}],left:[...z],wrote:!1,cancelled:!0,stamps:{}}:await ot({org:s,plan:[{objectApiName:F,ids:z}],undelete:n.undelete,...r?{signal:r}:{}});C.set(F,[...C.get(F)??[],...pe.left]),w=Bi(w,pe)}return!(w?.cancelled??!1)&&r?.aborted!==!0},x=async(O,F=y)=>{for(let{objectApiName:z}of t.giveBack.objects){if(!F(z))continue;let ae=de(z),pe={objectApiName:z,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]},ue={objects:[pe],left:[],wrote:!1,cancelled:!1,stamps:{}};for await(let je of rr(t.giveBack,z,Ne,O)){if(pe.planned+=je.length,(I?.cancelled??!1)||ue.cancelled||r?.aborted){ue.cancelled=!0,pe.notReached=(pe.notReached??0)+je.length,ue.left.push(...je);continue}if(h!==void 0){let Nr=je.filter(Br=>m.has(Br));Object.assign(g,await Cn(s,ae,Nr,h,f))}let cn={...p,...g},qe=await it({org:s,plan:[{objectApiName:z,backup:t.backup,ids:je}],backups:a,...e.lastWriteAt!==void 0?{lastWriteAt:e.lastWriteAt}:{},includeChanged:!1,...Object.keys(cn).length>0?{stamps:cn}:{},...r?{signal:r}:{}});sr(pe,qe.objects[0]),ue.left.push(...qe.left),ue.wrote||=qe.wrote,ue.cancelled||=qe.cancelled,Object.assign(ue.stamps,qe.stamps)}pe.planned>0&&(I=Ei(I,ue))}return!(I?.cancelled??!1)&&r?.aborted!==!0},_=async()=>{if(t.bringBack.count>0&&t.giveBack.count>0){let F=await En(s);h=Date.now()+F-Bt;let z=Date.parse(e.lastWriteAt??""),ae=Number.isFinite(z)?z+F+Bt:Number.NEGATIVE_INFINITY;m=await Fi(s,t.giveBack,ae,p,r)}return await A(v.bringFirst.filter(y))&&await x(v.held)&&await A(v.bringAfter.filter(y))&&(w&&(w=await Xt(s,w,[...C].map(([F,z])=>({objectApiName:F,ids:z})),c)),await x(F=>!v.held(F))),(w?.wrote??!1)||(I?.wrote??!1)},H,G=(O,F)=>{if(typeof O.Id!="string"||!o.keys.has(O.Id))return!1;if(H===void 0){let pe=new N;for(let ue of I?.left??[])pe.add(ue);H={stamps:new Map(Object.entries({...p,...g}).map(([ue,je])=>[fe(ue),Date.parse(je)])),notGiven:pe}}let z=Date.parse(String(O.LastModifiedDate??O.SystemModstamp??"")),ae=fe(O.Id);return z<=F||z<=(H.stamps.get(ae)??Number.NaN)?!0:t.giveBackKeys.has(ae)&&I!==void 0&&!H.notGiven.has(ae)},U=t.links,T={removed:we(),reinserted:we(),shared:we()};if(U&&U.remove.count>0&&!r?.aborted)for await(let O of U.remove.pages())ze(T.removed,await gt(s,O,{after:async({done:F})=>{F.length>0&&await i.linksUndone("removed",F.map(z=>z.Id))},stopped:()=>r?.aborted===!0}));let E;if(t.remove.spool.count>0?E=await rt(s,t.remove,{...n.splitting?{splitting:n.splitting}:{},runStartedAt:new Date(e.head.startedAt),...e.lastWriteAt!==void 0?{runRecordedAt:new Date(e.lastWriteAt)}:{},...l?{removalStamps:l}:{},...u.length>0?{removalSpans:u}:{},includeChanged:!1,...o.count>0?{goesWithParent:G,goesWithParentReadBelow:!0}:{},...t.bringBack.count>0||t.giveBack.count>0?{sweep:_}:{},...n.onUndeletable?{onUndeletable:n.onUndeletable}:{},...r?{signal:r}:{},...n.onProgress?{onProgress:n.onProgress}:{}}):(r?.aborted||await _(),E=Li(r?.aborted===!0&&!w&&!I)),k.size>0&&!E.stoppedForUndeletable&&(await x(()=>!0,O=>k.has(O)),await A([...v.bringFirst,...v.bringAfter].filter(O=>k.has(O)))),U&&!E.stoppedForUndeletable&&!r?.aborted){let O=s.create?.bind(s);for await(let F of U.reinsert.pages()){if(!O){T.reinserted.refused+=F.length,T.reinserted.reasons.push("The links the rewind removed could not be inserted again: this connection inserts no record.");continue}ze(T.reinserted,await mt({create:O},F,{after:async({made:z})=>{z.length>0&&await i.linksUndone("reinserted",z.map(ae=>ae.from))},stopped:()=>r?.aborted===!0}))}for await(let F of U.share.pages())ze(T.shared,await wt(s,F.map(z=>({...z,now:{ShareType:"",Visibility:""}})),{after:async({done:z})=>{z.length>0&&await i.linksUndone("shared",z.map(ae=>ae.Id))},stopped:()=>r?.aborted===!0}))}let b=U?{unlinked:T.removed.done,relinked:T.reinserted.done,linksUpdated:T.shared.done,linksRefused:T.removed.refused+T.reinserted.refused+T.shared.refused}:void 0;for(let O of[...T.removed.reasons,...T.reinserted.reasons,...T.shared.reasons])c.includes(O)||c.push(`A link between a file and a record: ${O}`);let M=new Date().toISOString();if(E.stoppedForUndeletable)return{rewindId:n.rewindId,status:"cancelled",deleted:[],restored:[],undeleted:[],residual:[],planned:d,notes:[],stoppedForUndeletable:!0,finishedAt:M};let D=[],re=new N,oe=new Map,$=new Map;for await(let{objectApiName:O,ids:F}of E.left())for(let z of F)re.add(z),D.push(z),t.remade.keys.has(z)&&oe.set(O,(oe.get(O)??0)+1),t.carriedAlone.keys.has(z)&&$.set(O,($.get(O)??0)+1);let R=t.remade.objects.map(({objectApiName:O,count:F})=>({objectApiName:O,count:F-(oe.get(O)??0)})).filter(({count:O})=>O>0),S=t.carriedAlone.objects.map(({objectApiName:O,count:F})=>({objectApiName:O,count:F-($.get(O)??0)})).filter(({count:O})=>O>0),L=[];for(let{objectApiName:O}of o.objects){let F=0;for await(let z of o.pages(O))for(let{id:ae,parent:pe}of z)re.has(pe)?D.push(ae):F++;F!==0&&L.push({objectApiName:O,planned:F,deleted:F,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})}let Z=[...L,...E.objects],he=await $i(t.comesWithParent,B,w),le=Tn(Dn(jn(Z,E.cancelled),Z,I),Z,I,w),Xe=[];if(I&&le!=="cancelled"){let O=new N;for(let F of I.left)O.add(F);Xe=await Di(s,t,a,O,c)}if(le!=="cancelled"){let O=await Ti(s,t.bringBack,C,c);O&&Xe.push(O)}Xe.length>0&&le==="success"&&(le="partial"),(b?.linksRefused??0)>0&&le==="success"&&(le="partial");let Or=t.remove.spool.count>0,jr=I?.objects.some(O=>O.restored+(O.restoredWithout??0)>0)===!0,dn={...g,...E.stamps},Lr={...Object.keys(dn).length>0?{removalStamps:dn}:{},...E.span?{removalSpans:[E.span]}:{},...Or?{removalLeft:D}:{},...I?{restoreLeft:I.left}:{},...jr?{restoredAt:M}:{},...w?{undeleteLeft:w.left}:{},...w&&!w.cancelled?{undeletedAt:M}:{}};try{await i.undone(Lr,le)}catch(O){c.push(`What this undo did could not be kept in the rewind\u2019s journal (${ee(O)}): an undo after it may set out to take back what it took back already.`)}return{rewindId:n.rewindId,status:le,deleted:Z,...R.length>0?{remade:R}:{},...S.length>0?{carriedAlone:S}:{},...L.length>0?{wentAlong:L.map(({objectApiName:O,deleted:F})=>({objectApiName:O,count:F}))}:{},...he.length>0?{cameBackAlong:he}:{},restored:I?.objects??[],undeleted:zi(w?.objects??[],he),...b?{files:b}:{},residual:Xe,planned:d,notes:c,finishedAt:M}}async function Ui(i){let e=new N;for(let{objectApiName:t}of i.objects)for await(let n of i.pages(t))for(let{parent:s}of n)e.add(s);return e}async function $i(i,e,t){if(t===void 0||e.size===0)return[];let n=new N;for(let r of t.left)n.add(r);let s=[];for(let{objectApiName:r}of i.objects){let o=0;for await(let a of i.pages(r))for(let{parent:d}of a)e.has(d)&&!n.has(d)&&o++;o>0&&s.push({objectApiName:r,count:o})}return s}function zi(i,e){let t=i.map(n=>({...n,reasons:[...n.reasons]}));for(let{objectApiName:n,count:s}of e){let r={objectApiName:n,planned:s,undeleted:s,alreadyBack:0,goneForGood:0,refused:0,reasons:[]},o=t.find(a=>a.objectApiName===n);o?ir(o,r):t.push(r)}return t}import{readFile as Wi,writeFile as _i}from"node:fs/promises";import{join as or}from"node:path";var ar="dependents-pointing.json",qi=un(X(),Qe().int().nonnegative()),Ma=V;async function Ua(i,e,t){if(e.length===0)return 0;let n=new Array(e.length).fill(!1);return(await lt(i,e.map(({childSObject:r,field:o})=>{let a=de(r);return{objectApiName:a,soql:`SELECT Id FROM ${a} WHERE ${de(o)} != null LIMIT 1`,scanAll:!1}}),(r,o)=>{o.length>0&&(n[r]=!0)},t,{oneRow:!0})).filter((r,o)=>!r.read||n[o]).length}async function $a(i,e){e.size!==0&&(await ye(i),await _i(or(i,ar),JSON.stringify(Object.fromEntries(e)),{encoding:"utf8",mode:Pe}))}async function dr(i){let e;try{e=JSON.parse(await Wi(or(i,ar),"utf8"))}catch{return new Map}let t=qi.safeParse(e);return t.success?new Map(Object.entries(t.data)):new Map}var fr=1e3,Ji=Hn*24*60*6e4,pr=50,kr=5,br=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],hr=[...br.filter(i=>i!=="carrier"),"goneForGood","convertedLead","activatedContract","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach"],Gi="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.",rn="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.",Ki={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:Gi,outOfReach:rn},St={createdSince:"removal",broughtBackSince:"removal",comesBackWithParent:"removal",giveBack:"restore",inBin:"undelete",withParent:"undelete",deletedWhileTaken:"undelete",toRecreate:"recreate",carrier:"undelete"},Qt={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.",contactKept:"Kept: the relation of a contact made since to its own account, which Salesforce deletes only with the contact, and the rewind left the contact.",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 en="It still differs from the checkpoint once the org was read again.",Ve=/Entity is not in the recycle bin/,Vi="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.",Ee="No record was written.",gr=4;function Yi(i,e,t){let n=e.some(a=>nt[a]!==void 0)?"as it is created or given its status back":"as it is created",s=[...new Set(t.fired.map(a=>`${a.objectApiName}: '${a.name}'`))],r=s.length-gr;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,gr).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 Zi="Account",Xi="Contact",Qi="001",eo="005",to=q({sobjects:me(q({name:X(),queryable:xe().optional()}).loose())}).loose(),no=/No such column 'IsDeleted'/;function tn(i){return i.toLowerCase()===ie.toLowerCase()}function so(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:o,errors:a}=r;return o===!0?!1:(Array.isArray(a)?a:[a]).some(d=>{let c=typeof d=="string"?d:typeof d=="object"&&d!==null?String(d.message??""):"";return Ve.test(c)})})}function ro(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 Od(i){let e=us(i),t=On(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:gn()}),destroy:(s,r)=>t.destroy(s,r),queryDeleted:s=>t.queryDeleted(s),...n?{bulkDestroy:(s,r,o)=>n(s,r,o)}:{}}}async function io(i,e,t){if(!i||!e)return e?{automation:e}:{};try{let n=await i(e,Lt(t));return{automation:n.automation??e,mute:n}}catch(n){if(!Et(n))throw n;let s=Mn(e,Lt(t));return{refusal:{code:"MUTE",message:`${n.message} ${Ee}`},automation:s.automation,plan:s.plan}}}async function oo(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(o){if(!s)throw o;let a=await s.release();throw n(a),Object.assign(o instanceof Error?o:new Error(String(o)),{mutedAutomation:a})}return s&&n(await s.release()),r}var Ye=class extends Error{constructor(){super("The rewind was stopped before it wrote anything to the org."),this.name="RewindStopped"}};function P(i){return i.slice(0,15)}function Be(i){let e=vn(i);return e===null?Number.NaN:Date.parse(e)}async function*ne(i){try{for await(let e of $e(i))yield e}catch(e){if(e.code!=="ENOENT")throw e}}async function mr(i,e){let t=[];for await(let n of ne(i)){let s=Se.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 ao(i){let e=[];for await(let t of ne(i)){let n=$t.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 co=q({sobjects:me(q({name:X(),keyPrefix:X().nullish()}).loose())}).loose();function lo(i){return{query:e=>i.query(e),queryMore:e=>i.queryMore(e)}}function uo(i,e){return{rewound:!1,refusal:{code:i,message:e}}}function wr(i,e){return{rewound:!1,refusal:i,...e.length>0?{alsoRefused:[...e]}:{}}}function fo(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 Rr=new Set(["noUndoNotAccepted","beforeParentNotAccepted"]),po={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 ho(i){return{code:"NO_UNDO",message:`${[...Rr].flatMap(t=>{let n=i.filter(o=>o.reason===t);if(n.length===0)return[];let s=n.reduce((o,a)=>o+a.count,0),r=[...new Set(n.map(o=>o.objectApiName))].join(", ");return[`Undo couldn't bring back ${s} ${r} record(s) this rewind deletes: ${po[t]??""}.`]}).join(" ")} Rewind refused; accept that Undo couldn't bring them back to rewind all the same. ${Ee}`}}function go(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. ${Ee}`}}function mo(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. ${Ee}`}}function wo(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 yo(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 ko(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. ${Ee}`}}var bo="accept that it runs to rewind all the same";function Ro(i,e,t,n){let s=jt(e,t),r=[...new Set(s.map(d=>d.objectApiName))],o=(t.recreate??[]).length>0?"makes them again, ":"",a=s.length>0?`${Is(s)} flow(s), trigger(s) or rule(s) of ${r.join(", ")} run as the rewind brings records back, ${o}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}: ${a}. ${xn("rewind",n)}Rewind refused; ${bo}. ${Ee}`}}function So(i,e){return{objectsRead:[...i],objects:[],unread:["flows","triggers","processes","workflowRules"].map(t=>({part:t,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function yr(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 Ae(i,e){i.length<kr&&!i.includes(e)&&i.push(e)}function vt(i,e,t){let n=t;for(let s of e){if(n<=0)return;let r=Number(i[s]??0),o=Math.min(r,n);i[s]=r-o,n-=o}}function At(i){return{objectApiName:i,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}function Sr(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)Ae(i.reasons,t)}function Pt(i){return{objectApiName:i,planned:0,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]}}function vr(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)Ae(i.reasons,t)}function Oe(i){return{objectApiName:i,planned:0,created:0,refused:0,reasons:[]}}function Ir(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)Ae(i.reasons,t)}function an(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)Ae(i.reasons,t);e.filesLeft&&(i.filesLeft={count:(i.filesLeft?.count??0)+e.filesLeft.count,names:[...i.filesLeft?.names??[],...e.filesLeft.names].slice(0,kr)})}var Ze=class{restored=new Map;undeleted=new Map;recreated=new Map;deleted=new Map;wentAlong=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:we(),relink:we(),share:we()};wrote=!1;cancelled=!1;leftBy(e,t,n){let s=this.left[e].get(t);s||(s=new N,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 N,this[e].set(t,s)),s.add(n)}cameBackGiven=new Map;cameBackRestored=0;restore(e,t){let n=this.restored.get(e.objectApiName)??At(e.objectApiName),s=t?.restored.length??0,r=t?.alreadyGone.length??0;if(Sr(n,{...e,planned:e.planned-s-r,restored:e.restored-s,alreadyGone:e.alreadyGone-r,reasons:e.reasons.map(yr)}),this.restored.set(e.objectApiName,n),s+r===0||!t)return;let o=this.cameBackGiven.get(e.objectApiName)??new N;for(let a of[...t.restored,...t.alreadyGone])o.add(a);this.cameBackGiven.set(e.objectApiName,o),this.cameBackRestored+=s}undelete(e){let t=this.undeleted.get(e.objectApiName)??Pt(e.objectApiName);vr(t,e),this.undeleted.set(e.objectApiName,t)}recreate(e){let t=this.recreated.get(e.objectApiName)??Oe(e.objectApiName);Ir(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(yr)};n?an(n,s):this.deleted.set(t.objectApiName,structuredClone(s))}}goneAlong(e){this.delete(e.map(({objectApiName:t,count:n})=>({objectApiName:t,planned:n,deleted:n,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})));for(let{objectApiName:t,count:n}of e)this.wentAlong.set(t,(this.wentAlong.get(t)??0)+n)}};async function vo(i,e){let t=[];for(let{objectApiName:n,file:s}of i){let r=0;for await(let o of ne(s))typeof o.parent=="string"&&!e(o.parent)&&r++;r>0&&t.push({objectApiName:n,count:r})}return t}async function Io(i){let e=new Map;for(let t of i)for(let{objectApiName:n}of t.objects){let s=e.get(n)??new N;for await(let r of t.pages(n))for(let o of r)s.add(o);e.set(n,s)}return e}async function It(i,e,t){let n=await Io(e),s=new Map,r=new Map;for(let o of i)for(let{objectApiName:a}of o.objects){let d=n.get(a);if(!d)continue;let c=s.get(a)??new N;s.set(a,c);let p=t?.get(a);for await(let l of o.pages(a))for(let u of l)d.has(u)&&p?.has(u)!==!0&&c.add(u)&&r.set(a,(r.get(a)??0)+1)}return r}async function Ao(i,e){let t=i.tally,n=new Map([...t.deleted].map(([d,c])=>[d,structuredClone(c)])),s=new Map([...t.restored].map(([d,c])=>[d,structuredClone(c)])),r=new Map([...t.undeleted].map(([d,c])=>[d,structuredClone(c)])),o=new Map([...t.recreated].map(([d,c])=>[d,structuredClone(c)]));if(e){let{tally:d,plan:c}=e,p=await It([c.giveBack.beforeDeletes,c.giveBack.afterDeletes],[i.plan.giveBack.beforeDeletes,i.plan.giveBack.afterDeletes],t.cameBackGiven);for(let[h,m]of d.restored){let g=s.get(h)??At(h),k=p.get(h)??0;vt(g,["refused","notReached","notKept","keptChanged","restoredWithout","alreadyGone","restored"],k),g.planned-=Math.min(k,g.planned),Sr(g,m),s.set(h,g)}let l=await It([c.bringBack],[i.plan.bringBack]);for(let[h,m]of d.undeleted){let g=r.get(h)??Pt(h),k=l.get(h)??0;vt(g,["refused","notReached","goneForGood","alreadyBack","undeleted"],k),g.planned-=Math.min(k,g.planned),vr(g,m),r.set(h,g)}let u=await It([c.recreate],[i.plan.recreate]);for(let[h,m]of d.recreated){let g=o.get(h)??Oe(h),k=u.get(h)??0;vt(g,["refused","notReached","created"],k),g.planned-=Math.min(k,g.planned),Ir(g,m),o.set(h,g)}let f=await It([c.deletes.spool],[i.plan.deletes.spool]);for(let[h,m]of d.deleted){let g=n.get(h);if(!g){n.set(h,structuredClone(m));continue}let k=f.get(h)??0;vt(g,["refused","keptDependents","keptChanged","notVisible","alreadyGone","deleted"],k),g.planned-=Math.min(k,g.planned),an(g,m)}}for(let[d,{reason:c}]of[...t.heldInPlace,...e?.tally.heldInPlace??[]]){let p=s.get(d);p&&Ae(p.reasons,c)}let a=new Map(t.wentAlong);for(let[d,c]of e?.tally.wentAlong??[])a.set(d,(a.get(d)??0)+c);return{deleted:[...n.values()],restored:[...s.values()],undeleted:[...r.values()],recreated:[...o.values()],wentAlong:[...a].map(([d,c])=>({objectApiName:d,count:c}))}}function Po(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 Oo(i){let e=i.objects,t=e.filter(n=>n.deleted+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+Wn(n)>0).map(n=>n.objectApiName),setToDraft:e.filter(n=>zn(n)>0).map(n=>n.objectApiName),delete:t}}function jo(i){let e=Oo(i),{unlink:t,relink:n,share:s,unlinkFrom:r}=i.links,o=(a,d)=>d?[...a??[],ie]:[...a??[]];return{...e,delete:o(e.delete,t.count+r.count>0),recreate:o(e.recreate,n.count>0),giveBack:o(e.giveBack,s.count>0)}}function Ar(i){let{unlink:e,relink:t,share:n,unlinkFrom:s}=i.links;return e.count+t.count+n.count+s.count}function jd(i){return i.reduce((e,{objectApiName:t,records:n})=>e+fs(t,{rows:n}),0)/1048576}function Lo(i,e){let t=new Set(e.filter(o=>!o.undeletable).map(o=>o.objectApiName)),n=new Set(i.did.broughtBack.flatMap(({ids:o})=>o.map(P))),s=new Set((i.did.deletedBeforeParent??[]).flatMap(({ids:o})=>o.map(P))),r=[];for(let{objectApiName:o,ids:a}of i.did.deleted){let d=a.map(P).filter(l=>!n.has(l)),c=d.filter(l=>s.has(l)).length,p=t.has(o)?d.length-c:0;p>0&&r.push({objectApiName:o,count:p}),c>0&&r.push({objectApiName:o,count:c,reason:"deletedBeforeParent"})}return r}var No=new Set(["outsideNotAccepted","holdsLeft","contactKept"]);function Bo(i){let e=new Map;for(let{objectApiName:t,reason:n,count:s}of i.left)No.has(n)&&e.set(t,(e.get(t)??0)+s);return[...e].map(([t,n])=>({objectApiName:t,count:n}))}function nn(i){return i.deletes.spool.count+i.bringBack.count+i.recreate.count+i.giveBack.beforeDeletes.count+i.giveBack.afterDeletes.count+Ar(i)>0}function Eo(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,o)=>n(()=>i.query(r,o)),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,o)=>n(()=>i.update(r,o)),create:(r,o)=>n(()=>i.create(r,o)),destroy:(r,o)=>n(()=>i.destroy(r,o)),queryDeleted:r=>n(()=>i.queryDeleted(r)),...s?{bulkDestroy:async(r,o,a)=>{let d=1;try{let c=await s(r,o,a);return d=c.requests??1,c}finally{t+=d}}}:{}},undelete:r=>n(()=>e(r)),used:()=>t,add:r=>{t+=r}}}async function Ld(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=Eo(i.org,i.undelete),r,o=await ls(lo(s.org),{act:"rewind",orgName:n,registered:e.registered,username:e.username,organizationId:t.org.organizationId,customSettings:Rn(t)},{userId:async()=>r=await s.org.userId()});if(!o.allowed)return{rewound:!1,refusal:o.refusal};let a=i.store.lock(t.org.organizationId,"rewind",t.checkpointId);if("busy"in a)return{rewound:!1,refusal:fo(n,a.busy)};let d=new on(i,e,s,a.lock,o.queryAllFiles,{grants:o.grants,...r!==void 0?{userId:r}:{}});try{let c=await i.runWriting?.(o.org.id);return c!==void 0?uo("RUN_WRITING",c):await d.go()}finally{await d.cleanUp(),a.lock.release()}}var on=class{constructor(e,t,n,s,r,o){this.deps=e;this.request=t;this.count=n;this.lock=s;this.queryAllFiles=r;this.user=o;this.org=this.clock.watched(n.org),this.signal=e.signal,this.now=e.now??(()=>new Date),this.kept=Po(Tt(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=Nt();stamps={};stampOf=new Map;spans=[];userId="";owners=new Set;carried=new N;comesBack=new N;before=Number.NaN;confirmedSets=new Set;setsRefused=new Set;clock=new Ps(()=>this.now().getTime());access=ms;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=Ge("pv",this.now()),n=Le(this.request.folder,t);return this.ownDirs.push(n),{diff:await ks({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 Rs({checkpoint:this.request.checkpoint,pass:e,confirmedDir:t,freshDir:n.dir,readAt:s,ownWriters:ft(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 Fe.read(this.request.folder)}:{},...this.picked!==void 0?{objects:this.picked,heldRows:vs(this.request.checkpoint,this.request.folder)}:{},dir:ur(n.dir,`plan${e}-${cr(4).toString("hex")}`),...this.signal?{signal:this.signal}:{}}),o=new Map;for(let{objectApiName:a}of this.request.checkpoint.objects){let d=new N;for(let c of br){let p=c==="inBin"||c==="withParent";for await(let l of ne(ke(r.dir,a,c)))typeof l.Id=="string"&&(d.add(l.Id),p&&this.comesBack.add(l.Id))}d.size>0&&o.set(a,d)}return{plan:r,acted:o}}async relationships(){let e=this.global,t=e?new Set((await Sn({describeGlobal:()=>e})).keys()):void 0,n=new Set(this.request.checkpoint.objects.map(({objectApiName:o})=>o.toLowerCase()));if(this.request.checkpoint.files!==void 0)for(let o of[ie,bn])n.add(o.toLowerCase());let s=await dr(Le(this.request.folder,this.request.previewId)),r=new Map;for(let[o,a]of this.kept.bodies){let d=Xn(a,{inCheckpoint:n,...t?{worked:t}:{}}),c=s.get(o);r.set(o,c!==void 0?{...d,pointing:c}:d)}return r}async go(){let{checkpoint:e,orgName:t,folder:n}=this.request,s=await es(this.org,t);if(this.stopped())throw new Ye;this.progress("reading",1,5,`Reading ${t} again`);let r=this.request.reusesPreview,o,a,d;try{this.access=await ws({grants:this.user.grants,...this.user.userId!==void 0?{userId:this.user.userId}:{},username:this.request.username,checkpoint:e,reader:this.kept.reader});let $=r?yo(r,this.access):[];if($.length>0)return{rewound:!1,refusal:ko(t,$)};if(o=r?r.readAt:await this.org.serverTime(),this.before=Date.parse(o)-fr,!Number.isFinite(this.before))throw new Error(`Not a date: ${o}`);a=r?{diff:r,dir:Le(n,this.request.previewId)}:await this.diff(o),d=await this.plan(1,Le(n,this.request.previewId),a,o),this.confirmedSets=e.scope.mode==="picked"&&!this.request.acceptOutside?new Set:await Qs(Le(n,this.request.previewId))}catch($){throw $ instanceof Je||this.stopped()?new Ye:$}let c=[],p=d.plan.left.filter($=>Rr.has($.reason));p.length>0&&c.push(ho(p));let l=d.plan.left.filter($=>$.reason==="recreateNotAccepted");l.length>0&&c.push(go(l));let u=wo(a.diff,d.plan);u.length>0&&!this.request.acceptUnseen&&c.push(mo(this.request.username,u));let f=ns("rewind",await this.bringBackFiles(d.plan,a.dir),s.fileStorage?.remaining,t);f&&c.push(f);let h=e.lastRewind,m=h!==void 0&&h.endedAt===void 0&&h.undoneAt===void 0,g=nn(d.plan);if(!g){let[$,...R]=c;if($)return wr($,R);if(!m)return this.wroteNothing(a,d,s.remaining)}let k=jo(d.plan),y;if(g&&this.deps.readAutomation){let $=[...new Set([...k.bringBack??[],...k.recreate??[],...k.giveBack??[],...k.setToDraft??[],...k.delete??[]])];try{y=await this.deps.readAutomation($)}catch(R){y=So($,ee(R))}this.count.add(y.requests)}let v=y,w=g?await io(this.deps.mute,y,k):{},I="refusal"in w?w:void 0,C="refusal"in w?void 0:w.mute;I&&c.push(I.refusal),w.automation&&(y=w.automation);let j=I?I.plan:C?.plan,B=this.request.acceptEmails===!0,A=g&&v?await Gn({act:"rewind",orgName:t,automation:v,steps:k,...j?{plan:j}:{},accepted:B,mayMute:this.deps.mute===void 0&&this.request.canMute===!0,read:()=>Fn(this.org)}):void 0,x=Ss(a.diff,this.picked),_=this.unpickedWrites(a.diff,d.plan),H=Qn({objects:e.objects,..._.length>0?{unpicked:_.map(({objectApiName:$})=>$)}:{},diff:{...x,objects:[...x.objects,..._],withParentDeleted:d.plan.objects.flatMap(({objectApiName:$,withParentDeleted:R})=>R>0?[{objectApiName:$,count:R}]:[])},...this.picked!==void 0?{readDiff:a.diff}:{},automationRequests:0,relationships:await this.relationships(),...this.confirmedSets.size>0?{duplicateSets:this.confirmedSets.size}:{},...r?{reusesPreview:!0}:{},kept:Bo(d.plan)}),G=ps(A?.ofRun),U=ts("rewind",{run:this.count.used()-(G.deliverability??0)+H.apiRequests,...G,...$n(j)},s,t);g&&U&&c.push(U),this.splitting=Nt(In(s.remaining,this.count.used()+H.apiRequests+Un(j)));let T=_n(d.plan.objects),E=y?Jn("rewind",at(T,y,s.emails),t):void 0;g&&E&&c.push(E);let b=y?qn(T,y):void 0;y&&!this.request.acceptAutomation&&(jt(y,k).length>0||wn(y.unread)||b!==void 0)&&c.push(Ro(t,y,k,b)),g&&A?.refusal&&c.push(A.refusal);let[M,...D]=c;if(M)return wr(M,D);if(y&&(this.asked={automation:y,steps:k,accepted:this.request.acceptAutomation},this.emailsCounted={written:[...T],limits:s.emails}),this.stopped())throw new Ye;this.userId=await this.org.userId(),this.owners=new Set(ft(e.takenBy,this.userId).map(P)),this.deps.onWriting?.(d.plan.objects.flatMap(({objectApiName:$,broughtBack:R,backWithParent:S,carriers:L,recreated:Z})=>{let he=R+S+(L??0)+Z;return he>0?[{objectApiName:$,records:he}]:[]}));let re=await Ks({folder:n,lock:this.lock,startedAt:o,userId:this.userId,...e.takenBy.automatedProcessUserId!==void 0?{automatedProcessUserId:e.takenBy.automatedProcessUserId}:{},now:this.now}),oe;try{let $=await oo(C,`rewind ${e.checkpointId} ${o}`,S=>{let L=S&&j&&v&&A?Kn({act:"rewind",orgName:t,automation:v,steps:k,plan:j,held:S.outcome,planned:A.ofRun.senders,...A.ofRun.read?{reading:A.ofRun.read.reading}:{},accepted:B}):void 0;return L?Promise.resolve({rewound:!1,refusal:L}):this.passes(re,o,a,d,s.remaining)},S=>{oe=S}).catch(S=>{if(Et(S))return{rewound:!1,refusal:{code:"MUTE",message:`${S.message} ${Ee}`}};throw S}),R=A?.gate.audit;return $.rewound?{...$,...oe?{result:{...$.result,mutedAutomation:oe}}:{},...R!==void 0?{deliverability:R}:{}}:$}finally{await re.close()}}async wroteNothing(e,t,n){let s=await this.residualOf(e,e,[t],new Ze),r=this.pickedOnly(e.diff.unread),o=await this.scopeOf(e,e),a=await this.setsLeft();return this.ended=!0,{rewound:!0,result:this.resultOf({rewindId:Ge("rw",this.now()),status:s.some(d=>d.reason==="changedDuringRewind")?"unstable":s.length>0||r.length>0?"partial":"success",tally:{deleted:a?[a]:[],restored:[],undeleted:[],recreated:[],wentAlong:[]},residual:s,unread:r,passes:1,leftToday:n,...o?{scope:o}:{}}),notes:this.notes}}async passes(e,t,n,s,r){let{checkpoint:o}=this.request,a=await e.read();this.addStamps(a.rewind.removalStamps??{}),this.spans.push(...a.rewind.removalSpans??[]);for(let{ids:b}of a.did.carried??[])for(let M of b)this.carried.add(M);let d=new Date(Date.parse(a.head.startedAt)+Ji).toISOString(),c;await this.deps.store.update(o.checkpointId,b=>(b.lastRewind?.rewindId!==e.rewindId&&(c=b.lastRewind),{...b,lastRewind:{rewindId:e.rewindId,undoUntil:d}}));let p=nn(s.plan),l=p?await this.pass(e,s.plan,n.diff,1):new Ze,u=[s],f,h,m=l.cancelled;try{if(!m&&l.wrote){this.progress("reading",2,70,`Reading ${this.request.orgName} again`);let b=await this.diff(await this.org.serverTime()),M=await this.plan(2,s.plan.dir,b,t);if(u.push(M),h=b,nn(M.plan)){let D=await this.pass(e,M.plan,b.diff,2);f={tally:D,plan:M.plan},m=D.cancelled,!m&&D.wrote&&(this.progress("checking",2,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime()))}}else!m&&p?(this.progress("checking",1,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime())):m||(h=n)}catch(b){if(!(b instanceof Je)&&!this.stopped())throw b;m=!0}this.stopped()&&(m=!0);let g=await Ao({tally:l,plan:s.plan},f),k=m?void 0:await this.setsLeft();if(k){let b=g.deleted.find(M=>M.objectApiName===se);b?an(b,k):g.deleted.push(k)}let y=!m&&h?await this.residualOf(h,n,u,l,f?.tally):[],v=!m&&h?this.pickedOnly(h.diff.unread):[],w=await this.scopeOf(m?void 0:h,n),I=g.deleted.some(b=>b.deleted>0)||g.restored.some(b=>b.restored+(b.restoredWithout??0)>0)||g.undeleted.some(b=>b.undeleted>0)||g.recreated.some(b=>b.created>0)||l.cameBackRestored+(f?.tally.cameBackRestored??0)>0,C=m?"cancelled":y.some(b=>b.reason==="changedDuringRewind")?"unstable":y.length>0||v.length>0?I?"partial":"failure":"success",j=this.filesOf(y,[l,...f?[f.tally]:[]]),B=(j?.unlinked??0)+(j?.relinked??0)+(j?.linksUpdated??0),A=I||B>0||(m||e.resumed)&&(await e.facts()).lastWriteAt!==void 0,x=[];if(m&&!A)try{await this.deps.store.update(o.checkpointId,b=>(delete b.lastRewind,c?{...b,lastRewind:c}:b))}catch(b){this.notes.push(`The checkpoint could not be told the rewind stopped before it wrote anything (${ee(b)}): its list may not offer to undo the rewind before it.`)}if(!m){await e.end(),this.ended=!0;let b=h?.diff.readAt??this.now().toISOString(),M=A?{rewindId:e.rewindId,endedAt:b,undoUntil:d}:c;try{await this.deps.store.update(o.checkpointId,D=>(delete D.lastRewind,M?{...D,lastRewind:M}:D))}catch(D){this.notes.push(A?`The checkpoint could not be told when the rewind ended (${ee(D)}): its list may not offer to undo it.`:`The checkpoint could not be told the rewind wrote nothing (${ee(D)}): its list may not offer to undo the rewind before it.`)}try{A&&(x=await Vs(this.deps.store,this.lock,{checkpointId:o.checkpointId,rewindId:e.rewindId}))}catch(D){this.notes.push(`The journals of the earlier rewinds of ${this.request.orgName} could not be deleted (${ee(D)}): they stay until their checkpoint goes.`)}}let _=await e.read(),H=this.undoCannotOf(_),G=(_.did.carriers??[]).map(({objectApiName:b,ids:M})=>({objectApiName:b,count:M.length}));if(m){let b=new Set(_.did.deleted.flatMap(({ids:D})=>D.map(P))),M=(_.did.carriers??[]).map(({objectApiName:D,ids:re})=>({objectApiName:D,count:re.filter(oe=>!b.has(P(oe))).length})).filter(({count:D})=>D>0);M.length>0&&this.notes.push(`Stopped with ${M.map(({objectApiName:D,count:re})=>`${re} ${D}`).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 U=new Map;for(let b of[l,...f?[f.tally]:[]])for(let[M,D]of b.draftsLeft)U.set(M,[...U.get(M)??[],...D]);let T=[...U].map(([b,M])=>({objectApiName:b,count:M.length,ids:M.slice(0,pr)})),E={rewound:!0,result:this.resultOf({rewindId:e.rewindId,status:C,tally:g,residual:y,unread:v,passes:f?2:1,leftToday:r,...A?{undo:{until:d,cannot:H}}:{},removedJournals:x,carriers:G,draftsLeft:T,...j?{files:j}:{},...w?{scope:w}:{}}),notes:this.notes};if(I||_.lastWriteAt!==void 0&&(m||e.resumed)){let b=await Os({folder:this.request.folder,lock:this.lock,checkpoint:o,result:E.result,startedAt:t,...!m&&h?{endedAt:h.diff.readAt}:{},clock:this.clock});b!==void 0&&this.notes.push(b)}if(!A){await e.close();try{await lr(De(this.request.folder,e.rewindId),{recursive:!0,force:!0})}catch(b){this.notes.push(`The journal of this rewind, which wrote nothing, could not be deleted (${ee(b)}): it stays until a later rewind that writes ends, or its checkpoint goes.`)}}return E}filesOf(e,t){if(this.request.checkpoint.files===void 0)return;let n=r=>t.reduce((o,a)=>o+a.links[r].done,0),s={unlinked:n("unlink"),relinked:n("relink"),linksUpdated:n("share"),linksRefused:e.filter(r=>r.objectApiName===ie&&r.reason==="refused").reduce((r,o)=>r+o.count,0)};return s.unlinked+s.relinked+s.linksUpdated+s.linksRefused>0?s:void 0}async bringBackFiles(e,t){let n=new N;for await(let r of e.bringBack.pages(Te))for(let o of r)n.add(o);if(n.size===0)return{files:0,bytes:0};let s=new Map;for await(let r of ne(ut(t,Te)))typeof r.Id=="string"&&typeof r.ContentSize=="number"&&n.has(r.Id)&&s.set(P(r.Id),r.ContentSize);if(s.size<n.size&&this.request.checkpoint.files!==void 0)for await(let r of cs(this.request.folder))n.has(r.Id)&&!s.has(P(r.Id))&&r.ContentSize!==null&&s.set(P(r.Id),r.ContentSize);return{files:n.size,bytes:[...s.values()].reduce((r,o)=>r+o,0)}}undoCannotOf(e){return Lo(e,this.request.checkpoint.objects)}resultOf(e){let t=this.count.used();return{checkpointId:this.request.checkpoint.checkpointId,rewindId:e.rewindId,status:e.status,deleted:e.tally.deleted,...e.tally.wentAlong.length>0?{wentAlong:e.tally.wentAlong}:{},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)),o=[],a=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 N;for await(let u of ne(ke(t.dir,c,"goneForGood")))typeof u.Id=="string"&&p.add(u.Id);let l=new N;for(let u of hr)for await(let f of ne(ke(e.dir,c,u)))typeof f.Id!="string"||p.has(f.Id)||l.add(f.Id);l.size>0&&(o.push(c),a+=l.size)}if(s.files!==void 0&&!n.has(Te)){let c=new N;for(let p of["linkAdded","linkRemoved","linkChanged"])for await(let l of ne(Ut(e.dir,p)))typeof l.Id=="string"&&c.add(l.Id);c.size>0&&(o.push(ie),a+=c.size)}}return{objects:r,notRewound:{objects:o,records:a}}}async readLeftFields(e){let t=e.limited?.leftFields;if(!(t===void 0||t.count===0))for await(let n of ne(t.file)){if(typeof n.Id!="string"||!Array.isArray(n.fields))continue;let s=this.leftFields.get(P(n.Id))??new Set;for(let r of n.fields)typeof r=="string"&&s.add(r.toLowerCase());this.leftFields.set(P(n.Id),s)}}async cleanUp(){let e=[...this.ownDirs];this.ended&&e.push(Le(this.request.folder,this.request.previewId));for(let t of e)await lr(t,{recursive:!0,force:!0}).catch(()=>{})}async pass(e,t,n,s){let r=new Ze;await this.readLeftFields(t);let o={},a=f=>{Object.assign(o,f),this.addStamps(f)},d=this.allowLists(n),c=new N;for(let{objectApiName:f}of t.giveBack.afterDeletes.objects){let h=t.giveBack.heldBy.find(m=>m.objectApiName===f)?.by;for await(let m of t.giveBack.afterDeletes.pages(f)){for(let g of m)c.add(g);h&&await e.heldInPlace(f,h,m)}}await this.keepFirst(e,t.giveBack.afterDeletes,d);let p=this.request.acceptRecreate?new Me(ur(t.dir,`remake-${cr(4).toString("hex")}`)):void 0,l=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,a,p));let f=p&&p.objects.length>0?await this.withPlanned(p,t.recreate):t.recreate;if(!r.cancelled&&!this.stopped()&&f.count>0)this.progress("recreating",s,s===1?32:81,"Making again what the recycle bin no longer holds"),await this.recreate(e,f,r);else if(f.count>0){for(let{objectApiName:h,count:m}of f.objects)r.recreate({...Oe(h),planned:m,notReached:m});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,a)),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:y,file:v}of t.beforeParent){let w=[];for await(let I of ne(v)){let C=Array.isArray(I.parents)?I.parents:[];for(let j of C)typeof I.Id=="string"&&typeof j=="string"&&w.push({id:I.Id,parent:j});w.length>=J&&await e.beforeParent(y,w.splice(0))}w.length>0&&await e.beforeParent(y,w)}let f=await this.withSets(t);await e.deleting(f);for(let{objectApiName:y,file:v}of t.along){let w=[];for await(let I of ne(v))typeof I.Id=="string"&&typeof I.parent=="string"&&w.push({id:I.Id,parent:I.parent}),w.length>=J&&await e.goingAlong(y,w.splice(0));w.length>0&&await e.goingAlong(y,w)}let h={...this.stamps,...t.removal.removalStamps},m=[...this.spans,...t.removal.removalSpans??[]].filter((y,v,w)=>w.findIndex(I=>JSON.stringify(I)===JSON.stringify(y))===v),g=(y,v)=>{if(typeof y.Id!="string"||!this.carried.has(y.Id)&&!t.goesAlong.has(y.Id))return!1;let w=Be(y.LastModifiedDate??y.SystemModstamp);return w<=v||w<=(this.stampOf.get(P(y.Id))??Number.NaN)};u=await rt(this.org,f,{splitting:this.splitting,runStartedAt:t.removal.runStartedAt,runEndedAt:t.removal.runEndedAt,includeChanged:t.removal.includeChanged,alongAccepted:!0,...Object.keys(h).length>0?{removalStamps:h}:{},...m.length>0?{removalSpans:m}:{},...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:l}:{},...this.deps.onUndeletable?{onUndeletable:this.deps.onUndeletable}:{},...this.signal?{signal:this.signal}:{},onProgress:(y,v,w)=>this.progress("deleting",s,s===1?55:85,`Deleting ${w}: ${y} / ${v}`)}),await e.deleted(u);for await(let{objectApiName:y,ids:v}of u.left())r.leftBy("removal",y,v);let k=[...r.left.removal.values()];r.goneAlong(await vo(t.along,y=>k.some(v=>v.has(y)))),r.delete(u.objects),u.cancelled&&(r.cancelled=!0),(u.objects.some(y=>y.deleted>0)||u.span)&&(r.wrote=!0),a(u.stamps),u.span&&this.spans.push(u.span)}else this.stopped()?r.cancelled=!0:await l();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,a)),!r.cancelled&&!this.stopped()&&Ar(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:o,removalSpans:u?.span?[u.span]:[]}),r}async withSets(e){let t=e.deletes;if(this.confirmedSets.size===0)return t;let n=(await Zt(this.org,{has:o=>t.has(o)||e.goesAlong.has(o)},{takenAt:this.request.checkpoint.takenAt,readAt:new Date(this.before+fr).toISOString()})).filter(o=>this.confirmedSets.has(P(o.id)));if(n.length===0)return t;let s=new Set(n.map(o=>P(o.id)));this.confirmedSets=new Set([...this.confirmedSets].filter(o=>!s.has(o)));let r;try{r=(await this.org.describe(se))?.deletable!==!1}catch{r=!1}if(!r){for(let o of s)this.setsRefused.add(o);return t}return tr(t,n.map(o=>o.id))}async setsLeft(){let e=[...new Set([...this.confirmedSets,...this.setsRefused])];if(e.length===0)return;let t;try{t=await Rt(this.org,e)}catch(o){this.notes.push(`Whether the ${se} records its preview named are still in ${this.request.orgName} could not be read (${ee(o)}).`);return}if(t.length===0)return;let n=t.filter(o=>this.setsRefused.has(P(o.id))).length,s=t.filter(o=>!this.setsRefused.has(P(o.id))&&o.items>=2).length,r=t.length-n-s;return{objectApiName:se,planned:t.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:s+r,refused:n,heldBy:[],unchecked:[],reasons:[...n>0?[`${this.request.username} may not delete ${se} records`]:[],...s>0?["they still report records alike that this rewind keeps"]:[],...r>0?[`they report nothing any more, and no rewind takes an empty set: delete them in ${this.request.orgName}, from the Duplicate Record Sets tab`]:[]]}}async writeLinks(e,t,n){let s=()=>this.stopped(),r=async d=>{d!==0&&(n.wrote=!0,await e.wrote())},o=await mr(t.links.unlink.file,"linkAdded"),a=new Set(o.map(d=>P(d.Id)));for(let d of await this.heldLinksOf(t.links.unlinkFrom,t))a.has(P(d.Id))||o.push(d);if(n.links.unlink=await gt(this.org,o,{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 Fe.read(this.request.folder);n.links.relink=await mt(this.org,await mr(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(P(c))??c),n.links.relink.cancelled&&(n.cancelled=!0)}if(!n.cancelled&&t.links.share.count>0){let d=await ao(t.links.share.file),c=new Map(d.map(p=>[P(p.Id),p.now]));n.links.share=await wt(this.org,d,{before:p=>e.linksUpdating(p.map(l=>({...l,...c.get(P(l.Id))??{}}))),after:async({done:p,left:l})=>{l.length>0&&await e.linksUpdateLeft(l),await r(p.length)},stopped:s}),n.links.share.cancelled&&(n.cancelled=!0)}}async heldLinksOf(e,t){if(e.count===0)return[];let n=co.safeParse(await this.describeGlobal()),s=as(n.success?n.data.sobjects:[],this.request.checkpoint.objects.map(({objectApiName:o})=>o)),r=[];for await(let o of e.pages(Te,Mt))for(let a of ge(o,Mt)){let d=await this.org.query(`SELECT ${os.join(", ")} FROM ${ie} WHERE ContentDocumentId IN (${a})`);for(;;){for(let c of d.records){let p=Se.safeParse(c);!p.success||ds(p.data,s)===void 0||t.deletes.has(P(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),o=t.get(s);return Ft(s,r?.fields??[],this.request.checkpoint.ignoredFields).filter(a=>!o?.has(a.toLowerCase()))}}async keepFirst(e,t,n){for(let{objectApiName:s}of t.objects){let r=n(s);if(r.length===0)continue;let o=de(s),d=this.request.checkpoint.objects.find(l=>l.objectApiName===s)?.fields.some(l=>l===Ue)===!0,c=["Id",...r.map(de),...d?[Ue]:[]],p=async l=>(await this.org.query(l)).records;try{for await(let l of t.pages(s))for(let u of ge(l,V)){if(this.stopped())return;let h=(await st(`SELECT ${c.join(", ")} FROM ${o} WHERE Id IN (${u})`,p)).map(m=>ct(s,m,r));h.length>0&&await e.keep(s,h)}}catch(l){if(l instanceof Je)return;this.notes.push(`What the ${s} records given back after the deletions held could not be kept before the rewind wrote (${ee(l)}): 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 a=await this.kept.reader.describe(e);t="body"in a?a.body:void 0}let n=Dt.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=e===Zi&&n.data.fields.some(a=>a.name===Ue),r=(n.data.childRelationships??[]).filter(a=>a.cascadeDelete===!0);if(r.length===0)return[];let o=await this.unqueriedObjects();return r.filter(a=>!o.has(a.childSObject)).map(a=>({child:a.childSObject,field:a.field,...s&&a.childSObject===Xi&&a.field==="AccountId"?{persons:!0}:{}}))}unqueriedObjects(){return this.unqueried??=this.describeGlobal().then(e=>{let t=to.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=Dt.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),o=Ft(e,r?.fields??[],this.request.checkpoint.ignoredFields).filter(d=>s.get(d.toLowerCase())?.createable===!0),a=o.filter(d=>s.get(d.toLowerCase())?.type==="reference");return{fields:o.map(de),lookups:a}}async withPlanned(e,t){for(let{objectApiName:s}of t.objects)for await(let r of t.pages(s))for(let o of r)await e.add(s,o);let n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s.readOrder]));return e.finish(s=>[...s].sort((r,o)=>(n.get(o.objectApiName)??0)-(n.get(r.objectApiName)??0)))}async recreate(e,t,n){let{checkpoint:s,folder:r}=this.request,o=new N;for(let{objectApiName:u}of t.objects)for await(let f of t.pages(u))for(let h of f)o.add(h);let a=await Fe.read(r),d=new Set,c=u=>a.originalOf(u.slice(0,15))??u.slice(0,15),p=[],l=new Map;for(let{objectApiName:u,count:f}of t.objects){if(n.cancelled||this.stopped()){n.recreate({...Oe(u),planned:f,notReached:f}),n.cancelled=!0;continue}let h;try{h=await this.insertFieldsOf(u)}catch(k){if(k instanceof Je){n.cancelled=!0,n.recreate({...Oe(u),planned:f,notReached:f});continue}let y=ee(k);n.recreate({...Oe(u),planned:f,refused:f,reasons:[y]});for await(let v of t.pages(u))n.leftBy("recreate",u,v);continue}let m=h.fields.find(k=>k.toLowerCase()==="status"),g=m!==void 0?await this.lifecycleOf(u):void 0;for await(let k of t.pages(u,Ne)){if(n.cancelled||this.stopped()){n.recreate({...Oe(u),planned:k.length,notReached:k.length}),n.cancelled=!0;continue}let y=await dt.read(r,s.snapshotId,u,a),v=[],w=await y.chunk(k).batches(s.snapshotId,u,V);for await(let B of w??[])v.push(...B);let I={...Oe(u),planned:k.length},C=new N;for(let B of v)typeof B.Id=="string"&&C.add(B.Id);let j=k.filter(B=>!C.has(B));j.length>0&&(I.refused+=j.length,Ae(I.reasons,"The checkpoint holds no values of it."),n.leftBy("recreate",u,j));for(let B=0;B<v.length;B+=V){if(this.stopped()){let T=v.length-B;I.notReached=(I.notReached??0)+T,n.leftBy("recreate",u,v.slice(B).map(E=>String(E.Id))),n.cancelled=!0;break}let A=v.slice(B,B+V),x=A.map(T=>y.snapshotIdOf(String(T.Id))),_=new Map,H=A.map((T,E)=>{let b=ct(u,T,h.fields);delete b.Id;let M=m!==void 0&&g?kn(b[m],g):void 0;m!==void 0&&M!==void 0&&(_.set(E,String(b[m])),b[m]=M),Pr(b,this.leftFields.get(P(x[E])));for(let D of h.lookups){let re=b[D];if(typeof re!="string"||re.length<15||!o.has(re))continue;let oe=c(re),$=d.has(oe)?a.currentOf(oe):void 0;if($!==void 0){b[D]=$;continue}p.push({objectApiName:u,from:x[E].slice(0,15),field:D,target:oe}),b[D]=null}return b});await e.recreating(u,x);let G=sn(await this.org.create(u,H)),U=[];if(A.forEach((T,E)=>{let b=G[E];if(b?.success===!0&&typeof b.id=="string"){U.push({objectApiName:u,from:x[E],to:b.id});let M=_.get(E);if(m!==void 0&&M!==void 0){let D=l.get(u)??[];D.push({id:b.id,field:m,status:M}),l.set(u,D)}return}I.refused++,Ae(I.reasons,b?.error??"The org gave no answer for it."),n.leftBy("recreate",u,[String(T.Id)])}),U.length>0){await Fe.add(r,U),await e.recreated(u,U.map(T=>({from:T.from,id:T.to}))),await e.wrote(),n.wrote=!0,I.created+=U.length;for(let T of U)d.add(T.from.slice(0,15));a=await Fe.read(r)}}n.recreate(I)}}await this.fillOwed(p,a,d,n),await this.giveStatusesBack(l,n)}lifecycleOf(e){let t=nt[e];if(t===void 0)return Promise.resolve(void 0);let n=this.lifecycles.get(e);return n||(n=yn(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,o]]of n.entries())for(let a=0;a<o.length;a+=V){if(this.stopped()){let l=[[r,o.slice(a)],...n.slice(s+1)];for(let[u,f]of l)f.length!==0&&t.draftsLeft.set(u,[...t.draftsLeft.get(u)??[],...f.map(({id:h})=>h)]);return}let d=o.slice(a,a+V),c=sn(await this.org.update(r,d.map(({id:l,field:u,status:f})=>({Id:l,[u]:f})))),p=t.recreated.get(r);d.forEach(({id:l},u)=>{let f=c[u];f?.success!==!0&&(p&&Ae(p.reasons,`Made again as a draft, but its status was refused: ${f?.error??"the org gave no answer for it."}`),t.leftBy("recreate",r,[l]))})}}async fillOwed(e,t,n,s){let r=new Map;for(let{objectApiName:o,from:a,field:d,target:c}of e){if(!n.has(a)||!n.has(c))continue;let p=t.currentOf(a),l=t.currentOf(c);if(p===void 0||l===void 0)continue;let u=r.get(o)??new Map;u.set(p,{...u.get(p),Id:p,[d]:l}),r.set(o,u)}for(let[o,a]of r){let d=[...a.values()];for(let c=0;c<d.length;c+=V){if(this.stopped())return;let p=d.slice(c,c+V),l=sn(await this.org.update(o,p)),u=s.recreated.get(o);l.forEach((f,h)=>{f.success||(u&&Ae(u.reasons,`Made again, but a lookup to a record made after it was refused: ${f.error}`),s.leftBy("recreate",o,[String(p[h].Id)]))})}}}async bringBack(e,t,n,s,r,o){let a=Tt(this.org),d=this.makesAgain();for(let{objectApiName:c,count:p}of t.objects){if(s.cancelled||this.stopped()){s.undelete({...Pt(c),planned:p,notReached:p}),s.cancelled=!0;continue}let l;try{l=await this.cascadesOf(c)}catch(f){l=[],this.notes.push(`The records that come back with ${c} could not be told (${ee(f)}): Undo may not send those ${c} records back to the recycle bin.`)}let u=async function*(){for await(let f of t.pages(c,Ne)){let h=f.filter(g=>n.has(g));h.length>0&&(yield{ids:h,asCarriers:!0});let m=h.length>0?f.filter(g=>!n.has(g)):f;m.length>0&&(yield{ids:m,asCarriers:!1})}};for await(let{ids:f,asCarriers:h}of u()){if(s.cancelled||this.stopped()){s.undelete({...Pt(c),planned:f.length,notReached:f.length}),s.cancelled=!0;continue}let m=e.bringingBack([{objectApiName:c,ids:f}],this.count.undelete,{carriers:h}),g=new Map,k=new Map,y=async I=>{let{byParent:C,under:j}=await this.nameChildren(e,a,l,c,I,h),B=await m(I);r(await this.undeleteStamps(c,I,C));for(let A of so(B,I))g.set(P(A),j.get(P(A))??[]);for(let A of ro(B,I))k.set(P(A),{id:A,under:j.get(P(A))??[]});return B},v=await Xt(this.org,await ot({org:this.org,plan:[{objectApiName:c,ids:f}],undelete:y,...this.signal?{signal:this.signal}:{}}),[{objectApiName:c,ids:f}],this.notes);await this.notBroughtBack(e,c,k,v.left);let w=await this.settleGone(c,v,g,s,o,d);for(let I of w.objects)s.undelete(I);s.leftBy("undelete",c,w.left),w.wrote&&(s.wrote=!0,await e.wrote()),w.cancelled&&(s.cancelled=!0)}}}makesAgain(){let e=new Map,{checkpoint:t,folder:n}=this.request;return async(s,r)=>{let o=t.objects.find(d=>d.objectApiName===s);if(!o||!ys(o))return!1;let a=e.get(s);return a||(a=dt.read(n,t.snapshotId,s).catch(()=>{}),e.set(s,a)),(await a)?.has(r)===!0}}remakeUnaskedWords(e){let t=this.asked;if(!t)return;let n=[...new Set(e)],s=As(t.automation,t.steps,n,t.accepted);if(!(s.fired.length===0&&!s.blind))return Yi(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},...nt[c]!==void 0?[{objectApiName:c,write:"update",records:1}]:[]]),r=at(t.written,n.automation,t.limits),a=at([...t.written,...s],n.automation,t.limits).filter(c=>c.verdict==="exceeds");if(a.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 ${a.map(c=>{let p=c.emails-(r.find(l=>l.limit===c.limit)?.emails??0);return`${Ct(p,c.limit)} more than the ${Ct(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,o){let a=t.left.filter(h=>n.has(P(h)));if(a.length===0)return t;let d=new Set,c=0,p=0,l,u=h=>this.access.heldAs(h)==="parent";await this.keepNotInBin(e,a);for(let h of a){if(u(e)){p++,s.mark("outOfReach",e,h);for(let y of n.get(P(h))??[])s.mark("outOfReach",y.objectApiName,y.id);continue}if(!await o(e,h)){s.mark("lost",e,h);continue}let m=[];for(let y of n.get(P(h))??[])u(y.objectApiName)?s.mark("outOfReach",y.objectApiName,y.id):await o(y.objectApiName,y.id)&&m.push(y);let g=[e,...m.map(y=>y.objectApiName)],k=r?this.remakeUnaskedWords(g)??this.remakeEmailsWords(g):void 0;if(r&&k===void 0){await r.add(e,h);for(let y of m)await r.add(y.objectApiName,y.id);d.add(P(h));continue}if(k!==void 0){l=k,s.notAsked.set(P(h),k);for(let y of m)s.notAsked.set(P(y.id),k);continue}c++,s.mark("notInBin",e,h);for(let y of m)s.mark("notInBin",y.objectApiName,y.id)}let f=a.length-d.size;return{...t,objects:t.objects.map(h=>{if(h.objectApiName!==e)return h;let m=f===0?h.reasons.filter(g=>!Ve.test(g)):c>0?h.reasons.map(g=>Ve.test(g)?Vi:g):l!==void 0?h.reasons.map(g=>Ve.test(g)?l??g:g):p>0?h.reasons.map(g=>Ve.test(g)?rn:g):h.reasons;return{...h,planned:h.planned-d.size,refused:Math.max(0,h.refused-d.size),reasons:m}}),left:t.left.filter(h=>!d.has(P(h)))}}async notBroughtBack(e,t,n,s){if(n.size===0)return;let r=new Set(s.map(P)),o=new Map,a=(d,c)=>{let p=o.get(d)??[];p.push(c),o.set(d,p)};for(let[d,{id:c,under:p}]of n)if(r.has(d)){a(t,c);for(let l of p)a(l.objectApiName,l.id)}try{for(let[d,c]of o)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 (${ee(d)}): its undo may count them among what it sends back to the recycle bin.`)}}async keepNotInBin(e,t){try{await Yn.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 (${ee(n)}): a later preview counts them to bring back again.`)}}async nameChildren(e,t,n,s,r,o=!1){let a=new Map,d=new Map,c=new Set(r.map(P)),p=new Map(r.map(h=>[P(h),P(h)])),l=new Map,u=new Map,f=[{objectApiName:s,cascades:n,ids:[...r]}];for(;f.length>0;){let h=new Map;for(let{objectApiName:m,cascades:g,ids:k}of f)for(let y of ge(k,V)){let v=g.filter(({child:C})=>!this.noBin.has(C));if(v.length===0)break;let w=v.map(({child:C,field:j,persons:B})=>({objectApiName:C,soql:`SELECT Id, ${de(j)}${B?`, ${Ue}`:""}${tn(C)?", IsDeleted":""} FROM ${de(C)} WHERE ${j} IN (${y})${tn(C)?"":" AND IsDeleted = true"}`,scanAll:!0}));(await lt(t,w,(C,j)=>{let{child:B,field:A,persons:x}=v[C];for(let _ of j){let H=_[A];if(typeof _.Id!="string"||typeof H!="string"||tn(B)&&_.IsDeleted!==!0)continue;let G=P(_.Id),U=p.get(P(H));U===void 0||c.has(G)||(c.add(G),p.set(G,U),a.set(U,[...a.get(U)??[],_.Id]),!(x&&_[Ue]===!0)&&(d.set(U,[...d.get(U)??[],{objectApiName:B,id:_.Id}]),l.set(B,[...l.get(B)??[],_.Id]),u.set(B,[...u.get(B)??[],o?P(H):U]),h.set(B,[...h.get(B)??[],_.Id])))}})).forEach((C,j)=>{if(!C.read){if(no.test(C.reason)){this.noBin.add(v[j].child);return}this.notes.push(`The ${v[j].child} records that come back with ${m} could not be read (${C.reason}): Undo may not send those ${s} records back to the recycle bin.`)}})}f=[];for(let[m,g]of h)f.push({objectApiName:m,cascades:await this.cascadesUnder(m),ids:g})}for(let[h,m]of l)await e.withParent(h,m,u.get(h),{carriers:o});if(o)for(let h of a.values())for(let m of h)this.carried.add(m);return{byParent:a,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 (${ee(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 o of ge(t,V)){let a=await this.org.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${o})`);for(let d of a.records)if(!(typeof d.Id!="string"||typeof d.LastModifiedDate!="string")){s[d.Id]=d.LastModifiedDate;for(let c of n.get(P(d.Id))??[])s[c]=d.LastModifiedDate}}}catch(o){this.notes.push(`What bringing back ${e} records left on them could not be read (${ee(o)}): the second pass may read them as changed by someone else.`)}return s}async giveBack(e,t,n,s,r,o,a,d){let{checkpoint:c,folder:p}=this.request;for(let{objectApiName:l,count:u}of n.objects){if(a.cancelled||this.stopped()){a.restore({...At(l),planned:u,notReached:u}),a.cancelled=!0;continue}let f=r(l),h=await dt.read(p,c.snapshotId,l),m=t.giveBack.heldBy.find(k=>k.objectApiName===l),g=f.find(k=>k.toLowerCase()==="status");for await(let k of n.pages(l,Ne)){let y=k.filter(A=>!h.retired(A));if(y.length===0)continue;if(a.cancelled||this.stopped()){a.restore({...At(l),planned:y.length,notReached:y.length}),a.cancelled=!0;continue}let v=async(A,x,_,H)=>{let G=await it({org:this.org,plan:[{objectApiName:l,backup:c.snapshotId,ids:[...A]}],backups:Co(h.chunk(A),l,x,_,this.leftFields),fields:{[l]:[...x]},changedAfter:t.restore.changedAfter,ownWriters:ft(c.takenBy,this.userId),includeChanged:!1,stamps:{...t.restore.stamps,...this.stamps},keep:e.keep,stampsFor:()=>!0,...H?{counted:H}:{},...this.signal?{signal:this.signal}:{}});return d(G.stamps),G.wrote&&(a.wrote=!0,await e.wrote()),G.cancelled&&(a.cancelled=!0),G};if(l==="Order"&&g!==void 0&&(await v(y,[g],A=>A[g]==="Draft"),a.cancelled))continue;let w=s==="before"?y.filter(A=>o.has(A)):[];if(w.length>0&&(await v(w,f),a.cancelled))continue;let I=w.length>0?y.filter(A=>!o.has(A)):y;if(I.length===0)continue;let C={restored:[],alreadyGone:[]},j=await v(I,f,void 0,(A,x)=>{this.comesBack.has(A)&&C[x].push(A)});for(let A of j.objects)a.restore(A,C);a.leftBy("restore",l,j.left);let B=j.objects[0];if(s==="after"&&m&&B&&B.refused+(B.restoredWithout??0)>0){let A=a.heldInPlace.get(l)??{reason:bs(l,m.by),ids:new N};for(let x of j.left)A.ids.add(x);a.heldInPlace.set(l,A)}}}}async residualOf(e,t,n,s,r){let o=new Map,a=(u,f,h,m={})=>{let g=`${u}\0${f}\0${m.by??""}\0${m.message??""}`,k=o.get(g);k||(k={objectApiName:u,reason:f,...m.by!==void 0?{by:m.by}:{},count:0,ids:[],...m.message!==void 0?{message:m.message}:{}},o.set(g,k)),k.count++,k.ids.length<pr&&k.ids.push(h)},d=n[n.length-1],c=r?[r,s]:[s],p=[...this.request.checkpoint.objects].sort((u,f)=>u.readOrder-f.readOrder),l=await this.throughCarriers(e.dir);for(let u of p){let f=u.objectApiName;if(this.picked!==void 0&&!this.picked.has(f))continue;let h=[];for(let v of hr)for await(let w of ne(ke(e.dir,f,v)))typeof w.Id=="string"&&(v==="comesBackWithParent"&&l.has(w.Id)||h.push({cls:v,id:w.Id}));if(h.length===0)continue;let m=await this.whoChanged(e.dir,f,h),g=e.dir===t.dir?m:await this.whoChanged(t.dir,f,h),k=this.keptOf(d,f),y=new N;for await(let v of ne(ke(t.dir,f,"goneForGood")))typeof v.Id=="string"&&y.add(v.Id);for(let{cls:v,id:w}of h){if(y.has(w))continue;if(v==="goneForGood"){a(f,"goneForGood",w);continue}let I=Ki[v];if(I!==void 0){a(f,"kept",w,{message:I});continue}let C=m.get(P(w)),j=Be(C?.at)>this.before,B=g.get(P(w)),A=j&&Be(B?.at)>this.before&&Be(C?.at)<=Be(B?.at),x=j&&!A&&this.isOwn(w,C);if(j&&!x){a(f,"changedDuringRewind",w,C?.by?{by:C.by}:{});continue}let _=n.map(({plan:E})=>E.limited?.why.get(P(w))).find(E=>E!==void 0);if(_!==void 0){a(f,"kept",w,{message:_});continue}if(!n.some(({acted:E})=>E.get(f)?.has(w)===!0)){a(f,x?"automation":"changedSincePreview",w);continue}let G=k(w,v);if(G!==void 0){a(f,"kept",w,{message:G});continue}if(v==="withParent"&&c.some(E=>E.left.restore.get(f)?.has(w)===!0)){a(f,"refused",w,{message:this.refusalOf(c,"restore",f,w)});continue}if(x){a(f,"automation",w);continue}if(St[v]==="undelete"||v==="toRecreate"){if(c.some(b=>b.outOfReach.get(f)?.has(w)===!0)){a(f,"kept",w,{message:rn});continue}if(c.some(b=>b.lost.get(f)?.has(w)===!0)){a(f,"goneForGood",w);continue}let E=c.map(b=>b.notAsked.get(P(w))).find(b=>b!==void 0);if(E!==void 0){a(f,"kept",w,{message:E});continue}if(c.some(b=>b.notInBin.get(f)?.has(w)===!0)){a(f,"notInBin",w);continue}}let U=St[v]==="undelete"&&c.some(E=>E.left.recreate.get(f)?.has(w)===!0)?"recreate":St[v],T=U==="removal"?this.keptForDependents(c,f,w):void 0;if(T!==void 0){a(f,"kept",w,{message:Hi(T)});continue}a(f,"refused",w,{message:U?this.refusalOf(c,U,f,w):en})}}return await this.linksStillDiffering(e.dir,n,c,a),[...o.values()]}async linksStillDiffering(e,t,n,s){if(this.request.checkpoint.files===void 0||this.picked!==void 0&&!this.picked.has(Te))return;let r=d=>`${P(d.ContentDocumentId)}:${P(d.LinkedEntityId)}`,o=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 ne(c)){let l=Se.safeParse(p);l.success&&o.add(r(l.data))}let a=new Map;for(let d of[...n].reverse())for(let c of["unlink","relink","share"])for(let{id:p,reason:l}of d.links[c].left)a.set(P(p),l);for(let d of["linkAdded","linkRemoved","linkChanged"])for await(let c of ne(Ut(e,d))){let p=Se.safeParse(c);if(!p.success)continue;let l=p.data,u=d==="linkChanged"?$t.safeParse(c):void 0;if(u?.success===!0&&u.data.now.Visibility===l.Visibility&&u.data.now.ShareType!==l.ShareType&&l.LinkedEntityId.startsWith(Qi)){s(ie,"kept",l.Id,{message:pt});continue}if(d==="linkAdded"&&l.LinkedEntityId.startsWith(eo)){s(ie,"kept",l.Id,{message:Wt});continue}if(!o.has(r(l))){s(ie,"changedSincePreview",l.Id);continue}s(ie,"refused",l.Id,{message:a.get(P(l.Id))??en})}}async throughCarriers(e){let t=new N,n=this.request.checkpoint.objects;for(let{objectApiName:s}of n)for await(let r of ne(ke(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 o=new N;for await(let a of ne(ke(e,r.objectApiName,"comesBackWithParent")))typeof a.Id=="string"&&o.add(a.Id);if(o.size!==0)for await(let a of ne(ut(e,r.objectApiName)))typeof a.Id!="string"||!o.has(a.Id)||t.has(a.Id)||r.cascadeParents.some(d=>t.has(a[d]))&&(t.add(a.Id),s=!0)}}return t}async whoChanged(e,t,n){let s=new Set(n.map(({id:o})=>P(o))),r=new Map;for(let o of[is(e,t),ut(e,t)])for await(let a of ne(o))typeof a.Id!="string"||!s.has(P(a.Id))||r.set(P(a.Id),{...typeof a.LastModifiedById=="string"?{by:a.LastModifiedById}:{},...typeof a.LastModifiedDate=="string"?{at:a.LastModifiedDate}:{}});return r}unpickedWrites(e,t){let n=new Map(e.objects.map(s=>[s.objectApiName,s]));return t.objects.flatMap(s=>{let r=n.get(s.objectApiName);return r===void 0||this.picked?.has(s.objectApiName)!==!1?[]:s.deleted+s.withParentDeleted+s.nextPassDeleted===0?[]:[{...r,toDelete:{createdSince:s.deleted+s.withParentDeleted,broughtBackSince:0,comesBackWithParent:s.nextPassDeleted},toGiveBack:{records:0,fields:0,clearedLookups:0},toBringBack:{inBin:0,withParent:0,deletedWhileTaken:0},toRecreate:0,cannotUndo:[],touched:0,unexplained:0}]})}isOwn(e,t){return t?.by!==void 0&&this.owners.has(P(t.by))?!0:Be(t?.at)<=(this.stampOf.get(P(e))??Number.NaN)}addStamps(e){for(let[t,n]of Object.entries(e)){this.stamps[t]=n;let s=Be(n),r=P(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(r=>r.objectApiName===t),s=n.filter(r=>Qt[r.reason]!==void 0);return(r,o)=>{if(s.length===0)return;let a=n.find(d=>d.ids.some(c=>P(c)===P(r)));if(a)return Qt[a.reason];if(St[o]==="removal"&&!e.plan.deletes.has(P(r)))return Qt[s[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(o=>o.heldInPlace.get(n)).find(o=>o?.ids.has(s)===!0)?.reason:void 0;for(let o of e){if(o.left[t].get(n)?.has(s)!==!0)continue;let d=(t==="restore"?o.restored.get(n)?.reasons:t==="undelete"?o.undeleted.get(n)?.reasons:t==="recreate"?o.recreated.get(n)?.reasons:o.deleted.get(n)?.reasons)?.find(c=>c!==r);if(d!==void 0)return r?`${d} \u2014 ${r}`:d}return r??en}};function Co(i,e,t,n,s){return{batches:async(r,o,a)=>{let d=await i.batches(r,o,a);return d?{async*[Symbol.asyncIterator](){for await(let c of d){let p=c.filter(l=>n?.(l)??!0).map(l=>Pr(ct(e,l,t),typeof l.Id=="string"?s?.get(P(l.Id)):void 0));p.length>0&&(yield p)}}}:null}}}function Pr(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 To=q({success:xe(),id:X().nullish(),errors:me(et([X(),q({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function sn(i){return(Array.isArray(i)?i:[i]).map(t=>{let n=To.safeParse(t);if(!n.success)return{success:!1};let{success:s,id:r,errors:o}=n.data,a=(o??[]).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}:{},...a.length>0?{error:a.join("; ")}:{}}})}export{fa as a,pa as b,ea as c,ta as d,na as e,La as f,Ma as g,Ua as h,$a as i,pr as j,Gi as k,rn as l,Vi as m,Yi as n,Od as o,io as p,oo as q,Ye as r,bo as s,So as t,yr as u,jd as v,Lo as w,Eo as x,Ld as y};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-
|
|
7
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f}from"./chunk-2LSGWTWX.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as loadCreatedRecords,f as loadRecordsInfo,c as loadRecordsKept,b as loadRecordsLeft,d as loadToRemove,e as loadsSweptWith};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,r as p,s as q,t as r,u as s,v as t,w as u,x as v,y as w,z as x}from"./chunk-KWUS7UAV.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-K5PUMHZU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{g as IDS_PER_LINE,m as OverwritesRead,h as PIPELINE_NAME_KEPT,e as SCENARIO_COMPANION_SUFFIX,d as SYNC_FILE_OBJECTS,a as SYNC_RUNS_DIR,c as SYNC_RUNS_HARD_MAX_BYTES,b as SYNC_RUNS_MAX_BYTES,x as SyncRunCreations,i as backupIdSchema,u as configTargetOf,o as createdCount,r as deletedCount,v as earlierRunsOf,f as nodeSyncRunCreations,p as overwrittenCount,j as readRemovalState,l as readRunFile,t as settled,n as syncRemovalPlan,q as syncRestorePlan,k as syncRunFileId,s as syncUndeletePlan,w as writtenAgainBy};
|