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
package/lib/chunk-26EGXYZ4.mjs
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as gS,b as fd,c as fS,d as hS}from"./chunk-BXZ73A5M.mjs";import{b as uS}from"./chunk-3QCUSZIZ.mjs";import{a as Gb}from"./chunk-KYLHS74X.mjs";import{c as Wb,d as zb}from"./chunk-FBYFCKPG.mjs";import{b as Ub}from"./chunk-ZRUDYB7O.mjs";import{d as mS,m as yS}from"./chunk-DN7YBILC.mjs";import{a as lS,b as oo,c as Vs,d as rp,e as np,f as op,g as pS,h as sp}from"./chunk-YTBM3TSW.mjs";import{a as Dl,b as Bb,c as qb,d as Ua,f as qs}from"./chunk-A3QNSALB.mjs";import{h as vR,k as ER,l as PR,m as zs,n as _o,o as Bl,p as Ga,q as CR,r as $R,s as xR,u as DR}from"./chunk-5C7LQXYS.mjs";import{a as Rv,b as Zl,c as eS,d as tS,e as rS,h as nS,i as oS,j as sS,k as iS,n as aS,o as dS,p as pd,q as ep,r as gd,s as tp}from"./chunk-BRN42U26.mjs";import{b as Qv,e as Zv}from"./chunk-55VBV2WK.mjs";import{$ as Kv,A as jv,B as dd,C as Mv,D as Lv,E as cd,F as ud,G as ld,H as Nn,I as Fv,J as _v,M as Uv,N as Hv,O as Bv,P as qv,Q as Wv,S as zv,T as Ql,U as Gv,V as Jv,W as Vv,a as Qa,ba as Xv,c as Za,ca as Yv,d as ed,e as vv,f as Sv,g as kv,h as It,j as Js,k as td,l as rd,m as nn,n as Wo,o as zo,p as Go,q as Ov,r as Iv,s as Av,t as nd,u as od,v as sd,w as Tv,x as xv,y as Dv,z as Nv}from"./chunk-TFGJDZFE.mjs";import{b as id,g as ad}from"./chunk-G6IYOZEH.mjs";import{e as Pr,g as Ev,i as Pv,k as Cv,l as Jo,m as $v}from"./chunk-2JRVBXJL.mjs";import{a as cS}from"./chunk-MQLTEXB7.mjs";import{a as Uh,b as aa,e as Ta,g as An,h as ar,i as Ib,l as Pb,p as Hb}from"./chunk-AAOMUI7S.mjs";import{a as Rt,b as Yw}from"./chunk-JHJDDQDE.mjs";import{a as ub,b as lb}from"./chunk-XCA5AONB.mjs";import{a as Ea,b as Qw,c as Zw,d as eb,e as Us,f as tb,g as rb,h as nb,j as ob}from"./chunk-WB2RIVO3.mjs";import{$ as Em,$b as Xy,A as im,Ab as Oy,B as Sn,Bb as Iy,C as hl,Ca as Hm,Cb as Ay,D as am,Da as Bm,Db as Ty,E as dm,Ea as qm,Eb as Ey,Ec as et,F as ca,Fa as Wm,Fb as Py,Fc as eo,G as cm,Ga as zm,Gb as la,Gc as pb,H as um,Ha as Gm,Hb as Cy,Hc as gb,I as lm,Ia as Jm,Ib as $y,J as pm,Ja as Vm,Jb as xy,K as gm,Ka as Km,Kb as Dy,L as fm,La as Xm,Lb as Ny,M as ml,Ma as Ym,Mb as jy,N as hm,Na as Qm,Nb as My,O as mm,Oa as Zm,Ob as Ly,P as ym,Pa as Yr,Pb as Fy,Q as wm,Qa as ey,Qb as _y,R as bm,Ra as Rl,Rb as Uy,S as Rm,Sa as ua,Sb as Hy,T as vm,Ta as Ds,Tb as By,U as Sm,Ua as ty,Ub as qy,V as km,Va as ry,Vb as Wy,W as Om,Wb as zy,X as Im,Xb as Gy,Y as Am,Yb as Jy,Z as Tm,Zb as Vy,_ as Po,_b as Ky,a as Kr,aa as Pm,ac as Yy,b as Re,ba as Cm,bc as Qy,c as sa,ca as $m,cc as Zy,d as xt,da as yl,dc as ew,e as Rn,ea as xm,ec as tw,f as Eo,fa as Dm,fb as ny,fc as rw,g as lt,ga as Nm,gb as oy,gc as nw,h as Rr,ha as jm,hb as sy,hc as ow,i as vn,ia as Mm,ib as iy,ic as sw,j as A,ja as Lm,jb as ay,jc as iw,k as Ie,ka as Fm,kb as dy,kc as aw,l as Je,la as _m,lb as cy,lc as dw,m as Fe,ma as Um,mb as uy,mc as pa,n as pe,na as wl,nb as ly,nc as cw,o as E,oa as bl,ob as py,oc as uw,p as ia,pa as xs,pb as gy,pc as lw,q as Ts,qb as fy,qc as pw,r as Xr,rb as hy,rc as gw,s as je,sb as my,sc as fw,t as tm,tb as yy,tc as hw,u as rm,ub as wy,uc as mw,v as nm,vb as by,vc as yw,w as om,wb as Ry,wc as vl,x as da,xb as vy,xc as $,yb as Sy,z as sm,zb as ky,zc as Aa}from"./chunk-RIIJJRGF.mjs";import{g as Ia}from"./chunk-EYFP3NA6.mjs";import{a as Lt,b as Cs,c as Wh,d as zh}from"./chunk-CE6ZDGBB.mjs";import{a as fb,b as hb,c as mb,e as yb,f as wb,g as $a,h as No,i as ro,j as en,k as Tn,l as xa}from"./chunk-LSEM2BZH.mjs";import{b as to,c as Ob}from"./chunk-BOGNK4LV.mjs";import{$a as qo,A as jR,Aa as QR,Ba as ZR,Ca as ev,E as MR,Ea as tv,Fa as rv,Ga as Kl,Ia as Uo,Ka as nv,La as Ka,Ma as ov,T as LR,Va as sv,Xa as Ho,Za as iv,_a as Bo,a as ea,b as Rh,da as Wl,db as av,ea as zl,eb as Er,fb as Xl,ga as Gl,gb as uv,h as RR,hb as lv,i as Hl,ib as pv,jb as gv,ka as Va,kb as Xa,lb as Ya,ma as GR,n as NR,oa as Jl,ob as fv,pb as hv,qa as JR,rb as Yl,sa as VR,sb as mv,tb as yv,ua as Vl,ub as wv,va as Gs,vb as bv,wa as KR,ya as XR,za as YR}from"./chunk-SAHGDSZQ.mjs";import{a as Ww,b as Co,c as $o,d as In,e as zw,f as Gw,g as Tl,j as sb,k as ib,l as Ca,m as ab,n as db,q as $l,r as Bs,s as no,t as Fa}from"./chunk-TG52WNGV.mjs";import{A as Uw,B as ir,C as Ra,D as va,E as Sa,G as ka,J as Hw,K as Il,L as Al,M as Kt,N as Bw,O as qw,P as Oa,a as Lh,b as bw,c as Rw,d as vw,e as sr,f as kl,g as Ol,h as Sw,i as kw,j as Ow,k as Iw,l as Yn,n as Ms,o as xw,p as Dw,r as Nw,s as jw,t as Ls,v as Mw,w as Lw,x as Fw,y as _w}from"./chunk-CSSOLHE3.mjs";import{b as dv,c as cv}from"./chunk-HGJFATSI.mjs";import{h as SR}from"./chunk-TEIBWMJM.mjs";import{a as kR,b as OR,f as IR,g as AR,h as TR}from"./chunk-BWWQXU2B.mjs";import{d as Pa}from"./chunk-T63U4OZJ.mjs";import{a as Mb,b as _a,c as Lb,k as Fb,p as _b}from"./chunk-5EESNYE3.mjs";import{a as cb}from"./chunk-YYZL7UGV.mjs";import{a as ya,c as wa}from"./chunk-YDXMTWAT.mjs";import{b as Jw,f as Vw,p as Ft,q as Fs,r as El,s as Do,t as Pl,u as _s,x as Kw,y as Xw}from"./chunk-RM5G4IP6.mjs";import{b as FR,c as _R,d as UR,e as Ja,f as ql,h as HR,i as BR,j as qR,k as WR,n as zR}from"./chunk-B5A4JHNN.mjs";import{c as vr,d as Zn}from"./chunk-YGE4AUXG.mjs";import{b as Ma,f as La}from"./chunk-C2MHMI7U.mjs";import{L as Eb,d as Da,h as Na,i as Ab,k as Tb,z as ja}from"./chunk-SF52ZSIV.mjs";import{a as ga,b as Wt,c as Qr,d as Ns,e as fa,f as js,g as ha,h as kn,i as ww,j as ma,k as Sl}from"./chunk-P6A22FMQ.mjs";import{a as xe}from"./chunk-5LFSFYFJ.mjs";import{b as bh}from"./chunk-XZRON54U.mjs";import{a as al,c as Oo,d as dl,e as lh,f as Is,g as cl,h as ph,j as gh,k as fh,l as Io,m as hh,n as ul,o as mh,p as yh,q as wh,r as q}from"./chunk-3EOIAC2M.mjs";import{a as bb,b as zt,c as Gt,g as dr}from"./chunk-AIUAEBHR.mjs";import{$a as Kb,Ac as Fl,Bc as _l,Cc as hR,Dc as mR,Ec as yR,Fb as eR,Fc as Ul,Gb as tR,H as Cb,Hb as rR,Ib as Ir,Ic as pt,J as $b,Jb as Ar,Jc as za,Kb as Wa,Kc as wR,L as xb,Lb as nR,Lc as bR,Nb as Ml,O as Db,P as Nb,Q as xl,Ra as rn,Rb as oR,T as jb,Ta as Nl,Ua as Jb,Xa as Vb,Xb as sR,Yb as iR,Za as En,Zb as aR,_a as jl,_b as Tr,ab as Xb,b as Hh,c as rt,cb as Yb,d as Bh,db as Qb,e as gl,eb as Zb,ec as dR,f as qh,fb as cr,g as Es,gc as cR,h as fl,hb as Or,hc as uR,i as _t,ib as ur,ic as lR,j as Dt,jc as pR,kc as gR,l as Sb,mb as Pn,n as Cl,nb as Mo,nc as fR,o as Zr,ob as Ha,p as kb,pb as Lo,pc as $n,qb as Cn,qc as xn,r as Ot,rb as Fo,s as Hs,sb as Ba,t as Xt,ub as qa,wc as Dn,xc as Ws,zc as Ll}from"./chunk-O3ZQSWDN.mjs";import{a as Fh,e as To,f as bt,g as _h,i as br,j as Q,k as mt}from"./chunk-DNE7JI3A.mjs";import{a as Qi,f as Zi}from"./chunk-CI2O7WBH.mjs";import{q as kr,r as tn,s as jo}from"./chunk-5T3LFDJ5.mjs";import{a as Sr,b as ge}from"./chunk-VV3B6IC3.mjs";import{a as ne}from"./chunk-4TLYUZD5.mjs";import{i as Ps}from"./chunk-INIT2UKJ.mjs";import{a as uh,b as Os,c as il}from"./chunk-Q7TLC3I2.mjs";import{e as Ew,h as On,k as Pw,l as Cw,m as $w}from"./chunk-JBOGAUGH.mjs";import{b as ba}from"./chunk-4N425UJC.mjs";import{D as $s,F as em,p as Xh}from"./chunk-TWYNQ2OO.mjs";import{b as Gh,e as Jh,k as Vh,m as Kh}from"./chunk-HFSBDM7B.mjs";import{a as or}from"./chunk-EADHKH3A.mjs";import{c as $h,f as oa,g as xh,j as Dh,l as Nh,r as jh,s as Mh}from"./chunk-FG4Y4ZVL.mjs";import{$ as Ch,F as wr,G as As,N as Ah,P as Th,Y as Eh,Z as Ph,a as ta,b as nr,c as ra,f as Sh,j as kh,m as na,n as pl,o as Oh,p as Ih,q as Ao,r as yr}from"./chunk-Z354SAEF.mjs";import{a as rr,d as ll,f as vh,h as ze}from"./chunk-TZE3Y7IQ.mjs";import{a as ch,b as I}from"./chunk-CA5NAXSU.mjs";import{a as Rb,b as vb}from"./chunk-PC247GKX.mjs";import{f as Aw,j as Tw}from"./chunk-THYQOG24.mjs";import{a as Qh,d as Zh}from"./chunk-JFVY66BS.mjs";import{a as Yh}from"./chunk-GUYEXPJ4.mjs";import{a as xo,d as Qn}from"./chunk-TUACWKIH.mjs";import{$b as Nf,$c as Qu,A as ys,Aa as qr,Ad as tl,Ae as bn,Ba as _i,Bd as wn,Be as $t,Ca as Sf,Cd as qf,Ce as Vi,Da as zu,Dd as Gr,De as Ss,Ea as Gu,Ed as Wf,Ee as ks,Fa as kf,Fd as rl,Fe as Ki,Ga as Ju,Gd as zf,Ge as nl,Hd as Gf,He as nh,I as yf,Id as Ji,Ie as ol,Jd as Jf,Ke as oh,Lb as Tf,Ma as Of,Mb as Kn,Me as sh,Na as If,Nb as Ku,Ne as sl,Ob as Xu,Oe as Xi,Pb as Ef,Pe as ih,Qb as Pf,Qd as Vf,Qe as ah,Re as dh,Se as Yi,Ub as Cf,Uc as wt,Wc as Xn,Xb as $f,Xc as Wi,Xd as Rs,Y as Fi,Yb as xf,Z as Bu,Zb as Df,Zc as Pe,Zd as Jr,_ as wf,_b as Ui,_c as vo,ac as jf,ad as Wr,b as sf,bc as Hi,be as Kf,c as af,cd as Zu,d as pf,dc as Mf,dd as ye,ec as Lf,fc as Ff,fe as Vr,ge as ut,ja as qu,k as bo,kd as zi,l as Ro,la as bf,lc as _f,ld as So,mc as Yu,md as ko,nb as Af,ne as Xf,o as yn,ob as Vu,od as Uf,oe as Yf,p as ms,pd as Hf,pe as vs,q as gf,r as ff,s as hf,te as Qf,ud as el,ue as Zf,va as Rf,vc as Bi,vd as zr,ve as eh,wa as Wu,we as th,xa as vf,xc as qi,xd as Bf,xe as rh,yd as bs,z as mf,zc as ws,zd as Gi}from"./chunk-CRPLDXJU.mjs";import{a as df,b as j,e as Te,f as Ke,i as mn,k as ve,l as V,o as cf,p as Mi,s as Li,u as We,v as yt,x as uf,y as lf,z as Vn}from"./chunk-WZQEK4WT.mjs";var wS="pipeline-rewind-grants",RS="pipeline:rewind-grant:",bS="pipeline:saved:",ip=V({pipelineId:j().min(1).max(200),stepId:j().min(1).max(200),organizationId:j().min(1).max(18),checkpointId:j().min(1).max(200),digest:j().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:Vn.datetime(),grantedBy:j().max(80).optional(),takenBackAt:Vn.datetime().optional()}).strict();function jn(s,e){return`Rewind step "${s}" has `+(e==="changed"?"not been confirmed since it was changed":"never been confirmed")+": open it and type the org's alias, or, for an org that has none, its name or Organization Id. No record was written."}function ap(s,e){return`${RS}${s}:${e}`}var Ks=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(wS)).flatMap(e=>{let t=ip.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=ip.safeParse(this.store.get(ap(e,t)));return r.success?r.data:void 0}write(e){this.store.set(ap(e.pipelineId,e.stepId),ip.parse(e),wS)}revoke(e,t){return this.store.delete(ap(e,t))}revokePipeline(e){let t=`${RS}${e}:`,r=[];for(let n of this.store.getKeysByPrefix(t))this.store.delete(n)&&r.push(n.slice(t.length));return r}revokeChanged(e,t,r=()=>new Date){let n=[];for(let o of this.all().filter(i=>i.pipelineId===e)){let i=t.find(d=>d.id===o.stepId),a=i?.type==="rewind";a&&o.takenBackAt!==void 0||a&&Xs(i.config)===o.digest||(a?(this.write({...o,takenBackAt:r().toISOString()}),n.push(o.stepId)):this.revoke(o.pipelineId,o.stepId)&&o.takenBackAt===void 0&&n.push(o.stepId))}return n}async revokeVoid(e){let t=[],r=new Map;for(let n of this.all()){let i=!this.store.has(`${bS}${n.pipelineId}`);if(!i&&e){let a=r.get(n.checkpointId);a||(a=e(n.checkpointId),r.set(n.checkpointId,a)),i=!await a}i&&this.revoke(n.pipelineId,n.stepId)&&t.push(n)}return t}verify(e,t){let r=this.get(e,t.id);return!r||!this.store.has(`${bS}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||Xs(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function Xs(s){let e=$t.safeParse(s??{});return e.success?ks(e.data):void 0}function vS(s,e){return new Ks(s).revokePipeline(e)}function Mn(s){let e;try{e=new URL(s)}catch{return{ok:!1,reason:"invalid"}}return e.protocol!=="https:"?{ok:!1,reason:"not-https",protocol:e.protocol}:{ok:!0,url:e}}var oE="/lightning/setup/AsyncApexJobs/home";function SS(s){let e=Mn(s);return e.ok?{ok:!0,url:new URL(oE,e.url.origin).toString()}:e}import{randomBytes as sE}from"node:crypto";import{createReadStream as iE}from"node:fs";import{open as aE,readdir as dE,rm as cE,stat as uE}from"node:fs/promises";import{homedir as lE}from"node:os";import{join as lr,resolve as pE}from"node:path";import{createInterface as gE}from"node:readline";var dp="journal.ndjson",hd=2e3,TS=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,kS="abcdefghijklmnopqrstuvwxyz0123456789";function up(s=new Date){let e=s.toISOString(),t=`${e.slice(0,4)}${e.slice(5,7)}${e.slice(8,10)}`,r=`${e.slice(11,13)}${e.slice(14,16)}${e.slice(17,19)}`,n=Array.from(sE(4),o=>kS[o%kS.length]).join("");return`em-${t}-${r}-${n}`}function cp(s){return TS.test(s)}function lp(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?pE(e):lr(lE(),".sandforge");return lr(t,"empty")}var fE=j().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),on=j().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Ys=Vn.datetime({offset:!0}),OS=ve(fE).max(hd),ES=We(["success","partial","failure","cancelled"]),PS=V({v:yt(1),kind:yt("head"),runId:j().regex(TS),organizationId:j().min(15).max(18),orgName:j(),startedAt:Ys,readAt:Ys,previewId:j(),mode:We(["objects","org"]),deleteMode:We(["recycle","hard"]),request:V({mode:We(["objects","org"]),objects:ve(j()).optional(),excluded:ve(j()).optional(),customSettings:Ke().optional(),files:Ke().optional(),managedPackages:Ke().optional(),unrestorable:Ke().optional()}).strict(),passes:ve(V({objectApiName:on,records:Te().int().nonnegative().optional(),sent:Te().int().nonnegative().optional(),rows:j().max(200).optional()})),toDraftAlong:ve(V({objectApiName:on,condition:j().optional()})),beforeParent:ve(V({objectApiName:on,field:j(),parent:on,reason:We(["restricted","customPrices"])})),undoLost:ve(V({objectApiName:on,field:j().optional(),parent:on.optional(),reason:We(["restricted","unordered","notRestorable"]),records:Te().int().nonnegative().optional(),atLeast:yt(!0).optional()})).optional()}),hE=V({kind:yt("attempt"),at:Ys,resumed:Ke()}),CS=V({kind:yt("spooled"),objectApiName:on,place:Te().int().nonnegative(),count:Te().int().nonnegative(),sinceRead:Ke()}),mE=V({kind:yt("settled"),objectApiName:on,deleted:OS,gone:OS}),yE=V({objectApiName:on,planned:Te().int().nonnegative(),deleted:Te().int().nonnegative(),gone:Te().int().nonnegative(),refused:Te().int().nonnegative(),notReached:Te().int().nonnegative().optional(),madeSince:Te().int().nonnegative().optional(),reasons:ve(j())}),$S=V({kind:yt("end"),at:Ys,status:ES,hardRefused:j().optional(),passes:ve(yE)}),wE=V({kind:yt("undo"),at:Ys,status:ES}),IS=Mi("kind",[PS,hE,CS,mE,$S,wE]),Cr=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function bE(s){return s==="success"||s==="partial"}var md=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=PS.parse({v:1,kind:"head",...t});await ja(e);let n=new s(e,r);return await n.write(r,"wx"),n}static async open(e){let t;for await(let r of AS(lr(e,dp))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new Cr("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return lr(this.dir,"ids",`${e}-${wt(t)}`)}async write(e,t="a"){let r=lr(this.dir,dp),n=await aE(r,t,Da);try{await n.appendFile(`${JSON.stringify(e)}
|
|
8
|
-
`,"utf8"),await n.sync()}finally{await n.close()}}attempt(e,t){return this.write({kind:"attempt",at:t.toISOString(),resumed:e})}spooled(e){return this.write(CS.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=hd)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+hd),gone:r.slice(n,n+hd)})}ended(e,t,r,n){return this.write($S.parse({kind:"end",at:r.toISOString(),status:e,...n!==void 0?{hardRefused:n}:{},passes:t}))}undone(e,t){return this.write({kind:"undo",at:t.toISOString(),status:e})}lines(){return AS(lr(this.dir,dp))}async state(){let e=0,t,r,n=!1,o=!1,i=new Map;for await(let a of this.lines())switch(a.kind){case"attempt":e++,r=void 0;break;case"spooled":i.set(a.objectApiName,a);break;case"settled":a.deleted.length>0&&(o=!0);break;case"end":t=a,r=a;break;case"undo":bE(a.status)&&(n=!0);break;default:break}return{head:this.head,attempts:e,...t?{lastEnd:t}:{},open:e>0&&!n&&(r===void 0||r.status==="cancelled"||r.status==="failure"&&o),undone:n,spooled:i,deletedAny:o}}async*settledOf(e){for await(let t of this.lines())t.kind==="settled"&&t.objectApiName===e&&(yield t)}};async function*AS(s){let e=iE(s,{encoding:"utf8"}),t=gE({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return IS.parse(JSON.parse(i))}catch{throw new Cr(`Line ${a} of the journal of this emptying does not read: the journal is not used.`)}};try{for await(let i of t)n++,i.trim()!==""&&(r&&(yield o(r.raw,r.number)),r={raw:i,number:n})}catch(i){throw i.code==="ENOENT"?new Cr("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield IS.parse(JSON.parse(r.raw))}catch{return}}var yd=class{constructor(e){this.root=e}root;orgDir(e){return lr(this.root,Tb(e))}begin(e,t){return md.begin(lr(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await dE(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(cp).sort().map(n=>({runId:n,dir:lr(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!cp(t))throw new Cr(`Not an emptying's id: ${t}`);let r=lr(this.orgDir(e),t);try{await uE(r)}catch{throw new Cr(`No journal of the emptying ${t} is on this machine.`)}return md.open(r)}async remove(e,t){cp(t)&&await cE(lr(this.orgDir(e),t),{recursive:!0,force:!0})}};import{createHash as RE}from"node:crypto";import{readFileSync as vE}from"node:fs";import{homedir as SE}from"node:os";import{join as wd,resolve as kE}from"node:path";var xS=V({...Rb,pipelineId:j().min(1).max(200),pipelineName:j().max(200).optional(),ranFrom:We(["editor","commandLine"]),triggeredBy:We(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),dryRun:Ke().optional()}),pp=vb(s=>{let e=xS.safeParse(s);return e.success?e.data:void 0}),OE="run.lock",IE=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;function DS(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?kE(e):wd(SE(),".sandforge");return wd(t,"pipelines")}function Qs(s){return IE.test(s)&&!s.includes("..")?s:`p-${RE("sha256").update(s).digest("hex").slice(0,32)}`}function bd(s,e){return wd(s,Qs(e))}function NS(s,e){return wd(bd(s,e),OE)}function AE(s){try{let e=xS.safeParse(JSON.parse(vE(s,"utf8")));return e.success?e.data:void 0}catch{return}}function gp({version:s,token:e,...t}){return t}function jS(s,e,t,r={}){let n=NS(s,e),o=AE(n),i=o!==void 0&&pp.holder(n,r)===void 0,a=pp.acquire(n,d=>({...d,pipelineId:e,...t.pipelineName!==void 0?{pipelineName:t.pipelineName.slice(0,200)}:{},ranFrom:t.ranFrom,triggeredBy:t.triggeredBy,...t.dryRun?{dryRun:!0}:{}}),r);return"busy"in a?{busy:gp(a.busy)}:{lock:{pipelineId:e,release:a.lock.release},...i&&o!==void 0?{tookOver:gp(o)}:{}}}function YL(s,e,t={}){let r=pp.holder(NS(s,e),t);return r!==void 0?gp(r):void 0}function MS(s){let e=s.dryRun?"a simulation":"a run";return s.ranFrom==="commandLine"?`${e} from the command line (sandforge pipeline run)`:`${e} in VS Code`}function fp(s,e){return`Pipeline "${e}" is already running on this machine: ${MS(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}) has not ended. A pipeline runs once at a time: run it again once that run ends.`}function LS(s){return`The run lock of pipeline "${s.pipelineName??s.pipelineId}" was left by ${MS(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}), whose process has ended: taken over.`}import{randomBytes as TE}from"node:crypto";import{mkdirSync as EE,readFileSync as US,readdirSync as PE,renameSync as FS,statSync as CE,unlinkSync as $E,writeFileSync as xE}from"node:fs";import{join as mp}from"node:path";var yp=50,wp="history.json",bp=1,_S=4*1024*1024,DE=448,NE=384,jE=V({decision:We(["approved","rejected","timedOut","cancelled"]),via:We(["notification","page","terminal","commandLine"]).optional(),at:j().max(64),by:j().max(64).optional()}),ME=V({stepName:j().max(200),stepType:j().max(80),status:We(["pending","running","completed","failed","skipped","stopped"]),duration:Te().nonnegative().optional(),summary:j().max(8e3).optional(),error:j().max(8e3).optional(),approval:jE.optional()}),hp=V({runId:j().min(1).max(200),pipelineId:j().min(1).max(200),pipelineName:j().max(200),status:We(["idle","queued","running","completed","completed_with_warnings","failed","cancelled"]),triggeredBy:We(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),startTime:Vn.datetime({offset:!0}),duration:Te().nonnegative(),stepCount:Te().int().nonnegative(),errorCount:Te().int().nonnegative(),steps:ve(ME).max(200).optional()}),LE=V({sandforgePipelineHistory:yt(bp),entries:ve(mn()).max(yp*4)});function nF(s,e){return mp(bd(s,e),wp)}function FE(s){let e=Date.parse(s.startTime);return{...s,ranFrom:"commandLine",timestamp:Number.isNaN(e)?0:e}}function HS(s){let e;try{e=JSON.parse(s)}catch{return{why:"it is not JSON"}}let t=LE.safeParse(e);if(!t.success){let o=e?.sandforgePipelineHistory;return{why:typeof o=="number"&&o>bp?`a later release of SandForge wrote it (version ${o})`:"it is not a pipeline history"}}let r=[],n=0;for(let o of t.data.entries){let i=hp.safeParse(o);i.success?r.push(FE(i.data)):n+=1}return{entries:r,skipped:n}}function BS(s,e){let t=new Map,r=(n,o,i)=>{t.get(n)!==o&&(t.set(n,o),e(i))};return{read(){let n;try{n=PE(s,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let o=[];for(let i of n.sort()){let a=mp(s,i,wp),d,c;try{let l=CE(a);if(d=`${l.size}:${l.mtimeMs}`,l.size>_S){r(a,d,`[WARN] pipeline history ${a} is not listed: at ${l.size} bytes it is past the ${_S} a history of ${yp} runs takes.`);continue}c=US(a,"utf8")}catch{continue}let u=HS(c);if("why"in u){r(a,d,`[WARN] pipeline history ${a} is not listed: ${u.why}. The runs it held are not shown in History; the next run from the command line starts it again.`);continue}u.skipped>0&&r(a,d,`[WARN] pipeline history ${a}: ${u.skipped} of its runs do not read and are not listed.`),o.push(...u.entries)}return o.sort((i,a)=>a.timestamp-i.timestamp)}}}function oF(s,e,t){let r=hp.safeParse(t);if(!r.success)throw new Error(`The run was not recorded: ${r.error.issues.slice(0,3).map(l=>`${l.path.join(".")||"(entry)"}: ${l.message}`).join("; ")}`);let n=bd(s,e);EE(n,{recursive:!0,mode:DE});let o=mp(n,wp),i=[],a,d;try{d=US(o,"utf8")}catch{d=void 0}if(d!==void 0){let l=HS(d);"why"in l?(a=`${o}.unreadable-${Date.now()}`,FS(o,a)):i=l.entries.map(({ranFrom:g,timestamp:p,...f})=>hp.parse(f))}let c=[r.data,...i.filter(l=>l.runId!==r.data.runId)].sort((l,g)=>Date.parse(g.startTime)-Date.parse(l.startTime)).slice(0,yp),u=`${o}.${process.pid}-${TE(4).toString("hex")}.tmp`;xE(u,`${JSON.stringify({sandforgePipelineHistory:bp,entries:c},null,2)}
|
|
9
|
-
`,{encoding:"utf8",mode:NE,flag:"wx"});try{FS(u,o)}catch(l){try{$E(u)}catch{}throw l}return{kept:c.length,...a!==void 0?{setAside:a}:{}}}var Ht={major:20,minor:19},qS=5,_E=12,UE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function gt(s){return s.replace(/\s*[\r\n\u2028\u2029]+\s*/g," ").trim()}function Ut(s){return`'${s.replace(/'/g,"'\\''")}'`}function Yt(s){return`'${s.replace(/['\u2018\u2019\u201a\u201b]/g,e=>e+e)}'`}function Vo(s){return JSON.stringify(s)}function Rp(s){return s.endsWith(nl)?s.slice(0,-nl.length):s.replace(/\.json$/,"")}function HE(s){return`SFDX_AUTH_URL_${s.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`}function vp(s){return"refused"in s?{kind:"refused",code:s.refused,reason:s.reason}:{kind:"line",text:s.cron,timezone:s.timezone,offsetMinutes:s.offsetMinutes,offsetChanges:s.offsetChanges}}function WS(s){return s.offsetChanges.map(e=>{let t=s.offsetMinutes-e.offsetMinutes,r=new Date(e.at).toISOString();return t===0?`From ${r}, it runs at the pipeline's times again.`:`From ${r}, it runs ${Math.abs(t)} minutes ${t>0?"later":"earlier"} than the pipeline's schedule says: export it again then.`})}function BE(s){return`npx -y sandforge@${s.sandforgeVersion} pipeline run --file ${s.fileName}`}function Sp(s,e){return[`SandForge pipeline "${gt(s.pipelineName)}", run from its file with VS Code closed.`,`Exported by SandForge ${s.sandforgeVersion} on ${s.exportedAt}.`,"",...e,"",`It runs: ${BE(s)}`,"Exit code: the run's. 0 completed; 1 failed; 2 refused before its first step, nothing","ran; 3 completed with a step that failed; 129, 130 or 143 stopped by a signal; and 127","when Node.js or the Salesforce CLI is not found."]}function kp(s,e,t){let r=[];if(s.approvals.length>0){r.push(`${e} An Approval step asks a person. Run with no one at a terminal, the run is`,`${e} refused before its first step unless the step is answered here, ahead:`,`${e} remove the "${e}" of its line to answer it yes on every run.`);for(let n of s.approvals)n.staging?r.push(`${e} "${gt(n.name)}" stands before a write to a sandbox marked Staging:`,`${e} only a person at a terminal answers it, never a line here.`):r.push(`${e} ${t("--approve",n.name)}`)}if(s.rewinds.length>0){r.push(`${e} A Rewind step runs once its org's alias is confirmed: by`,`${e} "npx -y sandforge@${s.sandforgeVersion} pipeline confirm --file ${s.fileName}"`,`${e} at a terminal of this machine, or here. Its checkpoint must be kept on this machine.`);for(let n of s.rewinds)r.push(n.alias!==void 0?`${e} ${t("--confirm-rewind",n.alias)}`:`${e} "${gt(n.name)}" rewinds an org with no alias: confirm it with pipeline confirm.`)}return r}function Ko(s){for(let e of s){let t=e.codePointAt(0)??0;if(t<32||t===127||t===8232||t===8233)return!1}return!0}function qE({alias:s,...e}){return e}function Op(s){if(!Ko(s.fileName))throw new Error("A pipeline file name is one line of text.");let e=[],t=s.orgs.flatMap(i=>Ko(i.key)?i.alias===void 0||Ko(i.alias)?[i]:(e.push(`The alias of org "${gt(i.label)}" holds a line break: it is asked below as an alias of this machine.`),[qE(i)]):(e.push(`Org "${gt(i.label)}" is named by a key no line can hold: run it from a terminal.`),[])),r=s.variables.filter(i=>Ko(i.name)?!0:(e.push(`Variable "${gt(i.name)}" holds a line break in its name, which no line gives: rename it.`),!1)),n=s.approvals.filter(i=>Ko(i.name)?!0:(e.push(`Approval step "${gt(i.name)}" holds a line break in its name: only a terminal answers it.`),!1)),o=s.rewinds.map(i=>i.alias===void 0||Ko(i.alias)?i:{name:i.name});return{input:{...s,orgs:t,variables:r,approvals:n,rewinds:o},leftOut:e}}function zS(s){return s.orgs.filter(e=>e.alias===void 0).map((e,t)=>({...e,slot:`org_alias_${t+1}`}))}function WE(s){let{input:e,leftOut:t}=Op(s),n=`${Rp(e.fileName)}.sh`,o=Qs(e.pipelineId),i=e.schedule===null?void 0:vp(Xi(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now)),a=i===void 0?["This pipeline has no schedule: run this script by hand, or from a scheduler of your own."]:i.kind==="line"?[`Its schedule, as a line of this machine's crontab (crontab -e), read in ${i.timezone}:`,` ${i.text} /bin/bash /path/to/${n}`,...i.offsetMinutes!==0?[`The pipeline's schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, moved by ${i.offsetMinutes} minutes: Ubuntu's cron reads no zone of its own.`]:[],...WS(i)]:["Its schedule cannot be written as a line of this machine's crontab:",gt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs Node.js ${Ht.major}.${Ht.minor} or later`,"and the Salesforce CLI (sf), signed in to each org of the pipeline under its alias.","Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=zS(e),u=["#!/usr/bin/env bash",...Sp(e,d).map(l=>l===""?"#":`# ${l}`),"set -u","",'here="$(cd "$(dirname "$0")" && pwd)"',`file="$here/"${Ut(e.fileName)}`,`store="\${SANDFORGE_JOURNAL_DIR:-$HOME/.sandforge}/pipelines/"${Ut(o)}`,'mkdir -p "$store" && chmod 700 "$store"','log="$store/runs.log"',"","# cron starts a script with little more than /usr/bin and /bin on its PATH:","# the usual places of node and sf are added, then the default Node.js of nvm.",'PATH="$PATH:/usr/local/bin:$HOME/.local/bin"',"node_ok() {"," command -v node >/dev/null 2>&1 &&",` node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > ${Ht.major} || (a === ${Ht.major} && b >= ${Ht.minor}) ? 0 : 1)'`,"}","if ! node_ok || ! command -v sf >/dev/null 2>&1; then",' nvm_sh="${NVM_DIR:-$HOME/.nvm}/nvm.sh"',' if [ -s "$nvm_sh" ]; then',' . "$nvm_sh" >/dev/null 2>&1'," nvm use --silent default >/dev/null 2>&1 || true"," fi","fi",`say() { printf '%s %s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$log" >&2; }`,"if ! node_ok; then",` say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH ($PATH), nor through nvm: nothing ran. Install it, or add its folder to PATH at the top of this script."`," exit 127","fi","if ! command -v sf >/dev/null 2>&1; then",' say "The Salesforce CLI (sf) is not found on this PATH ($PATH): nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH at the top of this script."'," exit 127","fi",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, read from here or from the environment.",'# cron gives a script no environment of yours: set values in "$store/env",',"# one `export NAME='value'` a line, in a file only you can read (chmod 600).",'if [ -f "$store/env" ]; then . "$store/env"; fi');for(let l of c)u.push(`# The alias, on this machine, of org "${gt(l.label)}", which has none of its own`,"# (sf alias set <alias>=<its username>).",`${l.slot}="\${${l.slot.toUpperCase()}:-}"`);u.push("missing=()");for(let l of c)u.push(`[ -n "$${l.slot}" ] || missing+=(${Ut(`${l.slot} (the alias of org "${gt(l.label)}")`)})`);for(let l of e.variables)u.push(`[ -n "\${${l.env}:-}" ] || missing+=(${Ut(`${l.env} (variable "${gt(l.name)}"${l.secret?", a secret":""})`)})`);u.push('if [ "${#missing[@]}" -gt 0 ]; then',' say "Not set, so nothing ran: ${missing[*]}. Set each in this script or in $store/env."'," exit 2","fi","")}return u.push('args=(pipeline run --file "$file" --triggered-by schedule --fail-on-partial)',...c.map(l=>`args+=(--org ${Ut(`${l.key}=`)}"$${l.slot}")`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...kp(e,"#",(l,g)=>`args+=(${l} ${Ut(g)})`),"",'say "start"',`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}" >>"$log" 2>&1`,"code=$?",'say "exit $code"','exit "$code"',""),{runner:"cron",fileName:n,text:u.join(`
|
|
10
|
-
`),...i!==void 0?{schedule:i.kind==="line"?{...i,text:`${i.text} /bin/bash /path/to/${n}`}:i}:{}}}function zE(s){let e=sl(s);if("refused"in e)return e.reason;if(e.daysOfMonth!=="*"||e.months!=="*")return"It names days of the month or months, which a daily or weekly trigger does not: create the task in Task Scheduler by hand.";let t=e.hours.flatMap(n=>e.minutes.map(o=>`${String(n).padStart(2,"0")}:${String(o).padStart(2,"0")}`));if(t.length>_E)return`It starts ${t.length} times a day; a task of that many daily triggers is better made with a repetition: create the task in Task Scheduler by hand.`;let r=e.daysOfWeek==="*"?void 0:e.daysOfWeek.map(n=>UE[n]).join(",");return t.map(n=>r===void 0?`New-ScheduledTaskTrigger -Daily -At ${Yt(n)}`:`New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${r} -At ${Yt(n)}`)}function GE(s){let{input:e,leftOut:t}=Op(s),r=Rp(e.fileName),n=`${r}.ps1`,o=Qs(e.pipelineId),i;if(e.schedule!==null){let l=vp(Xi(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now));if(l.kind!=="line")i=l;else{let g=zE(l.text);i=typeof g=="string"?{kind:"manual",reason:g}:{...l,text:[`# In PowerShell, from the folder that holds ${n}, once:`,`$action = New-ScheduledTaskAction -Execute 'pwsh' -Argument ('-NoProfile -File "{0}"' -f (Join-Path $PWD ${Yt(n)}))`,"$triggers = @(",...g.map(p=>` ${p}`),")",`Register-ScheduledTask -TaskName ${Yt(`SandForge ${r}`)} -Action $action -Trigger $triggers`].join(`
|
|
11
|
-
`)}}}let a=i===void 0?["This pipeline has no schedule: run this script by hand, or from a scheduler of your own."]:i.kind==="line"?[`Its schedule, as Task Scheduler reads it, in ${i.timezone}:`,...i.text.split(`
|
|
12
|
-
`).map(l=>` ${l}`),...WS(i)]:i.kind==="manual"?[`Its schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, as Task Scheduler reads it:`,gt(i.reason)]:["Its schedule cannot be written for this machine's clock:",gt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs PowerShell 7 (pwsh), Node.js`,`${Ht.major}.${Ht.minor} or later and the Salesforce CLI (sf), signed in to each org of the`,"pipeline under its alias. Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=zS(e),u=[...Sp(e,d).map(l=>l===""?"#":`# ${l}`),"$ErrorActionPreference = 'Continue'","","$here = Split-Path -Parent $MyInvocation.MyCommand.Path",`$file = Join-Path $here ${Yt(e.fileName)}`,"$journal = if ($env:SANDFORGE_JOURNAL_DIR) { $env:SANDFORGE_JOURNAL_DIR } else { Join-Path $HOME '.sandforge' }",`$store = Join-Path (Join-Path $journal 'pipelines') ${Yt(o)}`,"New-Item -ItemType Directory -Force -Path $store | Out-Null","$log = Join-Path $store 'runs.log'","function Say([string] $line) {"," $stamped = '{0} {1}' -f ([DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')), $line"," Add-Content -Path $log -Value $stamped"," [Console]::Error.WriteLine($stamped)","}","","if ($PSVersionTable.PSVersion.Major -lt 7) {",' Say ("PowerShell 7 (pwsh) runs this script, not PowerShell {0}: nothing ran. Start it with pwsh." -f $PSVersionTable.PSVersion)'," exit 127","}","$node = Get-Command node -ErrorAction SilentlyContinue","$nodeOk = $false","if ($node -and ((& node --version) -match '^v(\\d+)\\.(\\d+)')) {"," $major = [int] $Matches[1]",` $nodeOk = ($major -gt ${Ht.major}) -or ($major -eq ${Ht.major} -and [int] $Matches[2] -ge ${Ht.minor})`,"}","if (-not $nodeOk) {",` Say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH: nothing ran. Install it, or add its folder to PATH."`," exit 127","}","if (-not (Get-Command sf -ErrorAction SilentlyContinue)) {",' Say "The Salesforce CLI (sf) is not found on this PATH: nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH."'," exit 127","}",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, set here or in the environment.");for(let l of c)u.push(`# The alias, on this machine, of org "${gt(l.label)}", which has none of its own.`,`$${l.slot} = $env:${l.slot.toUpperCase()}`);u.push("$missing = @()");for(let l of c)u.push(`if (-not $${l.slot}) { $missing += ${Yt(`${l.slot} (the alias of org "${gt(l.label)}")`)} }`);for(let l of e.variables)u.push(`if (-not $env:${l.env}) { $missing += ${Yt(`${l.env} (variable "${gt(l.name)}"${l.secret?", a secret":""})`)} }`);u.push("if ($missing.Count -gt 0) {"," Say ('Not set, so nothing ran: {0}. Set each in this script or in the environment.' -f ($missing -join ', '))"," exit 2","}","")}return u.push("$runArgs = @('pipeline', 'run', '--file', $file, '--triggered-by', 'schedule', '--fail-on-partial')",...c.map(l=>`$runArgs += @('--org', (${Yt(`${l.key}={0}`)} -f $${l.slot}))`),...e.variables.map(l=>`$runArgs += @('--var-env', ${Yt(`${l.name}=${l.env}`)})`),...kp(e,"#",(l,g)=>`$runArgs += @('${l}', ${Yt(g)})`),"","Say 'start'",`& npx -y ${Yt(`sandforge@${e.sandforgeVersion}`)} @runArgs *>> $log`,"$code = $LASTEXITCODE",'Say "exit $code"',"exit $code",""),{runner:"taskScheduler",fileName:n,text:u.join(`
|
|
13
|
-
`),...i!==void 0?{schedule:i}:{}}}function JE(s){let e=sl(s);if("refused"in e)return!1;let t=e.minutes;if(t.length===1)return!1;for(let r=0;r<t.length;r+=1)if((r+1<t.length?t[r+1]:t[0]+60)-t[r]<qS)return!0;return!1}function VE(s){let{input:e,leftOut:t}=Op(s),n=`${Rp(e.fileName)}.yml`,o=Qs(e.pipelineId),i=e.schedule===null?void 0:vp(Xi(e.schedule.cron,e.schedule.timezone,e.schedule.timezone,e.now)),a=e.orgs.map((l,g)=>{let p=l.alias??`pipeline-org-${g+1}`;return{...l,ciAlias:p,secret:HE(p)}}),d=l=>l===""?"#":`# ${l}`,c=[...Sp(e,[`Save it as .github/workflows/${n} of a private repository, and commit`,`${e.fileName} at the repository's root. Each org signs in from a repository secret:`,...a.map(l=>` ${l.secret}: the sfdx auth URL of "${gt(l.label)}" (sf org auth show-sfdx-auth-url --target-org ${l.alias??"<its username>"} --json, its result.sfdxAuthUrl)`),...e.variables.map(l=>` ${l.env}: variable "${gt(l.name)}"${l.secret?" (a secret)":""}`),"","GitHub starts a schedule late when its runners are busy, the start of each hour most of","all, and may drop it under heavy load; it disables the schedules of a public repository",'after 60 days without activity (docs.github.com, "Events that trigger workflows").',...i?.kind==="refused"?["","The pipeline's schedule cannot be written for GitHub:",gt(i.reason)]:[],...i?.kind==="line"&&JE(i.text)?["",`GitHub starts a schedule every ${qS} minutes at most, whatever its line says.`]:[],...t.length>0?["",...t]:[]]).map(d),`name: ${Vo(`SandForge pipeline: ${gt(e.pipelineName)}`)}`,"","on:"];i?.kind==="line"&&c.push(" schedule:",` - cron: ${Vo(i.text)}`,` timezone: ${Vo(i.timezone)}`),c.push(" workflow_dispatch:","","# One run of the pipeline at a time: a run lock keeps one machine to one run, not two jobs.","concurrency:",` group: ${Vo(`sandforge-pipeline-${o}`)}`," cancel-in-progress: false","","permissions:"," contents: read","","jobs:"," run:"," runs-on: ubuntu-latest"," steps:"," - uses: actions/checkout@v4"," - uses: actions/setup-node@v4"," with:"," node-version: 22"," - name: Install the Salesforce CLI"," run: npm install -g @salesforce/cli"),a.length>0&&c.push(" - name: Sign in to the pipeline's orgs"," env:",...a.map(l=>` ${l.secret}: \${{ secrets.${l.secret} }}`)," # The URLs go to a private folder removed when this shell exits, a failed sign-in too."," run: |"," umask 077"," auth_dir=$(mktemp -d)",` trap 'rm -rf "$auth_dir"' EXIT`,...a.flatMap((l,g)=>[` printf '%s' "$${l.secret}" > "$auth_dir/org-${g+1}.txt"`,` sf org login sfdx-url --sfdx-url-file "$auth_dir/org-${g+1}.txt" --alias ${Ut(l.ciAlias)}`])),c.push(" # The Sync watermarks, the confirmations and the history of earlier runs."," - uses: actions/cache@v4"," with:"," path: .sandforge",` key: ${Vo(`sandforge-pipeline-${o}-\${{ github.run_id }}`)}`,` restore-keys: ${Vo(`sandforge-pipeline-${o}-`)}`),e.rewinds.length>0&&c.push(" # A Rewind step rewinds to a checkpoint kept on the machine of the run: import it"," # here first (sandforge checkpoint import), from a file you keep apart, with its key."," # - name: Import the checkpoint a Rewind step names",` # run: npx -y sandforge@${e.sandforgeVersion} checkpoint import --file <checkpoint file>`);let u=[`args=(pipeline run --file ${Ut(e.fileName)} --triggered-by "$TRIGGERED_BY" --fail-on-partial)`,...a.filter(l=>l.alias===void 0).map(l=>`args+=(--org ${Ut(`${l.key}=${l.ciAlias}`)})`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...kp(e,"#",(l,g)=>`args+=(${l} ${Ut(g)})`),`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}"`];return c.push(" - name: Run the pipeline"," env:"," SANDFORGE_JOURNAL_DIR: ${{ github.workspace }}/.sandforge"," TRIGGERED_BY: ${{ github.event_name == 'schedule' && 'schedule' || 'manual' }}",...e.variables.map(l=>` ${l.env}: \${{ secrets.${l.env} }}`)," run: |",...u.map(l=>` ${l}`),""),{runner:"githubActions",fileName:n,text:c.join(`
|
|
14
|
-
`),...i!==void 0?{schedule:i}:{}}}function GS(s){return{cron:WE(s),taskScheduler:GE(s),githubActions:VE(s)}}var KE={"pipeline.timeout":3e5,"sync.maxRecordsPerObject":5e4,"sync.defaultBatchSize":200,"seed.defaultBatchSize":200,"backup.maxRecordsPerObject":5e4,"backup.maxCount":10,"backup.maxAgeDays":30,"safety.auditLogging":!0,"safety.confirmAboveRecords":2e3,"grappe.enabled":!1,"grappe.autoActivateThreshold":1e4,"grappe.grappeSize":5e3},XE=new Set(["seed","anonymize","rewind","restore","delete"]),YE={sandbox_refresh:"sandbox refresh",event:"event",webhook:"webhook",deployment_complete:"deployment"},QE="prebuilt-",ZE="tpl-";function ei(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0}function $r(s){return typeof s=="string"&&s.trim()!==""?s:void 0}function vd(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function ti(s,e){return vd(s,e)?s[e]:void 0}function Zs(s){return JSON.parse(JSON.stringify(s))}function eP(s){switch(Wi(s.orgType??"",s.metadata?.edition)){case"Sandbox":return"sandbox";case"Scratch":return"scratch";case"Developer":return"developer";default:return"production"}}function tP(s){let e=eP(s),t=Zu(s.alias,s.username)?s.alias?.trim():void 0,r=s.organizationName?.trim();return{...t!==void 0?{alias:t}:{},organizationId:s.orgId??"",kind:e,staging:s.staging===!0&&e==="sandbox",...r&&Zu(r,s.username)?{name:r}:{}}}function Ip(s,e){return e.alias??e.name??s}function Rd(s,e,t,r){return{exported:!1,pipelineId:s,code:e,message:t,...r?{issues:r}:{}}}function rP(s,e){let t=[];return s.forEach((r,n)=>{let o=ei(r.config)??{};if(r.type==="sync"){let a=e.get($r(o.configId)??""),d=$r(a?.sourceOrgId),c=$r(a?.targetOrgId);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:!1}),c!==void 0&&t.push({orgId:c,stepIndex:n,stepName:r.name,writes:!0});return}let i=vd(ol,r.type)?ol[r.type]??[]:[];for(let a of i){let d=$r(o[a]);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:XE.has(r.type)})}}),t}function nP({defaultValue:s,...e}){return e}function oP(s){let e=new Set,t=new Map;for(let r of s){let n=`SANDFORGE_VAR_${r.name.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"VALUE"}`,o=n;for(let i=2;e.has(o);i+=1)o=`${n}_${i}`;e.add(o),t.set(r.name,o)}return t}function sP(s,e){let t=(s.triggers??[]).filter(n=>n.type==="schedule"&&(n.enabled||s.runsOutside!==void 0)&&$r(n.config?.cron)!==void 0);if(t.length>1)return{many:t.length};let[r]=t;return r?{cron:(r.config.cron??"").trim(),timezone:$r(r.config.timezone)?.trim()??e}:null}function iP(s){let e={};for(let t of Object.keys(nh)){let r=KE[t],n=s.setting(t,r);n===r||n===void 0||n===null||(e[t]=n)}return e}function ri(s,e,t={}){return{code:s,text:e,...t}}function JS(s){let{pipeline:e}=s,t=e.id,r=Zs(e.steps??[]).map(p=>({...p,config:ei(p.config)??{}})),n=sP(e,s.machineTimezone);if(n!==null&&"many"in n)return Rd(t,"SCHEDULES_MANY",`Pipeline "${e.name}" has ${n.many} schedules, and a pipeline file carries one: keep one schedule, save, and export again.`);let o={},i={},a={};for(let p of r){let f=p.config;if(p.type==="sync"){let m=$r(f.configId);if(m===void 0||vd(o,m))continue;let y=ei(s.syncConfig(m));if(!y)return Rd(t,"SYNC_CONFIG_UNKNOWN",`Sync step "${p.name}" runs the configuration "${m}", which is no longer saved: pick a saved configuration in the step, save the pipeline, and export again.`);o[m]={...Zs(y),id:m}}let h=$r(f.templateId);if(p.type==="seed"&&h&&!h.startsWith(QE)){let m=ei(s.seedTemplate(h));m&&(i[h]={...Zs(m),id:h})}if(p.type==="anonymize"&&h&&!h.startsWith(ZE)){let m=ei(s.maskingTemplate(h));m&&(a[h]={...Zs(m),id:h})}}let d=rP(r,new Map(Object.entries(o))),c={},u=new Map;for(let p of d){if(vd(c,p.orgId))continue;let f=s.org(p.orgId);if(!f)return Rd(t,"ORG_UNKNOWN",`Step "${p.stepName}" names an org that is no longer registered in SandForge: pick an org in the step, or in its Sync configuration, save, and export again.`);c[p.orgId]=tP(f),u.set(p.orgId,f.authMethod!=="usernamePassword")}let l=oP(e.variables??[]),g=Zs(e.variables??[]).map(p=>p.type==="secret"?nP(p):p);return{pipelineId:t,fileName:sh(e.name),schedule:n,orgs:c,cliHolds:u,uses:d,syncConfigs:o,seedTemplates:i,maskingTemplates:a,settings:iP(s),steps:r,variables:g,envs:l}}function VS(s,e,t){return s.checkedWhereItRuns!==!0&&e.type==="rewind"&&t!==void 0&&(t===jn(e.name,"never")||t===jn(e.name,"changed"))}function aP(s,e){let t=[],r=[],n=o=>e.uses.filter(i=>i.stepIndex===o&&i.writes).map(i=>i.orgId);return e.steps.forEach((o,i)=>{let a=[],d=(f,h)=>{a.push(f),t.push(ri(f,h,{step:o.name}))},c=s.stepRefusal?.(o,i),u=VS(s,o,c)?void 0:c,l=n(i).find(f=>ti(e.orgs,f)?.kind==="production"),g="runs",p;if(u!==void 0)g="refused",p=u,d("STEP_REFUSED",u);else if(l!==void 0){g="refused";let f=ti(e.orgs,l);p=`Step "${o.name}" writes to "${f?Ip(l,f):l}", a production org: the command line never writes to a production org, whatever an Approval answers.`,d("STEP_REFUSED",p)}else if(o.type==="approval")g="asks",e.uses.some(h=>h.stepIndex>i&&h.writes&&ti(e.orgs,h.orgId)?.staging===!0)?d("STAGING_NEEDS_PERSON",`Approval step "${o.name}" stands before a write to a sandbox marked Staging: only a person at a terminal answers it, never --approve.`):d("APPROVAL_NEEDS_PERSON",`Approval step "${o.name}" asks a person: at the terminal of the run, or answered ahead with --approve "${o.name}" for a run with no one at a terminal.`);else if(o.type==="rewind"){g="asks";let f=$r(o.config.orgId),h=f!==void 0?ti(e.orgs,f):void 0;d("REWIND_NEEDS_CONFIRMATION",`Rewind step "${o.name}" runs once its org's alias is confirmed on the machine of the run: by "sandforge pipeline confirm" at a terminal, or with --confirm-rewind ${h?.alias??"<alias>"}.`),d("REWIND_CHECKPOINT_ELSEWHERE",`Rewind step "${o.name}" rewinds to a checkpoint kept on this machine: on another, import it first (sandforge checkpoint import).`)}else o.type==="notification"&&d("NOTIFICATION_PRINTED",`Notification step "${o.name}" prints its message in the run's output: there is no VS Code window to show it in.`);r.push({stepId:o.id,name:o.name,type:o.type,fate:g,notes:a,...p!==void 0?{refusal:p}:{}})}),{steps:r,notes:t}}function dP(s,e){let t=[];for(let[r,n]of Object.entries(e.orgs))if(n.alias===void 0&&t.push(ri("ORG_NO_ALIAS",`Org "${Ip(r,n)}" has no alias of its own: give it one with "sf alias set <alias>=<its username>", then run with --org ${r}=<alias>.`,{org:r})),e.cliHolds.get(r)===!1){let o=n.kind==="sandbox"?" --instance-url https://test.salesforce.com":"";t.push(ri("ORG_NOT_SIGNED_IN",`The Salesforce CLI of this machine does not hold org "${Ip(r,n)}": SandForge connected it with a username and password. Sign in to it on the machine of the run: "sf org login web --alias ${n.alias??"<alias>"}${o}".`,{org:r}))}for(let r of s.pipeline.variables??[])r.type==="secret"&&t.push(ri("SECRET_NOT_EXPORTED",`Variable "${r.name}" is a secret: its value is not in this file. Give it as the run starts with --var-env ${r.name}=${e.envs.get(r.name)}.`));for(let r of s.pipeline.triggers??[]){let n=YE[r.type];!r.enabled||n===void 0||t.push(ri("TRIGGER_NOT_EXPORTED",`Its ${n} trigger starts it in the editor alone: a run of this file starts on its schedule, or by hand.`))}return t}function cP(s){return Object.entries(s.orgs).map(([e,t])=>{let r=s.uses.filter(a=>a.orgId===e),n=new Set(r.filter(a=>a.writes).map(a=>a.stepIndex)),o=[...new Set(r.filter(a=>a.writes).map(a=>a.stepName))],i=[...new Set(r.filter(a=>!n.has(a.stepIndex)).map(a=>a.stepName))];return{key:e,...t.alias!==void 0?{alias:t.alias}:{},...t.name!==void 0?{name:t.name}:{},kind:t.kind,staging:t.staging,cliHolds:s.cliHolds.get(e)??!1,writtenBy:o,readBy:i}})}function uP(s){return s.variables.map(e=>{let t=e.type!=="secret"&&e.defaultValue!==void 0,r=e.type==="secret"||e.required&&!t,n=s.envs.get(e.name);return{name:e.name,type:e.type,required:e.required,valued:t,...r&&n!==void 0?{env:n}:{}}})}function KS(s,e,t){let{pipeline:r}=s;return oh({exportedAt:s.exportedAt,sandforgeVersion:s.sandforgeVersion,pipeline:{id:r.id,name:r.name,description:r.description??"",steps:e.steps.map(n=>({...n})),variables:e.variables,tags:r.tags??[]},schedule:e.schedule,orgs:e.orgs,syncConfigs:e.syncConfigs,seedTemplates:e.seedTemplates,maskingTemplates:e.maskingTemplates,settings:e.settings,notes:t})}function XS(s){let e=s.pipeline.id,t=JS(s);if("exported"in t)return t;let{steps:r,notes:n}=aP(s,t),o=[...n,...dP(s,t)],i=KS(s,t,o);if(!i.ok)return Rd(e,"FILE_INVALID",`The pipeline file would not read: ${i.issues.length} ${i.issues.length===1?"issue":"issues"}. Fix each where the pipeline, its orgs or the settings hold it, and export again.`,i.issues);let a=cP(t),d=uP(t),c=a.map(g=>({key:g.key,...g.alias!==void 0?{alias:g.alias}:{},label:g.alias??g.name??g.key})),u=d.flatMap(g=>g.env!==void 0?[{name:g.name,env:g.env,secret:g.type==="secret"}]:[]),l={fileName:t.fileName,text:i.text,digest:i.file.digest,schedule:t.schedule,steps:r,orgs:a,variables:d,launchers:GS({pipelineId:e,pipelineName:s.pipeline.name,fileName:t.fileName,sandforgeVersion:s.sandforgeVersion,exportedAt:s.exportedAt,schedule:t.schedule,machineTimezone:s.machineTimezone,now:s.now,orgs:c,variables:u,approvals:r.filter(g=>g.type==="approval"&&g.fate==="asks").map(g=>({name:g.name,staging:g.notes.includes("STAGING_NEEDS_PERSON")})),rewinds:t.steps.filter(g=>g.type==="rewind").map(g=>{let p=$r(g.config.orgId),f=p!==void 0?ti(t.orgs,p)?.alias:void 0;return{name:g.name,...f!==void 0?{alias:f}:{}}})}),notes:o,problems:(s.problems??[]).filter(g=>!t.steps.some(p=>VS(s,p,g)))};return{exported:!0,pipelineId:e,...l}}function YS(s){let e=JS(s);if("exported"in e)return;let t=KS(s,e,[]);return t.ok?t.file.digest:void 0}import{randomUUID as IL}from"node:crypto";import{join as AL}from"node:path";import{randomBytes as lP,randomUUID as Xo}from"node:crypto";import{lstat as pP,rename as gP,rm as fP,stat as hP}from"node:fs/promises";import{hostname as mP}from"node:os";import{basename as oi,dirname as tk,join as yP,sep as wP}from"node:path";var bP=new Set(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"]),xr="checkpoint",RP=8,vP=6e4,pr="CANCELLED",SP={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},kP={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function Ap(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var OP=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function Tp(s,e,t,r){let n=t(s),o=(e??[]).map(t);return o.length===0?{done:!1,refusal:n}:r?{done:!1,refusal:{code:n.code,message:rk([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function rk(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(OP,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var IP=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),Dr=class extends Error{constructor(t,r,n,o=[]){super(r);this.code=t;this.result=n;this.alsoRefused=o;this.name="CheckpointStepRefused"}code;result;alsoRefused};function QS(s){return s.deleted.some(e=>e.deleted>0)||s.restored.some(e=>e.restored+(e.restoredWithout??0)>0)||s.undeleted.some(e=>e.undeleted>0)||(s.recreated??[]).some(e=>e.created>0)}async function AP(){let[s,e,t,r,n,o,i,a,d,c,u,l,g]=await Promise.all([import("./chunk-SBDF4AE5.mjs"),import("./chunk-XMJRXXUN.mjs"),import("./chunk-YVVPJRZC.mjs"),import("./chunk-NEKNAILD.mjs"),import("./chunk-OFQOKSEW.mjs"),import("./chunk-73SLYGWD.mjs"),import("./chunk-IVDBVWKK.mjs"),import("./chunk-MAOUFJ47.mjs"),import("./chunk-RZXEO5IE.mjs"),import("./chunk-K2WOT75I.mjs"),import("./chunk-SVNSAHG3.mjs"),import("./chunk-GNCEHAJY.mjs"),import("./chunk-OXIIKAUZ.mjs")]);return{pageEmailsRefusal:u.pageEmailsRefusal,planSelection:a.planSelection,snapshotRowsOf:a.snapshotRowsOf,rewindWriters:a.rewindWriters,boundsRefusals:d.boundsRefusals,selectionDiff:d.selectionDiff,rewindStepsOf:d.rewindStepsOf,notConfirmedRefusal:d.notConfirmedRefusal,undeletableUnattendedRefusal:d.undeletableUnattendedRefusal,REWIND_STEP_WORDS:d.REWIND_STEP_WORDS,REWIND_MUTING_STEP_WORDS:d.REWIND_MUTING_STEP_WORDS,guardCheckpoint:o.guardCheckpoint,newArchiveKey:i.newArchiveKey,archiveKeyText:i.archiveKeyText,parseArchiveKey:i.parseArchiveKey,ARCHIVE_EXTENSION:i.ARCHIVE_EXTENSION,exportCheckpointArchive:i.exportCheckpointArchive,CheckpointExportError:i.CheckpointExportError,readArchiveHeader:i.readArchiveHeader,importCheckpointArchive:i.importCheckpointArchive,DEFAULT_KEEP_DAYS:s.DEFAULT_KEEP_DAYS,openCheckpointStore:s.openCheckpointStore,defaultCheckpointStoreRoot:s.defaultCheckpointStoreRoot,scratchOrgExpired:s.scratchOrgExpired,previewDirOf:s.previewDirOf,CheckpointStoreError:s.CheckpointStoreError,takeCheckpoint:e.takeCheckpoint,scopeCheckpoint:e.scopeCheckpoint,takeOrgOf:e.takeOrgOf,CheckpointTakeStopped:e.CheckpointTakeStopped,previewCheckpoint:t.previewCheckpoint,rewindOrg:r.rewindOrg,rewindOrgOf:r.rewindOrgOf,RewindStopped:r.RewindStopped,undoCheckpoint:n.undoCheckpoint,UndoStopped:n.UndoStopped,beforeRunScopeOf:c.beforeRunScopeOf,beforeRunAskedOf:c.beforeRunAskedOf,beforeRunKeepDaysOf:c.beforeRunKeepDaysOf,beforeRunDiskRefusal:c.beforeRunDiskRefusal,beforeRunOutcomeOf:c.beforeRunOutcomeOf,freeBytesOf:c.freeBytesOf,scopeBeforeRun:c.scopeBeforeRun,settleBeforeRun:c.settleBeforeRun,ReplayStore:l.ReplayStore,defaultReplayStoreRoot:l.defaultReplayStoreRoot,loadToRemove:g.loadToRemove,loadRecordsInfo:g.loadRecordsInfo}}var Oe=class extends Error{constructor(t,r,n=!1,o,i,a=[]){super(r);this.code=t;this.retryable=n;this.result=o;this.refusal=i;this.alsoRefused=a;this.name="Refused"}code;retryable;result;refusal;alsoRefused};function Sd(s){return s instanceof Rt?s:s instanceof Oe?s.code===pr?new Rt(s.message):new Dr(s.code,s.alsoRefused.length>0?rk([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function ZS(s){try{return(await hP(s)).isDirectory()}catch{return!1}}function Nt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var ek=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ni(s,e){if(e===void 0)return;let t=new Map(s.objects.map(({objectApiName:n})=>[n.toLowerCase(),n])),r=e.filter(n=>!t.has(n.toLowerCase()));if(r.length>0)throw new Oe("NOT_HELD",`The checkpoint '${s.name}' holds no ${r.join(", ")}: a rewind is limited to objects it holds. No record was read or written.`);return[...new Set(e.flatMap(n=>t.get(n.toLowerCase())??[]))]}function ft(s){return ye(s)}function TP(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,oi(n));for(let n of t){let o=tk(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${wP}`,"").replaceAll(o,oi(o)))}return r}function EP(s){return{formatVersion:s.formatVersion,checkpointFormat:s.checkpointFormat,sandforgeVersion:s.sandforgeVersion,organizationId:s.organizationId,orgTier:s.orgTier,checkpointId:s.checkpointId,takenAt:s.takenAt,records:s.records,objects:s.objects,files:s.files,bytes:s.bytes,...s.dataStorageMaxMB!==void 0?{dataStorageMaxMB:s.dataStorageMaxMB}:{},...s.staging===!0?{staging:s.staging}:{}}}function PP(s){let e=s.reason==="notAFolder"?"it is a file, not a folder":s.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${s.detail!==void 0?` (${s.detail})`:""}`;return`The checkpoints cannot be kept in ${s.path}: ${e}.`}function Ep(s){return`${s.operation==="take"?"a checkpoint is being taken":s.operation==="rewind"?"a rewind is writing":s.operation==="undo"?"an undo is writing":s.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${s.pid} on ${s.host})`}var kd=class{constructor(e,t={},r=xo){this.deps=e;this.writers=t;this.self=r}deps;writers;self;loaded;store;replays;liveTracker;syncRuns;seedRuns;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;previewsAnswered;previewReads=new Map;changeListeners=new Set;importFiles=new Map;muteLeases={};freeBytes;setLiveOperationTracker(e){this.liveTracker=e}setRunFiles(e,t){e==="sync"?this.syncRuns=t:this.seedRuns=t}setStore(e){this.store=Promise.resolve(e)}setReplayStore(e){this.replays=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setFreeBytes(e){this.freeBytes=e}rewindFromPreviewsAnswered(){this.previewsAnswered??=new Map}async handle(e){if(!bP.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"checkpoint:list":return await this.handleList(e),!0;case"checkpoint:scope":return await this.handleScope(e),!0;case"checkpoint:take":return await this.handleTake(e),!0;case"checkpoint:preview":return await this.handlePreview(e),!0;case"checkpoint:plan-selection":return await this.handlePlanSelection(e),!0;case"checkpoint:rewind":return await this.handleRewind(e),!0;case"checkpoint:undo":return await this.handleUndo(e),!0;case"checkpoint:delete":return await this.handleDelete(e),!0;case"checkpoint:keep":return await this.handleKeep(e),!0;case"checkpoint:rename":return await this.handleRename(e),!0;case"checkpoint:ignore-fields":return await this.handleIgnoreFields(e),!0;case"checkpoint:rewinds":return await this.handleRewinds(e),!0;case"checkpoint:export":return await this.handleExport(e),!0;case"checkpoint:import-read":return await this.handleImportRead(e),!0;case"checkpoint:import":return await this.handleImport(e),!0;default:return!1}}async sweep(){try{let t=await(await this.openedStore()).sweep();for(let r of t.checkpoints)this.deps.log(`[INFO] Removed checkpoint '${r.name}' of ${r.alias??r.organizationId}, taken ${r.takenAt}: kept until ${r.expiresAt}`+(r.undoUntil!==void 0?`; the undo of its last rewind, open until ${r.undoUntil}, went with it`:""));for(let r of t.journals)this.deps.log(`[INFO] Removed the journal of rewind ${r.rewindId} of checkpoint '${r.name}': it could be undone until ${r.undoUntil}`);for(let r of t.skipped)this.deps.log(`[INFO] Checkpoints of ${r} not swept: a take, a rewind or an undo runs`);t.checkpoints.length>0&&this.checkpointsChanged()}catch(e){this.deps.log(`[WARN] Expired checkpoints were not removed: ${I(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!ek.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!vo(t))return;let r=await this.openedStore(),n=(await this.listOfOrg(r,e)).find(o=>o.valid&&o.checkpoint!==void 0)?.checkpoint;return n?{checkpointId:n.checkpointId,name:n.name,takenAt:n.takenAt}:void 0}onCheckpointsChanged(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}async scopeBeforeRun(e,t={}){let r=this.registeredOrg(e.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r);return n.scopeBeforeRun({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.beforeRunWriting(r,t),...this.freeBytes?{freeBytes:this.freeBytes}:{}},this.takeRequestOf(r,{mode:"picked"}),this.beforeRunRequestOf(n,e))}async takeBeforeRun(e,t={},r={}){let n=`checkpoint:before-run:${Xo()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),u=(f,h={})=>{let{taken:m}=h;Q(this.deps,{action:"checkpoint_take",module:xr,operationId:n,orgId:o.id,outcome:f,beforeRun:{module:e.module,operationId:e.operationId},...h.code!==void 0?{code:h.code}:{},details:m?{checkpointId:m.checkpointId,records:m.records,objects:m.objects.length,bytes:m.bytes}:{}})};if(r.planned!==void 0){let f=i.beforeRunDiskRefusal(r.planned.estimate.bytes,await(this.freeBytes??i.freeBytesOf)(a.root));if(f!==void 0)return u("stopped",{code:f.code}),{taken:!1,refusal:f}}let l=await this.connect(o);if(r.signal?.aborted)return u("cancelled"),{taken:!1,stopped:!0};let g;try{g=await this.take(n,i,a,l,o,i.beforeRunAskedOf(c,d),{description:`Checkpoint first: taking a checkpoint of ${ft(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(f){if(f instanceof Oe&&f.code===pr)return u("cancelled"),{taken:!1,stopped:!0};if(f instanceof Oe&&f.refusal!==void 0)return u("stopped",{code:f.refusal.code}),{taken:!1,refusal:f.refusal};throw u("failure"),f}let p=await i.beforeRunOutcomeOf(a,c,g);return p.taken?u("success",{taken:p.checkpoint}):(this.checkpointsChanged(),u("stopped",{..."refusal"in p?{code:p.refusal.code}:{}})),p}async settleBeforeRun(e,t){let r=await this.modules(),n=await this.openedStore(),o=await r.settleBeforeRun(n,e,t);return o.notDeleted!==void 0&&this.deps.log(`[WARN] ${o.notDeleted}`),o.info.state==="deleted"&&(this.deps.log(`[INFO] Deleted checkpoint '${e.name}', taken before a run that wrote nothing`),this.checkpointsChanged()),o.info}beforeRunRequestOf(e,t){let r=this.deps.services?.getSandforgeSetting?.("checkpoint.beforeRunKeepDays",mf.default);return{module:t.module,written:t.written,running:t.running,request:t.request,operationId:t.operationId,tool:"panel",keepDays:e.beforeRunKeepDaysOf(t.request.keepDays,r)}}beforeRunWriting(e,t){return this.runWriting(e.id,ft(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${Xo()}`;try{let n=bn.safeParse(e.config);if(!n.success)throw new Oe("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${n.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let o=n.data,i=this.registeredOrg(o.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(t?.aborted)throw new Oe(pr,new a.CheckpointTakeStopped().message);let{checkpoint:u}=await this.take(r,a,d,c,i,{...o.name!==void 0?{nameWithDate:o.name}:{},mode:o.mode,...o.objects!==void 0?{objects:o.objects}:{},...o.excluded!==void 0?{excluded:o.excluded}:{},...o.maxTotal!==void 0?{maxTotal:o.maxTotal}:{},keepDays:o.keepDays,...o.ignoredFields!==void 0?{ignoredFields:o.ignoredFields}:{}},{description:`Pipeline '${e.origin.pipeline}': taking a checkpoint of ${ft(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:u.checkpointId,name:u.name,records:u.objects.reduce((l,g)=>l+g.records,0),objects:u.objects.length,bytes:u.bytes,movedWhileTaken:u.movedWhileTaken}}catch(n){throw Sd(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Xo()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=$t.safeParse(e.config);if(!a.success)throw new Oe("CONFIG_INVALID",`The Rewind step "${o.step}" does not read: ${a.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let d=a.data;if(n.digest!==ks(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:u,checkpoint:l}=await this.checkpointOf(c,d.checkpointId);if(!Nt(n.organizationId,l.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,l,"rewind");let g=this.registeredOrg(d.orgId);if(!Nt(g.orgId,l.org.organizationId)&&!Nt(this.deps.sandboxRefreshes?.organizationIdOf(g.id),l.org.organizationId))throw new Oe("OTHER_ORG",`The checkpoint '${l.name}' is not of ${ft(g)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let p=ni(l,d.objects),f=await this.connect(g),h=ft(g),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",g,l,"stopped",{code:bt}),new Rt(new i.RewindStopped().message)),R=(x,J=[])=>(this.audit(m,"rewind",g,l,"stopped",{code:x.code}),this.refusalOf(x,J));if(t?.aborted)throw y();let S;try{S=await i.previewCheckpoint({org:i.takeOrgOf(f),store:c,readAutomation:x=>this.readAutomation(g.id,x),runWriting:this.runWriting(g.id,h,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:l,folder:u,orgName:h,registered:g,username:g.username,...p!==void 0?{objects:p}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch(x){throw t?.aborted?y():x}if(!S.previewed)throw R(S.refusal);let w=p!==void 0?i.selectionDiff(S.diff,await i.planSelection({checkpoint:l,previewDir:i.previewDirOf(u,S.diff.previewId),readAt:S.diff.readAt,objects:new Set(p),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(l,u),...t?{signal:t}:{}})):S.diff,O=d.muteAutomation&&S.automation?Cl(S.automation,Jr(i.rewindStepsOf(w))).automation:S.automation,P=await i.boundsRefusals({orgName:h,preview:{diff:w,...O?{automation:O}:{},...S.emails?{emails:S.emails}:{},...S.emailsUncounted!==void 0?{emailsUncounted:S.emailsUncounted}:{},...S.deliverability?{deliverability:S.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(l.takenBy,await i.takeOrgOf(f).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:g.username}),[v,...b]=[...S.refusal!==void 0?[S.refusal]:[],...P.filter(x=>x.code!==S.refusal?.code)];if(v!==void 0)throw R(v,b);if(t?.aborted)throw y();let C=[],k=[],T=await this.writeAct(m,"rewind",g,l,`Pipeline '${o.pipeline}': rewinding ${h} to '${l.name}'`,async(x,J)=>{let U=await i.rewindOrg({org:i.rewindOrgOf(f),undelete:K=>f.soap.undelete(K),store:c,readAutomation:K=>this.readAutomation(g.id,K),runWriting:this.runWriting(g.id,h,"rewind","No record was read or written."),onUndeletable:K=>(C.push(...K),this.deps.log(`[WARN] checkpoint:rewind ${r}: the user may not delete ${K.map(re=>`${re.objectApiName} (${re.records})`).join(", ")} in the target, and nobody runs the pipeline to be asked: the deletion is left untouched`),Promise.resolve(!1)),onProgress:({percentage:K,step:re})=>J(K,re),signal:x,...d.muteAutomation?{mute:this.muteOf(f)}:{}},{checkpoint:l,folder:u,orgName:h,registered:g,username:g.username,previewId:S.diff.previewId,reusesPreview:S.diff,...p!==void 0?{objects:p}:{},acceptAutomation:d.acceptAutomation,acceptEmails:d.acceptEmails,acceptNoUndo:d.acceptNoUndo,acceptRecreate:d.acceptRecreate,acceptOutside:d.acceptOutside,acceptUnseen:d.acceptUnseen});return U.rewound?(k=U.notes,Ap(U)):Tp(U.refusal,U.alsoRefused,K=>K,!1)},x=>x instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:x=>C.length>0?i.undeletableUnattendedRefusal(h,C,QS(x)):void 0});return{operationId:r,checkpointId:l.checkpointId,result:T,notes:k,estimate:S.estimate}}catch(i){throw Sd(i)}}async estimateTakeForPipeline(e,t){try{let r=bn.safeParse(e.config);if(!r.success)throw new Oe("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${r.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let n=r.data,o=this.registeredOrg(n.orgId),i=await this.modules(),a=await this.openedStore(),d=await this.connect(o);if(t?.aborted)throw new Oe(pr,new i.CheckpointTakeStopped().message);let c=await i.scopeCheckpoint({org:i.takeOrgOf(d),store:a,handler:this.deps,runWriting:this.runWriting(o.id,ft(o),"take the checkpoint","No record was read."),...t?{signal:t}:{}},this.takeRequestOf(o,{mode:n.mode,...n.objects!==void 0?{objects:n.objects}:{},...n.excluded!==void 0?{excluded:n.excluded}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{}}));if(c.refusal)throw this.refusalOf(c.refusal);return{objects:c.objects.length,records:c.objects.reduce((u,l)=>u+l.records,0),leftOut:c.leftOut.length,estimate:c.estimate}}catch(r){throw Sd(r)}}async previewRewindForPipeline(e,t){let{grant:r,origin:n}=e;try{let o=await this.modules(),i=$t.safeParse(e.config);if(!i.success)throw new Oe("CONFIG_INVALID",`The Rewind step "${n.step}" does not read: ${i.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let a=i.data;if(r.digest!==ks(a)||r.checkpointId!==a.checkpointId)throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));let d=await this.openedStore(),{folder:c,checkpoint:u}=await this.checkpointOf(d,a.checkpointId);if(!Nt(r.organizationId,u.org.organizationId))throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));this.usable(o,u,"rewind");let l=this.registeredOrg(a.orgId);if(!Nt(l.orgId,u.org.organizationId)&&!Nt(this.deps.sandboxRefreshes?.organizationIdOf(l.id),u.org.organizationId))throw new Oe("OTHER_ORG",`The checkpoint '${u.name}' is not of ${ft(l)}, the org the Rewind step "${n.step}" names. No record was read or written.`);let g=ni(u,a.objects),p=await this.connect(l),f=ft(l);if(t?.aborted)throw new Oe(pr,new o.RewindStopped().message);let h=await o.previewCheckpoint({org:o.takeOrgOf(p),store:d,readAutomation:P=>this.readAutomation(l.id,P),runWriting:this.runWriting(l.id,f,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:c,orgName:f,registered:l,username:l.username,...g!==void 0?{objects:g}:{},reusesPreview:!0,...a.muteAutomation?{muteAutomation:!0}:{},acceptOutside:a.acceptOutside});if(!h.previewed)throw this.refusalOf(h.refusal);let m=g!==void 0?o.selectionDiff(h.diff,await o.planSelection({checkpoint:u,previewDir:o.previewDirOf(c,h.diff.previewId),readAt:h.diff.readAt,objects:new Set(g),acceptOutside:a.acceptOutside,heldRows:o.snapshotRowsOf(u,c),...t?{signal:t}:{}})):h.diff,y=a.muteAutomation&&h.automation?Cl(h.automation,Jr(o.rewindStepsOf(m))).automation:h.automation,R=await o.boundsRefusals({orgName:f,preview:{diff:m,...y?{automation:y}:{},...h.emails?{emails:h.emails}:{},...h.emailsUncounted!==void 0?{emailsUncounted:h.emailsUncounted}:{},...h.deliverability?{deliverability:h.deliverability}:{}},bounds:{maxRecords:a.maxRecords,refuseWhenActive:a.refuseWhenActive},accepted:a,writers:async()=>o.rewindWriters(u.takenBy,await o.takeOrgOf(p).userId()),words:a.muteAutomation?o.REWIND_MUTING_STEP_WORDS:o.REWIND_STEP_WORDS,user:l.username}),[S,...w]=[...h.refusal!==void 0?[h.refusal]:[],...R.filter(P=>P.code!==h.refusal?.code)];if(S!==void 0)throw this.refusalOf(S,w);let O=P=>m.objects.reduce((v,b)=>v+P(b),0);return{checkpointId:u.checkpointId,toDelete:O(({toDelete:P})=>P.createdSince+P.broughtBackSince+P.comesBackWithParent),toGiveBack:O(({toGiveBack:P})=>P.records),toBringBack:O(({toBringBack:P})=>P.inBin+P.withParent+P.deletedWhileTaken),toRecreate:O(({toRecreate:P})=>P??0),estimate:h.estimate}}catch(o){throw Sd(o)}}async exportCheckpoint(e){try{let t=await this.modules(),r=await this.openedStore(),{folder:n,checkpoint:o}=await this.checkpointOf(r,e.checkpointId);this.usable(t,o,"export");let i=e.key??t.newArchiveKey(),a=await t.exportCheckpointArchive({folder:n,checkpoint:o,out:e.out,key:i,sandforgeVersion:e.sandforgeVersion}),{header:d}=a;return Q(this.deps,{action:"checkpoint_export",module:xr,operationId:Xo(),orgId:this.orgOfCheckpoint(o)?.id??o.org.organizationId,outcome:"success",details:{checkpointId:o.checkpointId,records:d.records,objects:d.objects,files:d.files,bytes:a.bytes}}),{exported:!0,checkpoint:o,header:d,bytes:a.bytes,sha256:a.sha256,...e.key===void 0?{key:t.archiveKeyText(i)}:{}}}catch(t){return{exported:!1,refusal:await this.transferRefusalOf(t,"EXPORT_ERROR")}}}async readImport(e){let t=await this.importChecked(e);return"refusal"in t?{allowed:!1,...t}:{allowed:!0,header:t.read.header}}async importCheckpoint(e){let t=await this.importChecked(e),r=(d,c,u,l={})=>{Q(this.deps,{action:"checkpoint_import",module:xr,operationId:Xo(),orgId:d,outcome:c,...l.code!==void 0?{code:l.code}:{},details:{...u?{checkpointId:u.checkpointId,records:u.records,objects:u.objects}:{},...l.alreadyKept?{alreadyKept:!0}:{}}})};if("refusal"in t)return t.orgId!==void 0&&r(t.orgId,"stopped",t.header,{code:t.refusal.code}),{imported:!1,refusal:t.refusal,...t.header?{header:t.header}:{}};let{m:n,store:o,org:i,read:a}=t;try{let d=await n.importCheckpointArchive({store:o,file:e.file,read:a,key:e.key,...i.alias?{alias:i.alias}:{},keepDays:e.keepDays??n.DEFAULT_KEEP_DAYS,takenOn:{host:mP(),pid:process.pid}});if(!d.imported)return r(i.id,"stopped",a.header,{code:d.refusal.code}),{imported:!1,header:a.header,refusal:d.refusal};r(i.id,"success",a.header,d.outcome==="alreadyKept"?{alreadyKept:!0}:{}),d.outcome==="imported"&&this.checkpointsChanged();let c=ft(i);return{imported:!0,outcome:d.outcome,checkpoint:d.checkpoint,warnings:[`Rewinds of ${c} from two machines at once fight each other: the lock is per machine. Agree on who rewinds.`,"A field your user cannot see is neither compared nor written back by a rewind from this machine, and its preview names it.","The rewinds made from the machine it came from, and their Undo, stayed there."]}}catch(d){return r(i.id,"failure",a.header),{imported:!1,header:a.header,refusal:await this.transferRefusalOf(d,"IMPORT_ERROR")}}}async importChecked(e){let t,r;try{let n=await this.modules(),o=await this.openedStore(),i=this.registeredOrg(e.orgId);r=i.id;let a=await n.readArchiveHeader(e.file);if("refusal"in a)return{refusal:a.refusal,orgId:r};t=a.read.header;let d=await this.connect(i),c=await n.guardCheckpoint(d,{act:"import",orgName:ft(i),registered:i,username:i.username,organizationId:t.organizationId});if(!c.allowed){let u=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:u!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${u.slice(0,10)}: ${ft(i)} is another org now, and the checkpoint can no longer be rewound to. ${ys} Nothing was imported.`}:c.refusal,header:t,orgId:r}}return{m:n,store:o,org:i,read:a.read}}catch(n){return{refusal:await this.transferRefusalOf(n,"IMPORT_ERROR"),...t?{header:t}:{},...r!==void 0?{orgId:r}:{}}}}async transferRefusalOf(e,t){if(e instanceof Oe)return{code:e.code,message:e.message};let r=await this.modules().catch(()=>{});return r!==void 0&&e instanceof r.CheckpointExportError?{code:e.code,message:e.message}:{code:t,message:I(e)}}async handleExport(e){let t=$(cy,e,"checkpoint:error",this.deps);if(!t)return;let r=[];try{let n=this.fileDialogs("export"),o=await this.modules(),i=await this.openedStore();r.push(i.root);let{checkpoint:a}=await this.checkpointOf(i,t.checkpointId);this.usable(o,a,"export");let{checkpointId:d}=a,c=await n.pickExportFile(`${d}${o.ARCHIVE_EXTENSION}`);if(c===void 0){this.respond(e,"checkpoint:export:response",{status:"cancelled",checkpointId:d});return}r.push(c);let u=await pP(c).then(()=>!0,()=>!1),l=u?yP(tk(c),`.${oi(c)}.${lP(4).toString("hex")}.export`):c;r.push(l);let g=await this.exportCheckpoint({checkpointId:d,out:l,sandforgeVersion:n.sandforgeVersion});if(!g.exported)throw new Oe(g.refusal.code,g.refusal.message);if(u)try{await gP(l,c)}catch(p){throw await fP(l,{force:!0}),p}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:oi(c),key:g.key,records:g.header.records,objects:g.header.objects,bytes:g.bytes})}catch(n){this.fail(e,this.pathless(n,r,"EXPORT_ERROR"),"EXPORT_ERROR")}}async handleImportRead(e){let t=[];try{let r=this.fileDialogs("import"),n=await this.modules(),o=await this.openedStore();t.push(o.root);let i=await r.pickImportFile();if(i===void 0){this.respond(e,"checkpoint:import-read:response",{status:"cancelled"});return}t.push(i);let a=await n.readArchiveHeader(i);if("refusal"in a)throw this.refusalOf(a.refusal);let{header:d}=a.read,c=[],u;for(let g of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(g.id).some(h=>Nt(h,d.organizationId)))continue;let f=await this.readImport({orgId:g.id,file:i});f.allowed?c.push(g.id):u??=f.refusal}if(c.length===0&&u!==void 0)throw new Oe(u.code,u.message);let l=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:oi(i),summary:EP(d),orgIds:c,...l?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=$(uy,e,"checkpoint:error",this.deps);if(!t)return;let r=this.importFiles.get(t.token),n=r!==void 0?[r]:[];try{if(r===void 0)throw new Oe("IMPORT_FILE_GONE","This window no longer knows the file to import: choose it again with Import\u2026. Nothing was imported.");let o=await this.modules();n.push((await this.openedStore()).root);let i=o.parseArchiveKey(t.key);if(i===void 0){let d=await this.readImport({orgId:t.orgId,file:r});throw d.allowed?new Oe("IMPORT_KEY","That is not a key SandForge draws: 52 letters and digits, in groups of four as the export showed it. Nothing was imported."):new Oe(d.refusal.code,d.refusal.message)}let a=await this.importCheckpoint({orgId:t.orgId,file:r,key:i,keepDays:t.keepDays});if(!a.imported)throw new Oe(a.refusal.code,a.refusal.message);this.importFiles.delete(t.token),this.respond(e,"checkpoint:import:response",{checkpoint:a.checkpoint,outcome:a.outcome})}catch(o){this.fail(e,this.pathless(o,n,"IMPORT_ERROR"),"IMPORT_ERROR")}}fileDialogs(e){let t=this.deps.infraServices?.checkpointFiles;if(!t)throw new Oe("NO_FILE_DIALOG",e==="export"?"This window has no dialog to ask where the file goes: export the checkpoint with npx sandforge checkpoint export. Nothing was written.":"This window has no dialog to ask which file to read: import it with npx sandforge checkpoint import. Nothing was imported.");return t}keepImportFile(e){let t=Xo();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=RP)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof Oe?e:new Oe(r,I(e));return new Oe(n.code,TP(n.message,t),n.retryable)}checkpointsChanged(){for(let e of this.changeListeners)try{e()}catch(t){this.deps.log(`[WARN] A listener of the checkpoints failed: ${I(t)}`)}}modules(){return this.loaded??=AP(),this.loaded}async openedStore(){this.store??=this.modules().then(t=>{let r=t.openCheckpointStore({root:t.defaultCheckpointStoreRoot()});return"store"in r?r.store:r.refusal});let e=await this.store;if("reason"in e)throw this.store=void 0,new Oe("STORE_REFUSED",PP(e));return e}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}fail(e,t,r,n=!0){if(t instanceof Oe){let o=t.refusal?.holdingLimit,i={...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...o!==void 0?{holdingLimit:o}:{}};E(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...Object.keys(i).length>0?{extraPayload:i}:{}});return}E(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new Oe(e.code,e.message,IP.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new Oe("ORG_NOT_FOUND","SandForge has no connected org of this id: connect it first.");return t}async connect(e){try{return await q(e.id,this.deps.orgRegistry,this.deps.orgManager)}catch(t){throw t instanceof Oo&&t.code==="SCRATCH_ORG_EXPIRED"?new Oe("SCRATCH_EXPIRED",`${ft(e)} is a scratch org that has expired: its checkpoints no longer rewind it. `+ys):t}}takeRequestOf(e,t){let r=e.metadata?.expirationDate,{mode:n,objects:o,excluded:i,customSettings:a,maxTotal:d}=t;return{orgId:e.id,orgName:ft(e),...e.alias?{alias:e.alias}:{},username:e.username,instanceUrl:e.instanceUrl,registered:e,...e.orgType==="Scratch"&&r!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(r)?{scratchExpiresAt:r}:{},mode:n,...o!==void 0?{objects:o}:{},...i!==void 0?{excluded:i}:{},...a!==void 0?{customSettings:a}:{},...d!==void 0?{maxTotal:d}:{}}}writingTo(e,t,r,n,o={}){return this.runWriting(e,t,r,n,o)}runWriting(e,t,r,n,o={}){let i=`A SandForge run is writing to ${t}: ${r} once it has ended. ${n}`;return async a=>{if(this.writers.writingTo?.(e,o.operationId)===!0)return i;for(let d of[this.syncRuns,this.seedRuns])if(d){for(let c of await d.list())if(!(c.end!==void 0||!this.writesTo(c,e,a))&&!(o.runId!==void 0&&c.runId===o.runId&&this.writtenHere(c))&&(this.writers.isRunning?.(c.runId)===!0||Qn(c,this.self)))return i}}}writtenHere(e){let t=e.writer;return t!==void 0&&t.pid===this.self.pid&&Date.parse(t.hostStartedAt)===Date.parse(this.self.startedAt)}writesTo(e,t,r){return e.targetOrgId===t||Nt(e.targetOrganizationId,r)||Nt(this.deps.orgManager.getOrg(e.targetOrgId)?.orgId,r)}refreshedAt(e){let t=this.deps.sandboxRefreshes;if(t)for(let r of this.deps.orgManager.getAllOrgs())for(let n of t.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?t.organizationIdOf(r.id):void 0);if(Nt(o,e))return n.detectedAt}}organizationIdsOf(e){let t=this.deps.sandboxRefreshes,r=[this.deps.orgManager.getOrg(e)?.orgId,t?.organizationIdOf(e),...t?.refreshesOf(e).map(o=>o.previousOrganizationId)??[]],n=[];for(let o of r)o===void 0||!ek.test(o)||n.some(i=>Nt(i,o))||n.push(o);return n}async listOfOrg(e,t){let r=o=>this.refreshedAt(o);return(await Promise.all(this.organizationIdsOf(t).map(o=>e.list({organizationId:o,refreshedAt:r})))).flat().sort((o,i)=>o.checkpointId<i.checkpointId?1:o.checkpointId>i.checkpointId?-1:0)}async withReplays(e){if(e.length===0)return e;try{let t=await this.modules();this.replays??=new t.ReplayStore({root:t.defaultReplayStoreRoot()});let r=this.replays,n=this.deps.orgManager.getAllOrgs(),o=new Map;for(let a of e)o.has(a.organizationId)||o.set(a.organizationId,await r.list({sourceOrganizationId:a.organizationId}));let i=[];for(let a of e){let d=(o.get(a.organizationId)??[]).filter(u=>u.checkpointId===a.checkpointId),c=[];for(let u of d){let l=n.find(f=>Nt(f.orgId,u.target.organizationId)),g=await r.mappingStoreOf(r.folderOf(u.sourceOrganizationId,u.checkpointId),u.target.organizationId).recordedLoads(),p=t.loadToRemove(g);c.push({target:{organizationId:u.target.organizationId,...u.target.name!==void 0?{name:u.target.name}:{},...l?{orgId:l.id}:{}},...u.replayedAt!==void 0?{replayedAt:u.replayedAt}:{},inPlace:u.inPlace,...u.removed?{removed:!0}:{},...u.choices?{choices:u.choices}:{},...l&&p?{records:{...t.loadRecordsInfo(p),orgId:l.id}}:{}})}i.push(c.length>0?{...a,replays:c}:a)}return i}catch(t){return this.deps.log(`[WARN] The replays of the checkpoints could not be read: ${I(t)}`),e}}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>Nt(a.orgId,t)),o=n.find(a=>a.alias===e.org.alias)??n[0];if(o)return o;let i=this.deps.sandboxRefreshes;return r.find(a=>Nt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new Oe("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new Oe("DAMAGED",`The file of checkpoint ${t} cannot be read: it can only be deleted.`);return{folder:r.folder,checkpoint:r.checkpoint}}usable(e,t,r){let n=ye(t.org);if(t.status!=="ready")throw new Oe(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${kP[r]} once taken, or deleted.`:`The take of checkpoint '${t.name}' failed: it can only be deleted.`);if(r==="export")return;let o=this.refreshedAt(t.org.organizationId);if(o!==void 0)throw new Oe("OTHER_ORG",`This sandbox was refreshed on ${o.slice(0,10)}: ${n} is another org now, and this checkpoint is of the org before it, which it no longer rewinds. `+ys);if(e.scratchOrgExpired(t.org,Date.now()))throw new Oe("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints no longer rewind it. `+ys)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=ye(e.org);throw new Oe("ORG_NOT_FOUND",`${n} is not connected in SandForge: connect it to ${t}.`)}return r}async undoOffered(e,t,r,n){if((await e.list({organizationId:t.organizationId,refreshedAt:d=>this.refreshedAt(d)})).find(d=>d.checkpointId===r.checkpointId)?.undo?.rewindId===n)return;let i=r.lastRewind,a=i?.rewindId!==n?`the rewind ${n} is not the last rewind to '${r.name}'`:i.undoneAt!==void 0?`it was undone on ${i.undoneAt.slice(0,10)}, and there is nothing left to undo`:i.undoUntil!==void 0&&Date.parse(i.undoUntil)<=Date.now()?`its 15 days ended on ${i.undoUntil.slice(0,10)}, and what it deleted may have left the recycle bin`:"Undo is offered for the last rewind of an org only, while its journal is kept on this machine";throw new Oe("UNDO_CLOSED",`This rewind can no longer be undone: ${a}. No record was read or written.`)}audit(e,t,r,n,o,i={}){let{result:a,code:d,deliverability:c}=i,u=a?.mutedAutomation??i.muted,l=a?.rewindId??i.rewindId,g=e.pipeline;Q(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:xr,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:Ia(In(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...u?{muted:ut(u)}:{},details:{checkpointId:n.checkpointId,...l!==void 0?{rewindId:l}:{},...a?{status:a.status,passes:a.passes}:{},...a?.scope?{limitedTo:a.scope.objects.join(", ")}:{},...c!==void 0?{deliverability:c}:{},...c!==void 0&&c!=="withheld"&&i.acceptEmails===!0?{confirmed:"emails"}:{},...g?{pipeline:g.origin.pipeline,step:g.origin.step,trigger:g.origin.trigger,grantedAt:g.grantedAt}:{}}})}async handleList(e){let t=$(ny,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),n=t?.orgId===void 0?await r.list({refreshedAt:i=>this.refreshedAt(i)}):await this.listOfOrg(r,t.orgId),o=await this.withReplays(n);this.respond(e,"checkpoint:list:response",{checkpoints:o})}catch(r){this.fail(e,r,"LIST_ERROR")}}async handleScope(e){let t=$(oy,e,"checkpoint:error",this.deps);if(t)try{let r=this.registeredOrg(t.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r),a=await n.scopeCheckpoint({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.runWriting(r.id,ft(r),"take the checkpoint","No record was read.")},this.takeRequestOf(r,t));this.respond(e,"checkpoint:scope:response",{orgId:t.orgId,mode:a.mode,objects:a.objects,leftOut:a.leftOut,estimate:a.estimate,...a.refusal?{refusal:a.refusal}:{},...a.files?{files:a.files}:{},...a.customSettings?{customSettings:a.customSettings}:{}})}catch(r){this.fail(e,r,"SCOPE_ERROR")}}async handleTake(e){let t=$(sy,e,"checkpoint:error",this.deps);if(!t)return;let r=e.id,o=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(r);try{let i=this.registeredOrg(t.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(o?.signal.aborted)throw new Oe(pr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:u,requests:l,estimate:g})=>this.respond(e,"checkpoint:take:response",{checkpoint:u,operationId:e.id,...l?{requests:l}:{},estimate:g})})}catch(i){this.fail(e,i,"TAKE_ERROR")}finally{o?.release()}}async take(e,t,r,n,o,i,a={}){let d=ft(o),c=a.description??`Taking a checkpoint of ${d}`,u=this.deps.infraServices?.backgroundRegistry,l=new AbortController,g=()=>{},p=new Promise((y,R)=>{g=S=>S===void 0?y():R(S)});p.catch(()=>{}),Je(this.deps,e,xr,c),u?.register(e,xr,c,p,l);let f=ar(this.liveTracker,e,xr,c),h=y=>{let{percentage:R,processedObjects:S,totalObjects:w,step:O}=y;Fe(this.deps,e,R,S,w,O),l.signal.aborted||u?.updateProgress(e,R),f.progress(R,S,w,O),a.onProgress?.(y)},m=()=>{u?u.abort(e):l.abort()};a.signal?.addEventListener("abort",m,{once:!0}),a.signal?.aborted&&m();try{let y=await t.takeCheckpoint({org:t.takeOrgOf(n),store:r,handler:this.deps,signal:l.signal,onProgress:h,runWriting:a.runWriting??this.runWriting(o.id,d,"take the checkpoint","No record was read.")},{...this.takeRequestOf(o,i),...i.name!==void 0?{name:i.name}:{},...i.nameWithDate!==void 0?{nameWithDate:i.nameWithDate}:{},keepDays:i.keepDays,...i.ignoredFields?{ignoredFields:i.ignoredFields}:{},...i.unprovenLeftOut===!0?{unprovenLeftOut:!0}:{},...i.beforeRun!==void 0?{beforeRun:i.beforeRun}:{}});if(!y.taken)throw pe(this.deps,e,{status:"refused",code:y.refusal.code}),f.fail(y.refusal.message),g(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:w,reason:O}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${w} while it was read was not checked: ${O}`);let{checkpoint:R}=y,S={checkpoint:R,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(S),this.checkpointsChanged(),pe(this.deps,e,{status:"success",objects:R.objects.length,records:R.objects.reduce((w,O)=>w+O.records,0)}),f.complete(),g(),S}catch(y){throw y instanceof Oe?y:y instanceof t.CheckpointTakeStopped?(u?.abort(e),pe(this.deps,e,{aborted:!0}),f.cancel(),g(),new Oe(pr,y.message,!0)):(pe(this.deps,e,{status:"failure"}),f.fail(I(y)),g(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=$(iy,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=ni(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),u=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:l=>this.readAutomation(d.id,l),runWriting:this.runWriting(d.id,ft(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:ft(d),registered:d,username:d.username,...a!==void 0?{objects:a}:{},...this.previewsAnswered!==void 0?{reusesPreview:!0}:{},...t.muteAutomation===!0?{muteAutomation:!0}:{},...t.acceptOutside!==void 0?{acceptOutside:t.acceptOutside}:{}});if(!u.previewed)throw this.refusalOf(u.refusal);this.previewsAnswered?.set(u.diff.previewId,u.diff),this.previewReads.set(u.diff.previewId,{checkpointId:i.checkpointId,readAt:u.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:u.diff,...u.automation?{automation:u.automation}:{},...u.emails?{emails:u.emails}:{},...u.emailsKeepingOutside?{emailsKeepingOutside:u.emailsKeepingOutside}:{},...u.emailsUncounted!==void 0?{emailsUncounted:u.emailsUncounted}:{},...u.deliverability?{deliverability:u.deliverability}:{},estimate:u.estimate,...u.refusal?{refusal:u.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=$(dy,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=ni(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await ZS(d))throw new Oe("PREVIEW_GONE",`The preview to plan this selection from is no longer kept on this machine: preview the rewind to '${i.name}' again. No record was read or written.`);let u=await r.planSelection({checkpoint:i,previewDir:d,readAt:c.readAt,objects:new Set(a),acceptOutside:t.acceptOutside,heldRows:r.snapshotRowsOf(i,o)});this.respond(e,"checkpoint:plan-selection:response",{checkpointId:i.checkpointId,previewId:t.previewId,plan:u})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=$(ay,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"rewind");let c=ni(d,t.objects);if(!await ZS(o.previewDirOf(a,t.previewId)))throw new Oe("PREVIEW_GONE",`The preview this rewind was confirmed on is no longer kept on this machine: preview the rewind to '${d.name}' again, then rewind. No record was read or written.`);let u=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),l=await this.connect(u),g=this.pageAt(e);if(n?.signal.aborted)throw this.audit(g,"rewind",u,d,"stopped",{code:bt}),new Oe(pr,new o.RewindStopped().message,!0);let p=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let f=p?.checkpointId===d.checkpointId?p:void 0,h=ft(u);await this.writeAct(g,"rewind",u,d,`Rewinding ${h} to '${d.name}'`,async(m,y)=>{let R=await o.rewindOrg({org:o.rewindOrgOf(l),undelete:w=>l.soap.undelete(w),store:i,readAutomation:w=>this.readAutomation(u.id,w),runWriting:this.runWriting(u.id,h,"rewind","No record was read or written."),onUndeletable:Kr(this.deps,u.id,"checkpoint:rewind"),onProgress:({percentage:w,step:O})=>y(w,O),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:h,registered:u,username:u.username,previewId:t.previewId,...f?{reusesPreview:f}:{},...c!==void 0?{objects:c}:{},acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0,acceptNoUndo:t.acceptNoUndo,acceptRecreate:t.acceptRecreate,acceptOutside:t.acceptOutside,acceptUnseen:t.acceptUnseen});if(R.rewound)return Ap(R);let S=t.fromPage===!0;return Tp(R.refusal,R.alsoRefused,w=>S?o.pageEmailsRefusal(w,"rewind",h):w,S)},m=>m instanceof o.RewindStopped,{acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"REWIND_ERROR")}finally{n?.release()}}async handleUndo(e){let t=$(ly,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"undo"),await this.undoOffered(i,a,d,t.rewindId);let c=this.connectedOrgOf(d,`undo its rewind to '${d.name}'`),u=await this.connect(c),l=this.pageAt(e);if(n?.signal.aborted)throw this.audit(l,"undo",c,d,"stopped",{code:bt,rewindId:t.rewindId}),new Oe(pr,new o.UndoStopped().message,!0);let g=ft(c);await this.writeAct(l,"undo",c,d,`Undoing the rewind of ${g} to '${d.name}'`,async(p,f)=>{let h=await o.undoCheckpoint({org:o.rewindOrgOf(u),undelete:y=>u.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,g,"undo the rewind","No record was read or written."),onUndeletable:Kr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:R})=>f(y,R),signal:p,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:g,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(h.undone)return Ap(h);let m=t.fromPage===!0;return Tp(h.refusal,h.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",g):y,m)},p=>p instanceof o.UndoStopped,{rewindId:t.rewindId,acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"UNDO_ERROR")}finally{n?.release()}}muteOf(e){return(t,r)=>Ot(async()=>_t(e),t,{...this.muteLeases,writes:r})}pageAt(e){return{operationId:e.id,respond:(t,r)=>this.respond(e,t,r)}}async writeAct(e,t,r,n,o,i,a,d={}){let{operationId:c}=e,{rewindId:u}=d,l=this.deps.infraServices?.backgroundRegistry,g=new AbortController,p=()=>{},f=new Promise((S,w)=>{p=O=>O===void 0?S():w(O)});f.catch(()=>{}),Je(this.deps,c,xr,o),l?.register(c,xr,o,f,g);let h=ar(this.liveTracker,c,xr,o),m=u!==void 0?{rewindId:u}:{},y=(S,w)=>{Fe(this.deps,c,S,0,0,w),g.signal.aborted||l?.updateProgress(c,S),h.progress(S,0,0,w)},R=()=>{l?l.abort(c):g.abort()};d.signal?.addEventListener("abort",R,{once:!0}),d.signal?.aborted&&R();try{let S=await i(g.signal,y);if(!S.done)throw this.audit(e,t,r,n,"stopped",{code:S.refusal.code,...m}),pe(this.deps,c,{status:"refused",code:S.refusal.code}),h.fail(S.refusal.message),p(new Error(S.refusal.message)),this.refusalOf(S.refusal,S.alsoRefused);let{result:w,notes:O,deliverability:P}=S,v={...P!==void 0?{deliverability:P}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let C of O)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${C}`);for(let C of w.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${C.rewindId} of checkpoint '${C.name}': Undo reaches the last rewind of the org alone`);let b=d.refusalOf?.(w);if(b!==void 0)throw this.audit(e,t,r,n,QS(w)?"partial":"stopped",{result:w,code:b.code,...v}),pe(this.deps,c,{status:"refused",code:b.code}),h.fail(b.message),p(new Error(b.message)),new Oe(b.code,b.message,!1,w);if(this.audit(e,t,r,n,SP[w.status],{result:w,...v}),e.respond?.(`checkpoint:${t}:response`,{result:w,operationId:c}),w.status==="cancelled")l?.abort(c),pe(this.deps,c,{aborted:!0}),h.cancel(),p();else if(w.status==="failure"){let C=`Nothing the ${t} set out to write went through: its result says why.`;pe(this.deps,c,{status:w.status}),h.fail(C),p(new Error(C))}else pe(this.deps,c,{status:w.status}),w.status==="success"?h.complete():h.partial(),p();return w}catch(S){if(S instanceof Oe)throw S;if(a(S))throw l?.abort(c),pe(this.deps,c,{aborted:!0}),h.cancel(),p(),this.audit(e,t,r,n,"stopped",{code:pr,...m}),new Oe(pr,I(S),!0);let w=Hs(S);throw this.audit(e,t,r,n,"failure",{...m,...w?{muted:w}:{}}),this.unreleased(e,t,r,w),pe(this.deps,c,{status:"failure"}),h.fail(I(S)),p(S),S}finally{d.signal?.removeEventListener("abort",R)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Xt(n,ft(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new ge(vP).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handleDelete(e){let t=$(py,e,"checkpoint:error",this.deps);if(t)try{let r=await this.openedStore(),n=[],o=[];for(let i of t.checkpointIds){let a=await r.delete(i);a.outcome==="deleted"?n.push(i):a.outcome==="busy"&&o.push(a.holder)}for(let i of o)this.deps.log(`[WARN] checkpoint:delete: kept while ${Ep(i)}`);if(n.length===0&&o.length>0)throw new Oe("RUN_WRITING",`The checkpoint was not deleted: ${Ep(o[0])}. Delete it once that has ended.`,!0);this.respond(e,"checkpoint:delete:response",{deleted:n}),n.length>0&&this.checkpointsChanged()}catch(r){this.fail(e,r,"DELETE_ERROR")}}async handleKeep(e){let t=$(gy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"keep",r=>r.keep(t.checkpointId,t.keep))}async handleRename(e){let t=$(fy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"rename",r=>r.update(t.checkpointId,n=>({...n,name:t.name})))}async handleIgnoreFields(e){let t=$(hy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"ignore-fields",r=>r.update(t.checkpointId,n=>({...n,ignoredFields:t.fields})))}async handleRewinds(e){let t=$(my,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-EFHDE7W4.mjs"),i=(t?.orgIds??this.deps.orgManager.getAllOrgs().map(c=>c.id)).map(c=>({orgId:c,ids:this.organizationIdsOf(c)})),a=await n(r.root,i.flatMap(({ids:c})=>c)),d=[];for(let[c,u]of a){for(let l of u.unreadable)this.deps.log(`[WARN] Line ${l} of the rewind ledger of ${c} does not parse: left out`);for(let l of u.records){let g=i.filter(({ids:p})=>p.some(f=>Nt(f,l.organizationId)));d.push({...l,orgIds:g.map(({orgId:p})=>p)})}}this.respond(e,"checkpoint:rewinds:response",{rewinds:d})}catch(r){this.fail(e,r,"REWINDS_ERROR")}}async change(e,t,r,n){try{let o=await this.modules(),i=await this.openedStore(),{folder:a}=await this.checkpointOf(i,t),d=i.heldBy(a.organizationId);if(d!==void 0&&(d.checkpointId===void 0||d.checkpointId===t))throw new Oe("RUN_WRITING",`The checkpoint was not changed: ${Ep(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(u){throw u instanceof o.CheckpointStoreError?new Oe(u.code==="notFound"?"NOT_FOUND":u.code==="damaged"?"DAMAGED":"INVALID",u.message):u}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var vt={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",templateMissing:"SEED_TEMPLATE_MISSING",templateInvalid:"SEED_TEMPLATE_INVALID",templateUsesAi:"SEED_TEMPLATE_USES_AI",unanswered:"SEED_CONFIRMATION_UNAVAILABLE"};function gr(s,e){return Object.assign(new Error(e),{code:s})}function nk(s,e,t){let r=Ki(s);if(r==="refused")return gr(vt.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never seeds one, whatever an Approval step answers. Seed a sandbox, a scratch org or a Developer Edition org. Nothing was written.`);if(r==="needsApproval"&&!e.approved)return gr(vt.needsApproval,`${t} is a sandbox marked Staging, which a pipeline seeds only once an Approval step before the seed has approved the run, and none did: put an Approval step before it. Nothing was written.`)}function Pp(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function Yo(s,e,t){let r=t(e)??Hi.find(d=>d.id===e);if(r==null)return{refusal:gr(vt.templateMissing,`No Seed template is saved under ${e}, and SandForge ships none: it was deleted on the Seed page. Choose another. Nothing was written.`)};let n=r.name,o=typeof n=="string"&&n!==""?n:e,i=Po.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:gr(vt.templateInvalid,`The Seed template "${o}" no longer validates (${d.path.join(".")}: ${d.message}): open it on the Seed page and save it again. Nothing was written.`)}}let a=Pp(i.data);return a.length>0?{refusal:gr(vt.templateUsesAi,`The Seed template "${o}" fills ${a.join(", ")} with AI rules: a pipeline runs where nobody watches, and an AI rule sends field names to Anthropic on each run. Give ${a.length===1?"it a Faker rule":"them Faker rules"} on the Seed page. Nothing was written.`)}:{asked:{orgId:s,template:i.data}}}var ck={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},Cp=Object.keys(ck),ok={apiLimits:{variable:vs.apiLimits,read:s=>s.percent},storage:{variable:vs.storage,read:s=>s.percent},recentErrors:{variable:vs.recentErrors,read:s=>s.count},failedJobs:{variable:vs.failedJobs,read:s=>s.count}},uk=500,lk=V({orgId:tm,checks:ve(We(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),pk=V({message:j().trim().min(1).max(uk)});function At(s,e){return`${s} ${e}${s===1?"":"s"}`}function jr(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"completed",output:t,summary:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function Tt(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"failed",output:t,error:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function Nr(s,e,t,r){if(typeof t!="string"||t.trim()==="")return`${e} names no org: choose ${r}.`;if(s.orgName(t)===void 0)return`${e} names an org SandForge does not know (${t}): connect it, or choose ${r} again.`}function Np(s){return Array.isArray(s)&&s.length>0?s:void 0}function CP(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=Nr(s,t,r.orgId,"the org it backs up");if(n)return n;let o=Np(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!rm.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!xs.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function $P(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=Nr(s,t,r.sourceOrgId,"the org it compares from")??Nr(s,t,r.targetOrgId,"the org it compares with");if(n)return n;if(r.sourceOrgId===r.targetOrgId)return`${t} compares an org with itself: choose two different orgs.`;let o=Np(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!Ds.safeParse({sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,types:o}).success)return`${t} names component types the Compare page would not send: at most 50, each a type name.`}}function xP(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=Nr(s,t,r.orgId,"the org it checks");if(n)return n;let o=Np(r.checks);if(!o)return`${t} names no check: choose what it checks (${Cp.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!Cp.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${Cp.join(", ")}.`;if(!lk.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function DP(s){return e=>{let t=`Notification step "${e.name}"`;if(!s.notify)return`${t} cannot show a notification: there is no VS Code window to show it in.`;let r=(e.config??{}).message;if(typeof r!="string"||r.trim()==="")return`${t} has no message: write what the notification says.`;if(!pk.safeParse({message:r}).success)return`${t} has a message longer than ${uk} characters.`}}function NP(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=xs.parse({orgId:e.config.orgId,objects:e.config.objects}),i=await s.backup({operationId:s.newId(),orgId:n,objects:o},t.signal),a=s.orgName(n)??n,d=i.objects.filter(u=>u.truncated).map(u=>u.objectApiName),c=`Backed up ${At(i.totalRecords,"record")} of ${At(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return jr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function jP(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=Ds.parse({sourceOrgId:e.config.sourceOrgId,targetOrgId:e.config.targetOrgId,types:e.config.types}),a=await s.compare({sourceOrgId:n,targetOrgId:o,types:i},t.signal),{added:d,removed:c,modified:u,unchanged:l,notCompared:g}=a.summary,p=s.orgName(n)??n,f=s.orgName(o)??o;return jr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[Yf]:String(d+c+u)}},`Compared ${At(i.length,"component type")} of ${p} with ${f}: ${c} only in ${p}, ${d} only in ${f}, ${u} modified, ${l} unchanged, ${g} not compared.`)}}function sk(s){switch(s.status){case"critical":return`${s.message} (critical)`;case"unknown":return`${s.message} (could not be read)`;case"warning":return`${s.message} (warning)`;default:return s.message}}function MP(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=lk.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(l=>ck[l])),a=n.map((l,g)=>({check:l,signal:i[g]})),d={};for(let{check:l,signal:g}of a){let p=g?ok[l].read(g):void 0;p!==void 0&&g.status!=="unknown"&&(d[ok[l].variable]=String(p))}let c={orgId:r,checks:a.map(({check:l,signal:g})=>({check:l,status:g?.status??"unknown",message:g?.message??"Not read"})),variables:d},u=a.filter(({signal:l})=>!l||l.status==="critical"||l.status==="unknown");return u.length>0?Tt(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${u.map(({check:l,signal:g})=>g?sk(g):`${l} was not read`).join("; ")}.`):jr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:l})=>sk(l)).join("; ")}.`)}}function LP(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=pk.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),jr(e,r,{message:n},s.ranFrom==="commandLine"?"Printed the message: a run from the command line has no VS Code window to show it in.":"Showed a notification in VS Code.")):Tt(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function gk(s,e,t){let r=`Approval step "${e.name}"`;if(s.ranFrom!=="commandLine")return`${r} cannot ask anyone: there is no VS Code window to ask in.`;let n=`${r} cannot ask anyone: this run has no terminal to ask in.`;if(t===void 0)return`${n} Run it in a terminal.`;let o=FP(s,t);return o!==void 0?`${n} Run it in a terminal: it stands before a write to ${o}, a sandbox marked Staging, which only a person at a terminal approves, never --approve.`:`${n} Run it in a terminal, or answer it ahead with --approve "${e.name}".`}function FP(s,e){for(let t of e.steps.slice(e.index+1)){if(t.type==="approval")return;let r;if(t.type==="sync"){let n=si(s,t);r="problem"in n?void 0:n.config.targetOrgId}else(t.type==="seed"||t.type==="anonymize")&&(r=sn((t.config??{}).orgId));if(r!==void 0&&s.orgTier?.(r)==="staging")return s.orgName(r)??r}}function _P(s){return(e,t)=>{let r=`Approval step "${e.name}"`;if(!s.askApproval)return gk(s,e,t);switch(rh(e.config)){case"timeout":return`${r} waits for a time it cannot keep: set a whole number of minutes from 1 to ${Zf} (a day).`;case"message":return`${r} has a message that is not text, or is longer than ${eh} characters.`;default:return}}}function ik(s){switch(s.via){case"page":return" on the Automation page";case"notification":return" in the VS Code notification";case"terminal":return" at the terminal";case"commandLine":return" ahead, on the command line (--approve)";default:return""}}function UP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return Tt(e,r,{},gk(s,e,void 0));let o=th(e.config)??Qf,i=e.config?.message,a=typeof i=="string"&&i.trim()!==""?i.trim():void 0,d=await s.askApproval({stepId:e.id,stepName:e.name,...t.pipelineName?{pipelineName:t.pipelineName}:{},...a?{message:a}:{},timeoutMs:o*6e4},t.signal),c={approval:d};switch(d.decision){case"approved":return{...jr(e,r,c,`Approved${ik(d)} at ${d.at}.`),approval:d};case"rejected":return{...Tt(e,r,c,`${n} was rejected${ik(d)} at ${d.at}.`),approval:d};case"timedOut":return{...Tt(e,r,c,`${n} was not approved in time: nobody answered within ${At(o,"minute")}.`),approval:d};case"cancelled":return{...Tt(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function si(s,e){let t=`Sync step "${e.name}"`,r=(e.config??{}).configId;if(typeof r!="string"||r.trim()==="")return{problem:`${t} names no saved Sync configuration: choose the one it runs.`};let n=s.savedSyncConfig?.(r);if(n==null)return{problem:`${t} names a Sync configuration that is no longer saved (${r}): choose another.`};let o=Sn.safeParse({config:n});if(!o.success){let d=o.error.issues[0];return{problem:`${t} names a Sync configuration that no longer validates (${d.path.slice(1).join(".")}: ${d.message}): open it on the Sync page and save it again.`}}let i=n,a=typeof i.name=="string"&&i.name!==""?i.name:r;return{config:i,name:a}}function fk(s){return(s.listSyncConfigs?.()??[]).flatMap(t=>{if(typeof t!="object"||t===null)return[];let{id:r,name:n}=t;if(typeof r!="string"||r==="")return[];let o=typeof n=="string"&&n!==""?n:r;if(!Sn.safeParse({config:t}).success)return[{id:r,name:o,valid:!1}];let i=t;return[{id:r,name:o,valid:!0,sourceOrgId:i.sourceOrgId,targetOrgId:i.targetOrgId,...s.syncGuard?{guard:s.syncGuard(i).decision}:{}}]})}function hk(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function HP(s){return(e,t)=>{let r=`Sync step "${e.name}"`;if(!s.runSync||!s.savedSyncConfig||!s.syncGuard)return`${r} cannot run here: Sync is not available in this window.`;let n=si(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=Nr(s,r,o.sourceOrgId,"the source org of its configuration")??Nr(s,r,o.targetOrgId,"the target org of its configuration");if(i)return i;let a=s.syncGuard(o);if(a.decision==="refused")return`${r} writes where Production Guard refuses it, whatever anyone answers: ${a.reason}.`;if(a.decision==="asks"&&!hk(t)){let d=s.orgName(o.targetOrgId)??o.targetOrgId;return`${r} writes to ${d}, which Production Guard asks about before a write, and nobody may be there to answer when the pipeline runs: put an Approval step before it.`}}}function jp(s){let e=s.previousResults.filter(r=>r.stepType==="approval"),t=e[e.length-1];return{approved:t?.status==="completed"&&t.approval?.decision==="approved"}}function Mp(s,e){let t=[],r=s.filter(o=>o.delta?.read==="full"&&o.delta.reason==="first_run").map(o=>o.objectApiName);r.length>0&&t.push(`first run from this store for ${r.join(", ")}: no watermark yet, every record ${e?"was":"is"} read`);let n=s.filter(o=>o.delta?.read==="delta");return n.length>0&&t.push(`${n.map(o=>o.objectApiName).join(", ")} read from the last run's watermark`),t}var ak=3;function BP(s){let e=s.filter(r=>r.failed>0).flatMap(r=>el(r.errors).map(n=>`${r.objectApiName}, ${n.count} \xD7 ${n.example}`));if(e.length===0)return"";let t=e.length-ak;return`; refused: ${e.slice(0,ak).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function qP(s){return async(e,t)=>{let r=new Date().toISOString(),n=si(s,e);if("problem"in n)throw new Error(n.problem);if(!s.runSync)throw new Error(`Sync step "${e.name}" cannot run here: Sync is not available in this window.`);let{config:o,name:i}=n,a=await s.runSync(o,jp(t),t.signal);if(a.cancelled)throw new Rt(`Sync step "${e.name}" was cancelled: ${a.error??"the run stopped before it synced every object."}`);let d=s.orgName(o.targetOrgId)??o.targetOrgId,c=a.summary,u={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(p=>{let f=p.failed>0?el(p.errors):[];return{objectApiName:p.objectApiName,operation:p.operation,processed:p.processed,success:p.success,failed:p.failed,skipped:p.skipped,...f.length>0?{refusals:f}:{},...p.delta?{delta:p.delta}:{}}}),...typeof c=="object"&&c!==null?{summary:c}:{}},l=Mp(a.objectResults,!0).map(p=>`; ${p}`).join(""),g=`${At(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read${l}`;if(a.status!=="success"){let p=[a.error,cd(a)].filter(f=>f!==void 0&&f!=="");return Tt(e,r,u,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${g}`+BP(a.objectResults)+(p.length>0?`; ${p.join("; ")}`:"."))}return jr(e,r,u,`Synced "${i}" into ${d}: ${g}.`)}}function sn(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Lp(s){let e=s.issues[0];return e?e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message:"its configuration is not one"}function WP(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function Od(s){return s.pipelineName??s.pipelineId}function mk(s,e,t,r,n){let o=s.orgName(t)??t,i=Ki(s.orgTier?.(t)??"production");if(i==="refused")return`${e} writes to ${o}, a production org or one SandForge cannot tell is not: a pipeline never ${r} one, whatever an Approval step answers. Choose a sandbox, a scratch org or a Developer Edition org.`;if(i==="needsApproval"&&!hk(n))return`${e} writes to ${o}, a sandbox marked Staging, which a pipeline ${r} only once an Approval step before it has approved the run: put an Approval step before it.`}function yk(s,e,t){return s.retries!==void 0&&s.retries>0?`${e} is given retries, and is never tried again: ${t}. Set its retries to 0.`:void 0}function wk(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function zP(s){return(e,t)=>{let r=`Seed step "${e.name}"`;if(!s.seed||!s.savedSeedTemplate)return`${r} cannot run here: Seed is not available in this window.`;let n=e.config??{},o=Nr(s,r,n.orgId,"the org it seeds");if(o)return o;let i=sn(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=Yo(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:yk(e,r,"a second try would write a second set of records")??mk(s,r,a,"seeds",t)}}function GP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`;if(!s.seed)throw new Error(`${n} cannot run here: Seed is not available in this window.`);let{orgId:o,templateId:i}=Vi.parse({orgId:e.config.orgId,templateId:sn(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:Od(t)},answer:jp(t)},t.signal)}catch(p){let f=wk(p);if(f===void 0)throw p;return Tt(e,r,{orgId:o,templateId:i,code:f},`${n}: ${p.message}`)}let{result:c}=d,u={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(p=>({objectApiName:p.objectApiName,recordsCreated:p.recordsCreated,recordsFailed:p.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},l=At(c.totalRecordsCreated,"record"),g="take them back from Seed's History";if(c.cancelled)throw new Rt(`${n} was cancelled: it had created ${l} in ${a}, which stay there; ${g}.`);return c.status!=="success"?Tt(e,r,u,`${n} seeded ${a} and did not complete: ${l} created, ${c.totalRecordsFailed} refused; ${g}.`):jr(e,r,u,`Seeded ${l} into ${a}: ${g}.`)}}function bk(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Hi.map(n=>({raw:n,builtIn:!0})),r=new Set;return[...e,...t].flatMap(({raw:n,builtIn:o})=>{if(typeof n!="object"||n===null)return[];let{id:i,name:a}=n;if(typeof i!="string"||i===""||r.has(i))return[];r.add(i);let d=typeof a=="string"&&a!==""?a:i,c=Po.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&Pp(c.data).length>0}]})}function JP(s){let e=[];for(let t of s.rules){let r=t.fieldPattern.split(".")[0];r&&!e.includes(r)&&e.push(r)}return e}function Rk(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:JP(e)}))}function VP(s){return(e,t)=>{let r=`Anonymize step "${e.name}"`;if(!s.anonymize||!s.maskingTemplates)return`${r} cannot run here: DataOps is not available in this window.`;let n=e.config??{},o=Nr(s,r,n.orgId,"the org it masks");if(o)return o;let i=sn(n.templateId);if(i===void 0)return`${r} names no masking template: choose the one it masks with.`;let a=String(n.orgId),d=s.maskingTemplates(),c=sn(n.object),u=sn(n.where),l=Ib({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...u!==void 0?{where:u}:{},...e.retries!==void 0?{retries:e.retries}:{}},p=>d.some(f=>f.id===p));if("refusal"in l)return`${r}: ${l.refusal.message}`;let g=Ss.safeParse({orgId:a,templateId:i,...Id(n)});return g.success?mk(s,r,a,"masks",t):`${r} does not read (${Lp(g.error)}).`}}function Id(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var dk=3;function KP(s){let e=[...new Set(s.errors.map(r=>`${r.objectApiName}: ${r.message}`))];if(e.length===0)return s.message?` (${s.message})`:"";let t=e.length-dk;return`, refused by the org: ${e.slice(0,dk).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function XP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.anonymize)throw new Error(`${n} cannot run here: DataOps is not available in this window.`);let o=sn(e.config.object),i=sn(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l}=Ss.parse({orgId:e.config.orgId,templateId:sn(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...Id(e.config)}),g=s.orgName(a)??a,p=O=>O?` ${Xt(O,g).map(P=>P.trim()).join("; ")}.`:"",f;try{f=await s.anonymize({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:u,muteAutomation:l},pipeline:{name:Od(t)},answer:jp(t)},t.signal)}catch(O){let P=wk(O);if(P===void 0)throw O;let v=O.snapshot,b=Hs(O);return Tt(e,r,{orgId:a,templateId:d,code:P,...v!==void 0?{snapshot:v}:{},...b?{mutedAutomation:b}:{}},`${n}: ${O.message}`+(typeof v?.operationId=="string"?` The snapshot ${v.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+p(b))}let{result:h}=f,m=h.snapshot?`the snapshot ${h.snapshot.operationId} keeps the values it wrote over, in clear, until it is deleted on the DataOps page, where a restore writes them back`:"no snapshot was kept",y={orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},operationId:f.operationId,status:h.status,recordsProcessed:h.recordsProcessed,recordsFailed:h.recordsFailed,recordsNotMasked:h.recordsNotMasked,objects:h.objects,message:h.message,errors:h.errors,...h.snapshot?{snapshot:h.snapshot}:{},...h.mutedAutomation?{mutedAutomation:h.mutedAutomation}:{}},R=p(h.mutedAutomation);if(h.cancelled)throw new Rt(`${n} was cancelled: it masked ${At(h.recordsProcessed,"record")} in ${g} before the stop, and ${h.recordsNotMasked} still hold their values; ${m}.`+R);let S=h.objects.filter(O=>O.notMasked>0);if(h.recordsNotMasked>0){let O=`${S.map(P=>`${P.notMasked} of ${P.objectApiName}`).join(", ")} still hold their values${KP(h)}`;return Tt(e,r,y,`${n} masked ${g} and did not complete: ${O}; ${m}.${R}`)}let w=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${h.objects.map(O=>O.objectApiName).join(", ")}`;return jr(e,r,y,`Masked ${At(h.recordsProcessed,"record")} in ${g}, ${w}; ${m}.${R}`)}}function YP(s){return e=>{let t=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=Nr(s,t,r.orgId,"the org it takes");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} names ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge takes no checkpoint of one.`;let i=bn.safeParse(r);if(!i.success)return`${t} does not read (${Lp(i.error)}).`}}function QP(s){return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/1024/1024).toFixed(1)} MB`:`${(s/1024/1024/1024).toFixed(2)} GB`}function ZP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=bn.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:Od(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(u){if(!(u instanceof Dr))throw u;return Tt(e,r,{orgId:o.orgId,code:u.code},u.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return jr(e,r,{orgId:o.orgId,operationId:a.operationId,checkpointId:a.checkpointId,name:a.name,records:a.records,objects:a.objects,bytes:a.bytes,movedWhileTaken:d},`Took the checkpoint '${a.name}' of ${i}: ${At(a.records,"record")} of ${At(a.objects,"object")}, ${QP(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${At(o.keepDays,"day")}`)+(c>0?`; ${At(c,"record")} changed while it was taken.`:"."))}}var eC={damaged:"whose file cannot be read: it can only be deleted",taking:"whose take is under way or never ended",failed:"whose take failed: it can only be deleted",refreshed:"of the org a sandbox was before its refresh: the sandbox is another org now, which the checkpoint no longer rewinds; exported, it is still replayed in another org. Take a checkpoint of the sandbox again, and choose it",scratchExpired:"of a scratch org that has expired, which it no longer rewinds; exported, it is still replayed in another org"};function vk(s,e,t,r){let n=s.checkpointKept?.(r);if(n===void 0)return;if(!n.kept)return{why:"missing",problem:`${e} rewinds to the checkpoint ${r}, which is not kept on this machine: it was deleted or expired, or the pipeline came from another machine. Take a checkpoint here, choose it, and confirm the step again.`};let o=n.name!==void 0?`'${n.name}'`:r;if(!n.valid){let a=n.why??"damaged";return{why:a,problem:`${e} rewinds to the checkpoint ${o}, ${eC[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>WP(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function tC(s){return e=>{let t=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=Nr(s,t,r.orgId,"the org it rewinds");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} writes to ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge rewinds none.`;let i=$t.safeParse(r);if(!i.success)return`${t} does not read (${Lp(i.error)}).`;let a=yk(e,t,"a second try would read the org after the first one wrote, with nobody to read its preview");if(a)return a;let d=s.rewindGrant(s.pipelineId??"",e);return"refusal"in d?jn(e.name,d.refusal):vk(s,t,o,i.data.checkpointId)?.problem}}function Dp(s){return{deleted:s.deleted.reduce((e,t)=>e+t.deleted,0),gaveBack:s.restored.reduce((e,t)=>e+t.restored+(t.restoredWithout??0),0),broughtBack:s.undeleted.reduce((e,t)=>e+t.undeleted,0),madeAgain:(s.recreated??[]).reduce((e,t)=>e+t.created,0)}}function $p(s){let e=Dp(s);return`${e.deleted} deleted, ${e.gaveBack} given their values back, ${e.broughtBack} brought back from the recycle bin`+(e.madeAgain>0?`, ${e.madeAgain} made again with new Ids`:"")}function xp(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function rC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=$t.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},jn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=f=>f?` ${Xt(f,a).map(h=>h.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:Od(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(f){let h=(f instanceof Dr?f.result?.mutedAutomation:void 0)??Hs(f);if(!(f instanceof Dr)){if(!h||f instanceof Rt)throw f;return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:h},`${I(f)}${d(h)}`)}return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:f.code,...f.alsoRefused.length>0?{alsoRefused:[...f.alsoRefused]}:{},...f.result?{status:f.result.status,...Dp(f.result)}:{},...h?{mutedAutomation:h}:{}},`${f.message}${d(h)}`)}let{result:u}=c,l=u.residual.reduce((f,h)=>f+h.count,0),g={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:u.rewindId,status:u.status,...Dp(u),residual:l,...u.undo?{undoUntil:u.undo.until}:{},apiRequests:u.apiRequests.used,...u.mutedAutomation?{mutedAutomation:u.mutedAutomation}:{}},p=d(u.mutedAutomation);if(u.status==="cancelled")throw new Rt(`${n} was stopped part way in ${a}: ${$p(u)}; ${xp(u)}.${p}`);return u.status!=="success"?Tt(e,r,g,`${n} rewound ${a} and did not complete (${u.status}): ${$p(u)}; ${At(l,"record")} still ${l===1?"differs":"differ"} from the checkpoint`+(u.unread&&u.unread.length>0?`, and ${u.unread.map(f=>f.objectApiName).join(", ")} could not be read`:"")+`; ${xp(u)}.${p}`):jr(e,r,g,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${$p(u)}, with ${At(u.apiRequests.used,"API request")}; ${xp(u)}.${p}`)}}function Sk(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=$t.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=vk({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function kk(s,e){s.registerHandler("backup",NP(e),CP(e)),s.registerHandler("compare",jP(e),$P(e)),s.registerHandler("precheck",MP(e),xP(e)),s.registerHandler("notification",LP(e),DP(e)),s.registerHandler("approval",UP(e),_P(e)),s.registerHandler("sync",qP(e),HP(e)),s.registerHandler("seed",GP(e),zP(e)),s.registerHandler("anonymize",XP(e),VP(e)),s.registerHandler("checkpoint",ZP(e),YP(e)),s.registerHandler("rewind",rC(e),tC(e))}function cn(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"completed",output:{...t,dryRun:!0},summary:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function an(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"failed",output:{...t,dryRun:!0},error:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function dn(s,e){return`${s} ${e}${s===1?"":"s"}`}function ii(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Ad(s){return s.pipelineName??s.pipelineId}function Fp(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function Qo(s){return new Error(`${s} cannot be simulated here: nothing can read what it would do. Nothing was written.`)}function nC(s){return s<6e4?`${s/1e3} s`:s<36e5?`${Math.round(s/6e4)} min`:`${(s/36e5).toFixed(1)} h`}function Ak(s){return`about ${dn(s.apiRequests,"API request")} of the ${s.apiRequestsLeft} the org has left today, about ${s.seconds} s`}function oC(s){let e=t=>s.reduce((r,n)=>r+t(n),0);return`${e(t=>t.insert)} to create, ${e(t=>t.update)} to update, ${e(t=>t.delete)} to delete, ${e(t=>t.skipped)} skipped and ${e(t=>t.refused)} refused of ${e(t=>t.read)} read`}function Ok(s){let e=Mp(s.objects,!1);return s.cutAtReadCap&&s.cutAtReadCap.length>0&&e.push(`${s.cutAtReadCap.join(", ")} read only up to ${s.readCap??"the bound of"} records (sync.maxRecordsPerObject): the run copies part of each`),e.length>0?`; ${e.join("; ")}`:""}var Ik=3;function sC(s){let e=s.flatMap(r=>(r.refusedFor??[]).map(({note:n})=>`${r.objectApiName}, ${n.replace(/\.$/,"")}`));if(e.length===0)return"";let t=e.length-Ik;return`; refused: ${e.slice(0,Ik).join("; ")}`+(t>0?`; and ${dn(t,"other reason")}`:"")}function iC(s){let e=new Date().toISOString(),t=Yw(s.config)??0;return Promise.resolve(cn(s,e,{wouldWait:t},`Would wait ${nC(t)}: a simulation does not wait.`))}function aC(s){let e=new Date().toISOString();return Promise.resolve(cn(s,e,{asked:!1},"Not asked in a simulation: the route goes on as if it were approved."))}function dC(s){return e=>{let t=new Date().toISOString(),r=ii(e.config.message)??"",n=s.ranFrom==="commandLine"?"Not printed in a simulation; the run would print":"Not shown in a simulation; the run would show in VS Code";return Promise.resolve(cn(e,t,{message:r},`${n}: "${r}"`))}}function cC(s){return e=>{let t=new Date().toISOString(),{orgId:r,objects:n}=xs.parse({orgId:e.config.orgId,objects:e.config.objects}),o=s.orgName(r)??r;return Promise.resolve(cn(e,t,{orgId:r,objects:n},`Would take a snapshot of ${dn(n.length,"object")} of ${o} (${n.join(", ")}): a simulation takes none.`))}}function uC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Sync step "${e.name}"`,o=si(s,e);if("problem"in o)throw new Error(o.problem);if(!s.simulateSync)throw Qo(n);let{config:i,name:a}=o,d=s.orgName(i.targetOrgId)??i.targetOrgId,c;try{c=await s.simulateSync(i,t.signal)}catch(p){let f=Fp(p);if(f===void 0)throw p;return an(e,r,{configId:i.id,code:f},`${n} would be refused: ${p.message}`)}if(c.cancelled)throw new Rt(`${n} was stopped before its simulation read every object. Nothing was written.`);let u={configId:i.id,configName:a,operationId:c.operationId,objects:c.objects.map(p=>({objectApiName:p.objectApiName,operation:p.operation,read:p.read,insert:p.insert,update:p.update,delete:p.delete,skipped:p.skipped,refused:p.refused,...p.refusedFor?{refusedFor:p.refusedFor}:{},...p.delta?{delta:p.delta}:{}})),...c.readCap!==void 0?{readCap:c.readCap}:{},...c.cutAtReadCap?{cutAtReadCap:c.cutAtReadCap}:{}},l=oC(c.objects);return c.error?an(e,r,u,`${n} would stop on ${c.failedObject??"an object"}: ${c.error}`):c.objects.reduce((p,f)=>p+f.refused,0)>0?an(e,r,u,`${n} would run "${a}" into ${d} and not complete: ${l}${Ok(c)}${sC(c.objects)}. Nothing was written.`):cn(e,r,u,`Would sync "${a}" into ${d}: ${l}${Ok(c)}. Nothing was written.`)}}function lC(s){let e=s.previousResults.filter(t=>t.stepType==="approval");return{approved:e[e.length-1]?.status==="completed"}}function pC(s,e){return zv(s,e)}function gC(s,e){let t=`about ${dn(s.estimate,"API request")}`;return s.verdict==="unread"?`${t}; what ${e} has left today could not be read (${s.unread})`:`${t} of the ${s.remaining} ${e} has left today`}function fC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`,{orgId:o,templateId:i}=Vi.parse({orgId:e.config.orgId,templateId:ii(e.config.templateId)}),a=s.orgName(o)??o,d=Yo(o,i,l=>s.savedSeedTemplate?.(l));if("refusal"in d)return an(e,r,{orgId:o,templateId:i,code:d.refusal.code},`${n} would be refused: ${d.refusal.message}`);if(!s.previewSeed)throw Qo(n);let{template:c}=d.asked,u;try{u=await s.previewSeed({orgId:o,templateId:i,pipeline:{name:Ad(t)},answer:lC(t)},t.signal)}catch(l){let g=Fp(l);if(g===void 0)throw l;return an(e,r,{orgId:o,templateId:i,code:g},`${n} would be refused: ${l.message}`)}return cn(e,r,{orgId:o,templateId:i,records:u.records,objects:u.objects,storage:u.storage,apiRequests:u.apiRequests,...u.automation.length>0?{automation:u.automation}:{}},`Would seed "${c.name}" into ${a}: ${dn(u.records,"record")} of ${dn(u.objects,"object")}, as its template asks; ${pC(u.storage,a)}; ${gC(u.apiRequests,a)}. Nothing was written.`)}}function hC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.previewMasking)throw Qo(n);let o=ii(e.config.object),i=ii(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l}=Ss.parse({orgId:e.config.orgId,templateId:ii(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...Id(e.config)}),g=s.orgName(a)??a;try{let p=await s.previewMasking({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:u,muteAutomation:l},pipeline:{name:Ad(t)},answer:{approved:!0}},t.signal),f=p.objects.filter(h=>h.records>0).map(h=>`${h.records} of ${h.objectApiName} (${h.fields.join(", ")})`);return cn(e,r,{orgId:a,templateId:d,records:p.records,objects:p.objects},p.records===0?`Would mask nothing in ${g}: no row of ${p.objects.map(h=>h.objectApiName).join(", ")} holds anything to mask. Nothing was written.`:`Would mask ${dn(p.records,"record")} in ${g}: ${f.join("; ")}, after a snapshot of them. Nothing was written.`)}catch(p){let f=Fp(p);if(f===void 0)throw p;return an(e,r,{orgId:a,templateId:d,code:f},`${n} would be refused: ${p.message}`)}}}function mC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.estimateTake)throw Qo(n);let o=bn.parse(e.config),i=s.orgName(o.orgId)??o.orgId;try{let a=await s.estimateTake({config:o,origin:{pipeline:Ad(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return cn(e,r,{orgId:o.orgId,objects:a.objects,records:a.records,leftOut:a.leftOut,estimate:a.estimate},`Would take a checkpoint of ${i}: ${dn(a.records,"record")} of ${dn(a.objects,"object")} now, ${Ak(a.estimate)}. Nothing was taken.`)}catch(a){if(!(a instanceof Dr))throw a;return an(e,r,{orgId:o.orgId,code:a.code},`${n} would be refused: ${a.message}`)}}}function yC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewindGrant||!s.previewRewind)throw Qo(n);let o=$t.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return an(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},jn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId;try{let d=await s.previewRewind({config:o,grant:i.grant,origin:{pipeline:Ad(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return cn(e,r,{orgId:o.orgId,checkpointId:d.checkpointId,toDelete:d.toDelete,toGiveBack:d.toGiveBack,toBringBack:d.toBringBack,toRecreate:d.toRecreate,estimate:d.estimate},`Would rewind ${a} to the checkpoint ${d.checkpointId}: ${d.toDelete} to delete, ${d.toGiveBack} to give their values back, ${d.toBringBack} to bring back from the recycle bin`+(d.toRecreate>0?`, ${d.toRecreate} to make again with new Ids`:"")+`, ${Ak(d.estimate)}. Nothing was written.`)}catch(d){if(!(d instanceof Dr))throw d;return an(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:d.code,...d.alsoRefused.length>0?{alsoRefused:[...d.alsoRefused]}:{}},`${n} would be refused: ${d.message}`)}}}function Tk(s,e){s.wrapHandler("delay",()=>iC),s.wrapHandler("approval",()=>aC),s.wrapHandler("notification",()=>dC(e)),s.wrapHandler("backup",()=>cC(e)),s.wrapHandler("sync",()=>uC(e)),s.wrapHandler("seed",()=>fC(e)),s.wrapHandler("anonymize",()=>hC(e)),s.wrapHandler("checkpoint",()=>mC(e)),s.wrapHandler("rewind",()=>yC(e))}var Zo=new Map,Ek=(s,e)=>`${s}::${e}`;async function Qt(s,e,t,r=Date.now){let n=Ek(s,e),o=Zo.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();Zo.set(n,{at:r(),value:i});try{return await i}catch(a){throw Zo.get(n)?.value===i&&Zo.delete(n),a}}function Pk(s){let e=Ek(s,"");for(let t of Zo.keys())t.startsWith(e)&&Zo.delete(t)}var wC=V({orgId:j(),detectedAt:j(),evidence:We(["connection","monitor","production"]),previousOrganizationId:j().optional(),organizationId:j().optional(),previousInstanceName:j().optional(),instanceName:j().optional(),sandboxName:j().optional(),reportedBy:j().optional()}),bC=V({organizationId:j(),instanceName:j().optional(),formerOrganizationIds:ve(j()),refreshes:ve(wC)}),Ck="sandbox-refresh:",RC="sandbox-refresh",$k=10,vC=20,SC=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function _p(s){return s!==void 0&&SC.test(s)?s.slice(0,15):void 0}function xk(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function kC(s){let e=xk(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function OC(s,e,t){let r=t.toLowerCase(),n=kC(s);return n&&xk(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var Td=class{constructor(e){this.deps=e;this.now=e.now??(()=>new Date)}deps;listeners=new Set;now;onRefreshDetected(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}observe(e,t,r){let n=this.deps.orgManager.getOrg(e);if(n?.orgType!=="Sandbox")return;let o=_p(t.organizationId);if(!o)return;let i=this.read(e),a=i??this.baselineOf(n);if(!a){this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[],refreshes:[]});return}if(o===a.organizationId){let g=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||g)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,u=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,l={...u??{orgId:e,detectedAt:this.now().toISOString(),evidence:r},previousOrganizationId:a.organizationId,organizationId:o,previousInstanceName:a.instanceName,instanceName:t.instanceName};return this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[a.organizationId,...a.formerOrganizationIds].slice(0,vC),refreshes:(u?[l,...c]:[l,...a.refreshes]).slice(0,$k)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),u||this.emit(l),l}noteCompletedRefresh(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)return[];let r=[];for(let n of this.deps.orgManager.getAllOrgs()){if(n.orgType!=="Sandbox"||n.id===t.id||!OC(t,n,e.sandboxName))continue;let o=this.read(n.id)??this.baselineOf(n);if(!o)continue;let i=Date.parse(e.refreshDate);if(o.refreshes.some(c=>c.evidence!=="production"&&Date.parse(c.detectedAt)>=i))continue;let d={orgId:n.id,detectedAt:this.now().toISOString(),evidence:"production",sandboxName:e.sandboxName,reportedBy:t.id};this.write(n.id,{...o,refreshes:[d,...o.refreshes].slice(0,$k)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: ${t.alias} reports the refresh of "${e.sandboxName}"`),r.push(d),this.emit(d)}return r}refreshesOf(e){return this.read(e)?.refreshes??[]}organizationIdOf(e){return this.read(e)?.organizationId}wasRefreshedTo(e,t){let r=_p(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=_p(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${Ck}${e}`);if(t===void 0)return;let r=bC.safeParse(t);if(!r.success){this.deps.log?.(`[sandbox-refresh] ignoring an unreadable record for ${e}`);return}return r.data}write(e,t){this.deps.configStore.set(`${Ck}${e}`,t,RC)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){this.deps.log?.(`[sandbox-refresh] a listener failed: ${String(r)}`)}}};import{readFile as IC,writeFile as AC}from"node:fs/promises";import{homedir as TC}from"node:os";import{basename as Up}from"node:path";async function EC(){let[s,e,t,r,n,o,i,a,d,c,u]=await Promise.all([import("./chunk-BD724WOH.mjs"),import("./chunk-74HZ274R.mjs"),import("./chunk-ZDMSTL2L.mjs"),import("./chunk-6ZWY36LK.mjs"),import("./chunk-YSQJKIO6.mjs"),import("./chunk-IZREPWYQ.mjs"),import("./chunk-TIVI2KGB.mjs"),import("./chunk-LD34JNCC.mjs"),import("./chunk-A6IJUOLB.mjs"),import("./chunk-SBDF4AE5.mjs"),import("./chunk-GNCEHAJY.mjs")]);return{recoveryFactsOf:s.recoveryFactsOf,recoveryAckKeyOf:s.recoveryAckKeyOf,readAcks:s.readAcks,frozenDatasetDirOf:s.frozenDatasetDirOf,recoveryStatusOf:e.recoveryStatusOf,awaitingAddressesOf:t.awaitingAddressesOf,recoveryUsersOf:t.recoveryUsersOf,recoveryTestersKey:t.recoveryTestersKey,readSavedTesters:t.readSavedTesters,saveTesters:t.saveTesters,replacedRunOf:t.replacedRunOf,choicesKeyOf:t.choicesKeyOf,planSignatureOf:t.planSignatureOf,changingUsersOf:t.changingUsersOf,usersDoneOf:t.usersDoneOf,usersAuditObjectsOf:t.usersAuditObjectsOf,ObservedUsersRunStore:t.ObservedUsersRunStore,journalDirOf:r.journalDirOf,newestHandoffOf:r.newestHandoffOf,recoveryHandoffNoteOf:r.recoveryHandoffNoteOf,recoveryHandoffPathOf:r.recoveryHandoffPathOf,writeRecoveryHandoff:r.writeRecoveryHandoff,guardUsersOrg:n.guardUsersOrg,usersToRestoreOf:n.usersToRestoreOf,planUsersGated:n.planUsersGated,gatedPlanAnswerOf:n.gatedPlanAnswerOf,applyUsers:o.applyUsers,UsersRunStore:i.UsersRunStore,defaultUsersStoreRoot:i.defaultUsersStoreRoot,readAudits:a.readAudits,myDomainHostOf:d.myDomainHostOf,openCheckpointStore:c.openCheckpointStore,defaultCheckpointStoreRoot:c.defaultCheckpointStoreRoot,ReplayStore:u.ReplayStore,defaultReplayStoreRoot:u.defaultReplayStoreRoot}}var PC=new Set(["recovery:status","recovery:users:list","recovery:users:plan","recovery:users:apply","recovery:users:cancel","recovery:users:config:save","recovery:users:config:export","recovery:users:config:import","recovery:audit","recovery:handoff","recovery:handoff:open","recovery:ack"]),tt=class extends Error{constructor(t,r,n=!1,o){super(r);this.code=t;this.retryable=n;this.step=o;this.name="Refused"}code;retryable;step},Dk="SandForge writes and reads a users.json on the disk of the machine it runs on: pick a folder there.",CC={async pickUsersExport(s){let e=await import("vscode"),t=await e.window.showSaveDialog({title:e.l10n.t("Export the testers list as users.json"),saveLabel:e.l10n.t("Export"),defaultUri:e.Uri.joinPath(e.Uri.file(TC()),s),filters:{JSON:["json"]}});if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",Dk);return t.fsPath}},async pickUsersImport(){let s=await import("vscode"),t=(await s.window.showOpenDialog({title:s.l10n.t("Import the testers list from a users.json"),openLabel:s.l10n.t("Import"),canSelectFiles:!0,canSelectFolders:!1,canSelectMany:!1,filters:{JSON:["json"]}}))?.[0];if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",Dk);return t.fsPath}}},$C=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})};function xC(s,e,t){return{org:s,users:[],emailsToPeople:0,apiRequests:t,refusals:[e]}}function DC(s){let e=0,t=0,r=0;for(let n of s.users){n.changes.some(o=>!("name"in o))&&(e+=1);for(let o of n.changes)"name"in o&&(o.to==="added"?t+=1:r+=1)}return{updated:e,added:t,removed:r}}function Hp(s,e){return s.length>=15&&s.slice(0,15)===e.slice(0,15)}var NC=4e3,Ed=class{constructor(e,t={}){this.deps=e;this.options=t;this.dialogs=t.dialogs??CC,this.openInEditor=t.openInEditor??$C,this.now=t.now??(()=>new Date),t.checkpointStore&&(this.checkpoints=Promise.resolve(t.checkpointStore)),t.usersStore&&(this.usersStore=t.usersStore),t.replayStore&&(this.replayStore=t.replayStore)}deps;options;loaded;checkpoints;usersStore;replayStore;dialogs;openInEditor;now;running=new Map;simulated=new Map;listed=new Map;audited=new Map;statusListeners=new Set;setCheckpointStore(e){this.checkpoints=Promise.resolve(e)}onStatusChanged(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}async progressCountOf(e){let t=await this.modules(),r=await t.recoveryFactsOf(this.factsDeps(t),e);if(!("facts"in r))return;let n=t.recoveryStatusOf(r.facts);return{done:n.done,total:n.total}}async handle(e){if(!PC.has(e.type))return!1;switch(e.type){case"recovery:status":return await this.handleStatus(e),!0;case"recovery:users:list":return await this.handleUsersList(e),!0;case"recovery:users:plan":return await this.handleUsersPlan(e),!0;case"recovery:users:apply":return await this.handleUsersApply(e),!0;case"recovery:users:cancel":return this.handleUsersCancel(e),!0;case"recovery:users:config:save":return await this.handleConfigSave(e),!0;case"recovery:users:config:export":return await this.handleConfigExport(e),!0;case"recovery:users:config:import":return await this.handleConfigImport(e),!0;case"recovery:audit":return await this.handleAudit(e),!0;case"recovery:handoff":return await this.handleHandoff(e),!0;case"recovery:handoff:open":return await this.handleHandoffOpen(e),!0;case"recovery:ack":return await this.handleAck(e),!0;default:return!1}}async handleStatus(e){let t=$(Kn,e,"recovery:error",this.deps);if(t)try{let r=await this.statusOf(t.orgId);this.respond(e,"recovery:status:response",{status:r})}catch(r){this.fail(e,r)}}async handleAck(e){let t=$(Pf,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=this.deps.sandboxRefreshes,i=r.orgType==="Sandbox"?o?.refreshesOf(t.orgId)[0]:void 0,a=n.recoveryAckKeyOf(t.orgId,i,u=>o?.organizationIdOf(u)),d=n.readAcks(this.deps.configStore,a);t.what==="finish"?d.finishedAt=this.now().toISOString():t.what==="resume"?delete d.finishedAt:t.mark==="cleared"?delete d.steps[t.step]:d.steps[t.step]=t.mark,this.deps.configStore.set(a,Tf.parse(d),"recovery");let c=await this.statusOf(t.orgId);this.respond(e,"recovery:ack:response",{status:c}),this.changed(t.orgId)}catch(r){this.fail(e,r)}}async handleUsersList(e){let t=$(Kn,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId,"users"),o=await r.usersToRestoreOf(n.org),i=await this.users(r).list(n.organization.organizationId),a=r.recoveryUsersOf(o.users,r.awaitingAddressesOf(i));this.listed.set(t.orgId,{organizationId:n.organization.organizationId,total:o.total});let d=r.readSavedTesters(this.deps.configStore,r.recoveryTestersKey(r.myDomainHostOf(n.registered.instanceUrl),t.orgId));this.respond(e,"recovery:users:list:response",{orgId:t.orgId,users:a,total:o.total,...d!==void 0?{saved:d}:{}}),this.changed(t.orgId)}catch(r){this.fail(e,r,"users")}}async handleUsersPlan(e){let t=$(Ku,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId,"users"),{answer:o}=await this.planOf(r,n,t);this.simulated.set(t.orgId,{choices:r.choicesKeyOf(t),signature:r.planSignatureOf(o)}),this.respond(e,"recovery:users:plan:response",{orgId:t.orgId,plan:o})}catch(r){this.fail(e,r,"users")}}async handleUsersApply(e){let t=$(Ku,e,"recovery:error",this.deps);if(!t)return;let{orgId:r}=t;if(this.running.has(r)){this.fail(e,new tt("FAILED","A run of the users of this org is under way from this window: wait for it to end. Nothing was read or written.",!0,"users"));return}let n=new AbortController;this.running.set(r,n);try{let o=await this.modules(),i=this.simulated.get(r);if(i===void 0||i.choices!==o.choicesKeyOf(t))throw new tt("ORG_CHANGED","No simulation of these choices was answered on this page: simulate them, then apply. Nothing was read or written.",!1,"users");let a=await this.reach(o,r,"users"),{answer:d,gated:c}=await this.planOf(o,a,t);if(o.planSignatureOf(d)!==i.signature)throw new tt("ORG_CHANGED",`${a.orgName} changed since the simulation: a run now would not do what it showed. Simulate again. Nothing was written.`,!1,"users");let u=d.refusals??[];if(c===void 0||u.length>0)throw new tt("FAILED",`${u.map(y=>y.message).join(" ")} Nothing was written.`.trim(),!1,"users");let l=await this.consultGuard(e,a,d);if(n.signal.aborted)throw this.recordUsersRun(e,r,"stopped",l),new tt("CANCELLED","Stopped before the first write: nothing was written.");let g=o.changingUsersOf(d),p=y=>{this.deps.broker.postToWebview(A(this.deps,e,"recovery:users:progress",{orgId:r,done:y,total:g}))};p(0);let f=new o.ObservedUsersRunStore({root:this.users(o).root},y=>p(o.usersDoneOf(y,d))),h;try{h=await o.applyUsers({org:a.org,organization:a.organization,users:Vu(t.config),store:f,signal:n.signal,...c.options})}catch(y){throw this.recordUsersRun(e,r,"failure",l),y}if(h.kind==="refused")throw this.recordUsersRun(e,r,"stopped",l),new tt("ORG_CHANGED",`${a.orgName} changed since the plan read it: ${(h.plan.refusals??[]).map(y=>y.message).join(" ")} Nothing was written.`,!1,"users");let m={...h.answer,apiRequests:a.typingRequests+a.org.requests()+c.outsideRequests};this.recordUsersRun(e,r,m.status,l,m,o),this.respond(e,"recovery:users:apply:response",{orgId:r,applied:m})}catch(o){this.fail(e,o,"users")}finally{this.running.delete(r),this.simulated.delete(r),this.changed(r)}}handleUsersCancel(e){let t=$(Kn,e,"recovery:error",this.deps);t&&this.running.get(t.orgId)?.abort()}async planOf(e,t,r){let{org:n,organization:o}=t,i=u=>t.typingRequests+n.requests()+u,a;if(r.replaces!==void 0){let u=await e.replacedRunOf(this.users(e),o.organizationId,r.replaces);if("refusal"in u)return{answer:xC(o,u.refusal,i(0))};a=u.record}let d=await e.planUsersGated({conn:t.conn,org:n,orgName:t.orgName,users:Vu(r.config),...a!==void 0?{previous:a}:{},acceptUserEmails:r.acceptUserEmails,acceptEmails:r.acceptEmails,acceptAutomation:r.acceptAutomation,voice:"page",now:this.now()});return{answer:e.gatedPlanAnswerOf(d,o,i(d.outsideRequests)),gated:d}}async consultGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw new tt("FAILED",Re.message,!1,"users");let o=Pe(t.registered),{updated:i,added:a,removed:d}=DC(r),c=[{operation:"delete",objectName:"PermissionSetAssignment, GroupMember",recordCount:d},{operation:"update",objectName:"User, UserLogin",recordCount:i},{operation:"insert",objectName:"PermissionSetAssignment, GroupMember",recordCount:a}].filter(l=>l.recordCount>0),u="allowed";for(let l of c){let g=await et(n,{orgId:t.registered.id,orgTier:o,module:"recovery",...l});if(u=eo(u,g.decision),g.decision==="refused")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("FAILED",`Operation blocked by Production Guard: ${g.check.blockedReason??g.check.impactSummary} Nothing was written.`,!1,"users");if(g.decision==="declined")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("CANCELLED",`Production Guard asked before this run (${g.check.impactSummary}), and the answer was no. Nothing was written.`,!1,"users")}return u}recordUsersRun(e,t,r,n,o,i){Q(this.deps,{action:"users_apply",module:"recovery",operationId:e.id,orgId:t,outcome:r,guard:n,...o!==void 0&&i!==void 0?{objects:i.usersAuditObjectsOf(o)}:{},details:o!==void 0?{run:o.run,emailsToPeople:o.emailsToPeople}:{}})}async handleConfigSave(e){let t=$(Xu,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=n.saveTesters(this.deps.configStore,n.recoveryTestersKey(n.myDomainHostOf(r.instanceUrl),t.orgId),t.config,this.now());this.respond(e,"recovery:users:config:save:response",{orgId:t.orgId,savedAt:o.savedAt}),this.changed(t.orgId)}catch(r){this.fail(e,r,"users")}}async handleConfigExport(e){let t=$(Xu,e,"recovery:error",this.deps);if(!t)return;let r;try{if(this.registered(t.orgId),r=await this.dialogs.pickUsersExport("users.json"),r===void 0){this.respond(e,"recovery:users:config:export:response",{status:"cancelled",orgId:t.orgId});return}await AC(r,`${JSON.stringify(t.config,null,2)}
|
|
15
|
-
`,{encoding:"utf8",mode:384}),this.respond(e,"recovery:users:config:export:response",{status:"saved",orgId:t.orgId,fileName:Up(r)})}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleConfigImport(e){let t=$(Kn,e,"recovery:error",this.deps);if(!t)return;let r;try{let n=this.registered(t.orgId);if(r=await this.dialogs.pickUsersImport(),r===void 0){this.respond(e,"recovery:users:config:import:response",{status:"cancelled",orgId:t.orgId});return}let o=Up(r),i;try{i=JSON.parse(await IC(r,"utf8"))}catch(c){throw new tt("INVALID_PAYLOAD",`${o} does not read as JSON (${I(c)}). Nothing was kept.`,!1,"users")}let a=Af.safeParse(i);if(!a.success){let c=a.error.issues.map(u=>{let l=u.path.map(String).join(".");return l===""?u.message:`${l}: ${u.message}`});throw new tt("INVALID_PAYLOAD",`${o} is not a users.json of sandforge users --config: ${c.join("; ")}. Nothing was kept.`,!1,"users")}let d=await this.modules();d.saveTesters(this.deps.configStore,d.recoveryTestersKey(d.myDomainHostOf(n.instanceUrl),t.orgId),a.data,this.now()),this.respond(e,"recovery:users:config:import:response",{status:"read",orgId:t.orgId,fileName:o,config:a.data}),this.changed(t.orgId)}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleAudit(e){let t=$(Ef,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId),{conn:o,organization:i}=n,a=r.myDomainHostOf(o.instanceUrl)??r.myDomainHostOf(n.registered.instanceUrl),d=await r.readAudits({transport:{request:l=>o.request(l)},journalDir:this.journalDir(r),now:this.now},{org:{organizationId:i.organizationId,kind:i.kind,alias:n.orgName,...a!==void 0?{host:a}:{}},asked:t.asked,save:t.save});for(let l of d.notes)this.deps.log(`[INFO] recovery:audit: ${l}`);let c=this.audited.get(t.orgId),u=c!==void 0&&Hp(c.organizationId,i.organizationId)?c.audit:{};this.audited.set(t.orgId,{organizationId:i.organizationId,audit:{...u,...d.result.deliverability!==void 0?{deliverability:d.result.deliverability}:{},...d.result.schedules!==void 0?{schedules:d.result.schedules}:{},...d.result.endpoints!==void 0?{endpoints:d.result.endpoints}:{}}}),this.respond(e,"recovery:audit:response",{orgId:t.orgId,audit:d.result}),this.changed(t.orgId)}catch(r){this.fail(e,r)}}async handleHandoff(e){let t=$(Kn,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=await this.statusOf(t.orgId),i=o.organizationId;if(i===void 0)throw new tt("NOT_CONNECTED",`The org ${o.alias} is now is not known yet: only its production's history reported its refresh. Connect to it once, then write the note. Nothing was written.`,!0,"handoff");let a=this.now().toISOString(),d=this.audited.get(t.orgId),c=n.recoveryHandoffNoteOf({status:o,org:{organizationId:i,kind:r.orgType==="Sandbox"?"sandbox":r.orgType==="Scratch"?"scratch":"developer",alias:o.alias,...o.myDomainHost!==void 0?{host:o.myDomainHost}:{}},...d!==void 0&&Hp(d.organizationId,i)?{audits:d.audit}:{},at:a,...this.options.sandforgeVersion!==void 0?{sandforgeVersion:this.options.sandforgeVersion}:{}}),u=n.recoveryHandoffPathOf(this.journalDir(n),{organizationId:i,at:a});await n.writeRecoveryHandoff(u,c);try{await this.openInEditor(u)}catch(l){this.deps.log(`[WARN] recovery:handoff: the note was not opened: ${I(l)}`)}this.respond(e,"recovery:handoff:response",{orgId:t.orgId,path:u}),this.changed(t.orgId)}catch(r){this.fail(e,r,"handoff")}}async handleHandoffOpen(e){let t=$(Kn,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.statusOf(t.orgId),o=n.organizationId!==void 0?await r.newestHandoffOf(this.journalDir(r),n.organizationId):void 0;if(o===void 0)throw new tt("NOTE_NOT_FOUND",`No handoff note of ${n.alias} as it is now is kept on this machine: write one. Nothing was written.`,!1,"handoff");try{await this.openInEditor(o.path)}catch(i){throw new tt("FAILED",`The handoff note could not be opened in the editor: ${I(i)}`,!0,"handoff")}this.respond(e,"recovery:handoff:open:response",{orgId:t.orgId,path:o.path})}catch(r){this.fail(e,r,"handoff")}}modules(){return this.loaded??=EC(),this.loaded}async openedCheckpoints(e){this.checkpoints??=Promise.resolve().then(()=>{let t=e.openCheckpointStore({root:e.defaultCheckpointStoreRoot()});if("store"in t)return t.store;throw new tt("FAILED",`The checkpoints cannot be read in ${t.refusal.path}: ${t.refusal.reason}.`)});try{return await this.checkpoints}catch(t){throw this.checkpoints=void 0,t}}users(e){return this.usersStore??=new e.UsersRunStore({root:e.defaultUsersStoreRoot()}),this.usersStore}replays(e){return this.replayStore??=new e.ReplayStore({root:e.defaultReplayStoreRoot()}),this.replayStore}journalDir(e){return this.options.journalDir??e.journalDirOf()}factsDeps(e){let t=this.deps.sandboxRefreshes;return{configStore:this.deps.configStore,orgOf:r=>this.deps.orgManager.getOrg(r),refreshesOf:r=>t?.refreshesOf(r)??[],organizationIdOf:r=>t?.organizationIdOf(r),checkpoints:()=>this.openedCheckpoints(e),replays:()=>this.replays(e),users:()=>this.users(e),journalDir:this.journalDir(e),frozenDatasetDir:()=>e.frozenDatasetDirOf(this.deps.configStore),usersListed:(r,n)=>{let o=this.listed.get(r);return o!==void 0&&Hp(o.organizationId,n)?o.total:void 0}}}async statusOf(e){let t=await this.modules(),r=await t.recoveryFactsOf(this.factsDeps(t),e);if("refused"in r)throw this.registered(e),new tt(r.refused,`${e} is not an org SandForge brings back into service.`);return t.recoveryStatusOf(r.facts)}registered(e,t){let r=this.deps.orgManager.getOrg(e);if(r===void 0)throw new tt("ORG_NOT_FOUND",`No org is registered in SandForge as ${e}: connect it on the Organizations page.`,!1,t);if(!vo(r))throw new tt("NOT_A_DEVELOPMENT_ORG",`${ye(r,r.username)} is registered as a production org: SandForge brings back into service a sandbox, a scratch org or a Developer Edition org, and reads nothing of a production org's. Nothing was read or written.`,!1,t);return r}async reach(e,t,r){let n=this.registered(t,r),o=ye(n,n.username),i;try{i=await q(t,this.deps.orgRegistry,this.deps.orgManager)}catch(d){throw new tt("NOT_CONNECTED",`${o} could not be reached (${I(d)}): reconnect it on the Organizations page. Nothing was read or written.`,!0,r)}let a=await e.guardUsersOrg(i,{orgName:o,registered:n});if(!a.allowed){let{refusal:d}=a;throw new tt(d.code==="PRODUCTION"?"NOT_A_DEVELOPMENT_ORG":"NOT_CONNECTED",d.message,d.code==="ORG_UNTYPED",r)}return{registered:n,orgName:o,conn:i,org:a.org,organization:a.organization,typingRequests:a.typingRequests}}changed(e){for(let t of[...this.statusListeners])try{t(e)}catch(r){this.deps.log(`[WARN] recovery: a listener of the steps failed: ${I(r)}`)}}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}pathless(e,t){return e instanceof tt||t===void 0?e:new Error(I(e).replaceAll(t,Up(t)))}fail(e,t,r){let n=t instanceof tt?t:new tt("FAILED",I(t),!0,r),o=n.message.trim()===""?n.code:n.message,i=n.step??r;E(this.deps,e.type,"recovery:error",e,new Error(o.slice(0,NC)),{code:n.code,retryable:n.retryable,...i!==void 0?{extraPayload:{step:i}}:{}})}};var jC=5,MC=5e3,LC=3e4,FC=V({device_code:j().min(1).max(4096),user_code:j().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:j().min(1).max(2048),interval:Te().int().positive().max(300).optional(),expires_in:Te().int().positive().optional()}),_C=V({access_token:j().min(1),refresh_token:j().min(1).optional(),instance_url:j().min(1).max(2048)}),Nk=V({error:j().min(1),error_description:j().optional()}),so=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},Pd=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function UC(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new so);return}let n=()=>{clearTimeout(o),r(new so)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function Mk(s){let e=Mn(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!dh(e.url.hostname)))return e.url}function jk(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var Cd=class{fetchFn;now;sleep;constructor(e={}){this.fetchFn=e.fetch??((t,r)=>fetch(t,r)),this.now=e.now??Date.now,this.sleep=e.sleep??UC}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=Nk.safeParse(n);if(o.success)throw new Error(jk(o.data));let i=FC.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=Mk(i.data.verification_uri);if(!a)throw new Error("Salesforce sent a verification page that is not on a Salesforce host.");let d=Math.min((i.data.expires_in??Number.POSITIVE_INFINITY)*1e3,ff);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??jC)*1e3,expiresAt:this.now()+d}}async awaitApproval(e,t,r,n){let o=r.intervalMs;for(;;){let i=r.expiresAt-this.now();if(i<=0||(await this.sleep(Math.min(o,i),n),this.now()>=r.expiresAt))break;let a;try{a=await this.post(e,{grant_type:"device",client_id:t,code:r.deviceCode},n)}catch(c){if(n?.aborted)throw new so;if(c instanceof Pd)throw c;continue}let d=Nk.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=MC;continue}throw new Error(jk(d.data))}return HC(a)}throw new Error("The code expired before it was approved. Start the sign-in again for a new one.")}async post(e,t,r){if(r?.aborted)throw new so;let n=AbortSignal.timeout(LC),o;try{o=await this.fetchFn(`${e}/services/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(t).toString(),signal:r?AbortSignal.any([r,n]):n})}catch(a){throw r?.aborted?new so:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new Pd(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function HC(s){let e=_C.safeParse(s);if(!e.success)throw new Error("Salesforce approved the sign-in without an access token and an instance URL.");if(!e.data.refresh_token)throw new Error('Salesforce signed you in without a refresh token, so the Salesforce CLI could not keep the session. Give the external client app the "Perform requests at any time (refresh_token, offline_access)" scope, then sign in again.');let t=Mk(e.data.instance_url);if(!t||t.pathname!=="/"||t.search!==""||t.hash!=="")throw new Error("Salesforce approved the sign-in for an instance that is not a Salesforce host.");return{refreshToken:e.data.refresh_token,instanceUrl:t.origin}}var Mr=class{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{openExternal:t=>e.env.openExternal(t),parseUri:t=>e.Uri.parse(t,!0)}}async open(e){let t=this.host??await this.defaultHost();try{return await t.openExternal(t.parseUri(e))?{status:"opened"}:{status:"error",message:"VS Code did not open the page."}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}};import{readFile as BC,readdir as qC}from"node:fs/promises";import{join as Lk}from"node:path";var WC=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function Fk(s,e=Date.now()){let t=Lk(s,".sfdx"),r;try{r=await qC(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>WC.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await zC(Lk(t,o),e);i&&n.add(i)})),n.size}async function zC(s,e){try{let t=JSON.parse(await BC(s,"utf8"));if(typeof t!="object"||t===null)return;let{orgId:r,username:n,expirationDate:o}=t;if(typeof r!="string"||r===""||typeof n!="string")return;if(typeof o=="string"){let i=Date.parse(o);if(Number.isFinite(i)&&i+1440*60*1e3<=e)return}return r}catch{return}}import{homedir as GC}from"node:os";var JC=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status","org:assign-right"]),_k=15e3,Uk="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",$d=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new Mr,this.deviceLogin=t.deviceLogin??new Cd,this.countCliOrgs=t.countCliOrgs??(()=>Fk(GC())),this.connectTo=t.connectTo??(r=>wh(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!JC.has(e.type))return!1;switch(e.type){case"org:list":return this.handleOrgList(e),!0;case"org:connect":return await this.handleOrgConnect(e),!0;case"org:connect:cancel":return this.handleConnectCancel(e),!0;case"org:disconnect":return await this.handleOrgDisconnect(e),!0;case"org:select":return this.handleOrgSelect(e),!0;case"org:update":return this.handleOrgUpdate(e),!0;case"org:open-in-browser":return await this.handleOpenInBrowser(e),!0;case"org:cli-status":return await this.handleCliStatus(e),!0;case"org:assign-right":return await this.handleAssignRight(e),!0;default:return!1}}async handleCliStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let[t,r]=await Promise.all([this.deps.sfdxBridge.isCliAvailable().catch(()=>!1),this.countCliOrgs().catch(()=>0)]),n=A(this.deps,e,"org:cli-status:response",{available:t,orgCount:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleAssignRight(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(tw,e,"org:error",this.deps);if(!t)return;let r=!1;try{let o=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager);r=await Sb({query:async i=>o.query(i)})}catch(o){this.deps.log(`[WARN] org:assign-right: not read: ${I(o)}`)}let n=A(this.deps,e,"org:assign-right:response",{orgId:t.orgId,...r?{cannotAssign:!0}:{}});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.orgManager.getAllOrgs(),r=A(this.deps,e,"org:list:response",{orgs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleOrgConnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Vy,e,"org:error",this.deps);if(!t)return;let r=t;switch(r.authMethod){case"sfdx_import":await this.handleSfdxImport(e);break;case"usernamePassword":await this.handleUsernamePassword(e,r);break;case"oauth_web":await this.handleOAuthWeb(e,r);break;case"jwt":await this.handleJwt(e);break;case"oauth_device":await this.handleOAuthDevice(e);break;default:Ie(this.deps,"warning","Auth Method",`${r.authMethod} is not yet supported.`),this.failConnect(e,`${r.authMethod} is not yet supported.`,"UNSUPPORTED_AUTH");break}this.syncOrgState()}failConnect(e,t,r){E(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Ie(this.deps,"error","Salesforce CLI",`${ms} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:gf}]})}ackConnect(e,t){let r=A(this.deps,e,"org:statusChanged",{orgId:t,status:"connected"});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleSfdxImport(e){try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("Importing orgs from the CLI needs it."),this.failConnect(e,ms,"SF_CLI_NOT_FOUND");return}let r=[],n=await this.deps.sfdxBridge.listOrgs(d=>{r.push(d)});if(n.length===0&&r.length>0){let d=this.reportUnreadable(r);Ie(this.deps,"error","Import Failed",d),this.failConnect(e,d,"SFDX_IMPORT_FAILED");return}if(n.length===0){Ie(this.deps,"info","Import",Uk,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,Uk,"NO_CLI_ORGS");return}let o=await this.saveImported(n),i=this.deps.orgManager.getAllOrgs(),a=A(this.deps,e,"org:list:response",{orgs:i});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`),Ie(this.deps,"success","Import",`Imported ${n.length} org(s) from SF CLI.`),r.length>0&&Ie(this.deps,"warning","Import",this.reportUnreadable(r),{autoDismissMs:null}),this.ackConnect(e,o[0])}catch(t){let r=I(t);this.deps.log(`[ERR] org:sfdx-import: ${r}`),Ie(this.deps,"error","Import Failed",r),this.failConnect(e,r,"SFDX_IMPORT_FAILED")}}reportUnreadable(e){for(let o of e)this.deps.log(`[WARN] org:import: ${o.why==="notConnected"?"not connected":"no access token for"} ${o.alias??o.username}: ${o.reason}`);let t=o=>o.map(i=>`${ye(i)} (${i.reason})`).join("; "),r=e.filter(o=>o.why!=="notConnected"),n=e.filter(o=>o.why==="notConnected");return[...n.length>0?[`The Salesforce CLI cannot reach these orgs, so they were not imported: ${t(n)}. Log in to each again with the CLI, or use Log in with your browser; a scratch org past its date is gone, create a new one.`]:[],...r.length>0?[`No access token from the Salesforce CLI, so not imported: ${t(r)}`]:[]].join(" ")}async saveImported(e){let t=await Promise.all(e.map(n=>this.typedImport(n))),r=[];for(let{org:n,credentials:o}of t){let i=this.refreshedEntryFor(n);i&&this.deps.log(`[INFO] org:import: ${i.alias} was refreshed into org ${n.orgId}; its entry is updated`);let a=i?{...n,id:i.id}:n;await this.deps.orgRegistry.saveOrg(a,o),r.push(a.id)}return r}async typedImport(e){let{org:t,credentials:r}=e;if(t.orgType!=="Production"||(t.metadata.edition??"")!=="")return e;let{accessToken:n,instanceUrl:o}=r;if(!n||!o)return e;try{let i=await fh(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(u=>Qi(u)),_k,`the org did not answer within ${_k/1e3} s`),a=Xn({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=Wr(a);return a!==t.orgType&&this.deps.log(`[INFO] org:import: ${t.alias} says it is ${i.edition??(i.sandbox?"a sandbox":"no edition")}; typed ${a}`),{credentials:r,org:{...t,orgType:a,safetyTier:d,appearance:{...t.appearance,color:c},metadata:{...t.metadata,edition:i.edition??""}}}}catch(i){return this.deps.log(`[WARN] org:import: ${t.alias} gave no edition and could not be asked what it is (${I(i)}): typed Production until it is reconnected`),e}}refreshedEntryFor(e){let t=this.deps.sandboxRefreshes;if(!t||this.deps.orgManager.getOrg(e.id))return;let r=e.username.toLowerCase();return this.deps.orgManager.getAllOrgs().find(n=>n.username.toLowerCase()===r&&t.wasRefreshedTo(n.id,e.orgId))}async handleUsernamePassword(e,t){if(!t.username||!t.password){Ie(this.deps,"error","Auth","Username and password are required."),this.failConnect(e,"Username and password are required.","MISSING_CREDENTIALS");return}let r=this.resolveLoginUrl(e,t);if(!r)return;let n=await this.deps.authProvider.authenticate({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken});if(!n.success||!n.accessToken||!n.instanceUrl){Ie(this.deps,"error","Auth Failed",n.error??"Authentication failed"),this.failConnect(e,n.error??"Authentication failed","AUTH_FAILED");return}try{let o=await this.deps.authProvider.validateConnection(n.accessToken,n.instanceUrl),i=Xn({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=Wr(i),c={id:o.orgId,alias:t.alias??t.username??o.username,username:o.username,...o.orgName?{organizationName:o.orgName}:{},instanceUrl:n.instanceUrl,orgId:o.orgId,orgType:i,authMethod:"usernamePassword",safetyTier:a,appearance:{color:d,icon:"cloud",position:0},metadata:{apiVersion:bo.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},u=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,u);let l=A(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`),Ie(this.deps,"success","Connected",`${ye(c)} connected.`)}catch(o){let i=I(o);this.deps.log(`[ERR] org:username-password: ${i}`),Ie(this.deps,"error","Validation Failed",`Auth succeeded but org validation failed: ${i}`),this.failConnect(e,`Auth succeeded but org validation failed: ${i}`,"ORG_VALIDATION_FAILED")}}resolveLoginUrl(e,t){let r=t.loginUrl??"https://login.salesforce.com",n=Yi(r);if(n.ok)return n.origin;let o=n.reason==="not-https"?"Login URL must use HTTPS.":n.reason==="not-salesforce"?`Login URL must be a Salesforce login host (login.salesforce.com, test.salesforce.com or a My Domain): "${r}". For an org on another Salesforce cloud, log in with "sf org login web --instance-url <url>", then add it with Import from Salesforce CLI.`:n.reason==="not-origin"?`Login URL must name a host only, with no path, query or credentials: "${r}".`:`Invalid login URL: "${r}".`;Ie(this.deps,"error","Auth",o),this.failConnect(e,o,"INVALID_LOGIN_URL")}async handleOAuthWeb(e,t){let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("OAuth web login runs through it."),this.failConnect(e,ms,"SF_CLI_NOT_FOUND");return}let o=t.alias??"",i=await this.deps.sfdxBridge.loginWeb(o,r);await this.importSignedInOrg(e,i,"OAuth")}catch(n){let o=I(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),Ie(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=$(Ky,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.requireCli(e,"JWT sign-in runs through it."))return;let n=await this.deps.sfdxBridge.loginJwt({username:t.username,clientId:t.clientId,keyFile:t.jwtKeyFile,loginUrl:r,alias:t.alias||void 0});await this.importSignedInOrg(e,n,"JWT")}catch(n){let o=I(n);this.deps.log(`[ERR] org:jwt: ${o}`),Ie(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=$(Xy,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(!r)return;let n=new AbortController;this.pendingSignIns.set(e.id,n);try{if(!await this.requireCli(e,"The device sign-in hands its session to it."))return;let o=await this.deviceLogin.authorize(r,t.clientId,n.signal),i=A(this.deps,e,"org:device-code",{userCode:o.userCode,verificationUri:o.verificationUri,expiresAt:o.expiresAt});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`);let a=await this.browser.open(o.verificationUri);a.status==="error"&&this.deps.log(`[WARN] org:oauth-device: verification page not opened: ${a.message}`);let d=await this.deviceLogin.awaitApproval(r,t.clientId,o,n.signal);if(n.signal.aborted)throw new Error("Sign-in cancelled.");let c=await this.deps.sfdxBridge.loginWithRefreshToken({clientId:t.clientId,refreshToken:d.refreshToken,instanceUrl:d.instanceUrl,alias:t.alias||void 0});await this.importSignedInOrg(e,c,"Device Sign-in")}catch(o){if(n.signal.aborted){this.deps.log(`[INFO] org:oauth-device cancelled id=${e.id}`),this.failConnect(e,"Sign-in cancelled.","CANCELLED");return}let i=I(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),Ie(this.deps,"error","Device Sign-in Failed",i),this.failConnect(e,i,"OAUTH_DEVICE_FAILED")}finally{this.pendingSignIns.delete(e.id)}}handleConnectCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yy,e,"org:error",this.deps);t&&this.pendingSignIns.get(t.requestId)?.abort()}async requireCli(e,t){return await this.deps.sfdxBridge.isCliAvailable()?!0:(this.notifyCliMissing(t),this.failConnect(e,ms,"SF_CLI_NOT_FOUND"),!1)}async importSignedInOrg(e,t,r){let n=await this.deps.sfdxBridge.findOrg(t.username);if(!n)throw new Error(`Signed in as ${t.username}, but "sf org display" does not show that org as connected.`);let[o]=await this.saveImported([n]);Ie(this.deps,"success",r,`${ye(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Qy,e,"org:error",this.deps);if(!t)return;let r=t;Io().remove(r.orgId),await this.deps.orgRegistry.removeOrg(r.orgId);let n=A(this.deps,e,"org:statusChanged",{orgId:r.orgId,status:"disconnected"});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}handleOrgSelect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Zy,e,"org:error",this.deps);if(!t)return;let{orgId:r}=t;if(!this.deps.orgManager.getOrg(r)){Ie(this.deps,"warning","Orgs",`Unknown org: ${r}`);return}this.deps.onOrgSelected?.(r);let n=A(this.deps,e,"org:selected",{orgId:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(rw,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"org:update","org:error",e,new Error(`Unknown org: ${t.orgId}`),{code:"ORG_NOT_FOUND",retryable:!1});return}try{this.deps.orgRegistry.updateOrgMetadata({...r,alias:t.alias,appearance:{...r.appearance,color:t.color},tags:t.tags,...t.staging!==void 0?{staging:t.staging}:{}})}catch(o){E(this.deps,"org:update","org:error",e,o,{code:"ORG_UPDATE_FAILED",retryable:!0});return}let n=A(this.deps,e,"org:list:response",{orgs:this.deps.orgManager.getAllOrgs()});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}async handleOpenInBrowser(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ew,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"org:open-in-browser","org:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND",retryable:!1});return}let n=Mn(r.instanceUrl);if(!n.ok){let a=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";E(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${ye(r)}": ${a}.`),{code:"INVALID_INSTANCE_URL",retryable:!1});return}let o=await this.browser.open(n.url.toString());o.status==="error"&&this.deps.log(`[WARN] org:open-in-browser: not opened: ${o.message}`);let i=A(this.deps,e,"org:open-in-browser:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}syncOrgState(){let e=this.deps.orgManager.getAllOrgs();this.deps.stateSync.updateState({orgs:e})}};function VC(s){let e=bf.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}var KC=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),xd=class{constructor(e){this.deps=e}deps;async handle(e){if(!KC.has(e.type))return!1;switch(e.type){case"settings:get":return this.handleSettingsGet(e),!0;case"settings:update":return this.handleSettingsUpdate(e),!0;case"telemetry:status":return this.handleTelemetryStatus(e),!0;case"telemetry:toggle":return await this.handleTelemetryToggle(e),!0;default:return!1}}postSettings(){this.deps.broker.postToWebview({id:this.deps.nextId(),type:"settings:response",timestamp:Date.now(),payload:this.settingsPayload()})}settingsPayload(){return{settings:this.deps.configStore.getByCategory("settings"),forgeGraphView:VC(this.deps)}}handleSettingsGet(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(t),this.deps.log(`[TX] ${t.type} id=${t.id}`)}handleSettingsUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(nw,e,"settings:error",this.deps);if(!t)return;let r=t;this.deps.configStore.set(r.key,r.value,"settings");let n=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleTelemetryStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,r=this.deps.services?.telemetry.getTelemetryEventCount()??0,n=A(this.deps,e,"telemetry:status:response",{enabled:t,eventCount:r});this.deps.broker.postToWebview(n)}async handleTelemetryToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ow,e,"settings:error",this.deps);if(!t)return;let{enabled:r}=t;if(!this.deps.services?.setSandforgeSetting){let n=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,error:"Settings backend not available \u2014 telemetry preference was not persisted."});this.deps.broker.postToWebview(n);return}try{await this.deps.services.setSandforgeSetting("telemetry",r);let n=this.deps.services.getSandforgeSetting?.("telemetry",r)??r,o=A(this.deps,e,"telemetry:toggle:response",{success:!0,enabled:n});this.deps.broker.postToWebview(o)}catch(n){this.deps.log(`[ERR] telemetry:toggle: ${I(n)}`);let o=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var Bp={DailyApiRequests:{weight:.2,category:"limits"},DataStorageMB:{weight:.2,category:"storage"},DailyBulkApiBatches:{weight:.15,category:"limits"},DailyBulkV2QueryJobs:{weight:.15,category:"limits"},DailyAsyncApexExecutions:{weight:.15,category:"jobs"}},qp=1,Hk=.15,XC=.55;function Bk(s){let e=Math.max(0,Math.min(100,s)),t;return e<=50?t=100-e*.6:t=70-(e-50)*1.4,Math.max(0,Math.min(100,Math.round(t)))}function YC(s){let e=Math.max(0,Math.min(100,s)),t;return e<=75?t=e/75*70:t=70+(e-75)/25*30,Math.max(0,Math.min(100,Math.round(t)))}function Wp(s,e,t){if(s<=e)return 100;if(s>=t)return 20;let r=(s-e)/(t-e);return Math.round(100-r*80)}function qk(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function Wk(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function ai(s){return s>=70?"healthy":s>=40?"warning":"critical"}function zk(s,e){if(e<75)return"No action needed.";let t=e>=90?"Urgent: ":"";switch(s){case"DailyApiRequests":return`${t}Review scheduled batch jobs and integrations consuming API calls.`;case"DataStorageMB":return`${t}Consider archiving old records or cleaning up attachments.`;case"DailyBulkApiBatches":return`${t}Group small Bulk API loads into fewer, larger jobs, or spread them over several days.`;case"DailyBulkV2QueryJobs":return`${t}Review the integrations that run Bulk API 2.0 queries, and how often they run.`;case"DailyAsyncApexExecutions":return`${t}Review queued and scheduled Apex jobs for efficiency.`;default:return`${t}Monitor this limit and optimize usage if it continues to grow.`}}function Gk(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var Dd=class{calculate(e){let t=[],r=this.countOptionalDimensions(e),n=this.computeLimitsWeightMultiplier(r);this.addCoreLimitFactors(e,t,n),this.addRemainingLimitFactors(e,t,n);let o=this.computeOptionalDimensionWeight(r);this.addMetadataDimension(e,t,o),this.addCoverageDimension(e,t,o),this.addSecurityDimension(e,t,o);let{weightedSum:i,totalWeight:a}=t.reduce((p,f)=>({weightedSum:p.weightedSum+f.score*f.weight,totalWeight:p.totalWeight+f.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),l=[...t].sort((p,f)=>p.score-f.score).filter(p=>p.status!=="healthy").slice(0,3),g=this.buildSummary(c,l);return{overallScore:d,overallStatus:c,factors:t,summary:g,topRisks:l}}countOptionalDimensions(e){let t=0;return(e.metadataCounts!==void 0||e.orgInfo!==void 0)&&t++,e.codeCoverage!==void 0&&t++,e.securitySettings!==void 0&&t++,t}computeLimitsWeightMultiplier(e){if(e===0)return qp;let t=e*Hk;return Math.max(XC,qp-t)}computeOptionalDimensionWeight(e){return e===0?0:Hk}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Bp)){let i=e.limits.find(g=>g.name===n);if(!i)continue;let a=Bk(i.usedPercent),d=this.fetchTrendData(e,n),c=d?qk(d.direction):"stable",u=d?Wk(d):0,l=Math.max(0,Math.round(a-u));t.push({name:i.name,category:o.category,score:l,weight:o.weight*r,status:ai(l),detail:Gk(i),recommendation:zk(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Bp)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Bp).reduce((c,u)=>c+u.weight,0),d=Math.max(0,(qp-i)*r)/o.length;for(let c of o){let u=Bk(c.usedPercent),l=this.fetchTrendData(e,c.name),g=l?qk(l.direction):"stable",p=l?Wk(l):0,f=Math.max(0,Math.round(u-p));t.push({name:c.name,category:"limits",score:f,weight:d,status:ai(f),detail:Gk(c),recommendation:zk(c.name,c.usedPercent),trend:g})}}addMetadataDimension(e,t,r){if(e.metadataCounts===void 0&&e.orgInfo===void 0)return;let n=e.metadataCounts?.customObjectCount??e.orgInfo?.customObjectCount??0,o=e.metadataCounts?.customFieldCount??0,i=e.metadataCounts?.apexClassCount??e.orgInfo?.apexClassCount??0,a=Math.round(Wp(n,50,500)*.4+Wp(o,200,2e3)*.3+Wp(i,100,1e3)*.3),d=`${n} custom objects, ${o} custom fields, ${i} Apex classes`,c=a<60?"High metadata complexity detected - consider consolidating custom objects and reviewing unused Apex classes":"Metadata complexity is manageable";t.push({name:"Metadata Complexity",category:"metadata",score:a,weight:r,status:ai(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=YC(e.codeCoverage),o=`${Math.round(e.codeCoverage)}% org-wide Apex code coverage`,i=e.codeCoverage<75?`Code coverage is at ${Math.round(e.codeCoverage)}% - Salesforce requires minimum 75% for deployment`:"Code coverage meets Salesforce requirements";t.push({name:"Code Coverage",category:"coverage",score:n,weight:r,status:ai(n),detail:o,recommendation:i,trend:"stable"})}addSecurityDimension(e,t,r){if(e.securitySettings===void 0)return;let{score:n,detail:o,recommendation:i}=this.scoreSecuritySettings(e.securitySettings);t.push({name:"Security Settings",category:"security",score:n,weight:r,status:ai(n),detail:o,recommendation:i,trend:"stable"})}scoreSecuritySettings(e){let t=0,r=[];e.passwordMinLength>=12?t+=25:e.passwordMinLength>=8?t+=15:(t+=5,r.push("password minimum length is below 8 characters")),e.passwordComplexity?t+=20:r.push("password complexity requirements are disabled"),e.sessionTimeout<=120?t+=20:e.sessionTimeout<=480?t+=10:r.push("session timeout exceeds 8 hours"),e.mfaEnabled?t+=20:r.push("MFA is not enabled"),e.ipRestrictions?t+=15:r.push("login IP restrictions are not configured");let n=r.length===0?"All security settings are properly configured":`${r.length} security issue(s) found`,o=r.length===0?"Security configuration is strong":`Improve security: ${r.join(", ")}`;return{score:t,detail:n,recommendation:o}}fetchTrendData(e,t){if(e.trends)return e.trends[t];if(e.trendStorage)return e.trendStorage.getTrendData(e.orgId,t)}scoreToOverallStatus(e){return e>=70?"healthy":e>=40?"warning":"critical"}buildSummary(e,t){return e==="healthy"&&t.length===0?"Your org is healthy. All limits are within safe thresholds.":e==="healthy"?`Your org is healthy but ${t[0].name} is trending up.`:e==="warning"?`Warning: ${t.map(o=>o.name).join(", ")} approaching limits. Review recommendations.`:`Critical: ${t.map(n=>n.name).join(", ")} at dangerous levels. Immediate action required.`}};var QC=ve(V({version:j()}));function Jk(s){let e=QC.parse(s).map(({version:t})=>t).filter(t=>Number.isFinite(Number(t)));if(e.length===0)throw new Error("The org listed no API version under /services/data.");return e.reduce((t,r)=>Number(r)>Number(t)?r:t)}function ZC(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var Nd=class{cache=new Map;cacheTtlMs;constructor(e=300*1e3){this.cacheTtlMs=e}async fetch(e,t){let r=this.cache.get(e);if(r&&Date.now()-r.fetchedAt<this.cacheTtlMs)return r.data;let[n,o,i,a,d,c]=await Promise.all([t.latestApiVersion(),t.queryOrg(),t.queryCount("SELECT COUNT() FROM User WHERE IsActive = true"),t.queryCount("SELECT COUNT() FROM EntityDefinition WHERE DeploymentStatus != null AND QualifiedApiName LIKE '%__c'"),t.queryCount("SELECT COUNT() FROM ApexClass"),t.queryCount("SELECT COUNT() FROM FlowDefinitionView WHERE IsActive = true")]),u=o.namespacePrefix||void 0,l=ZC(o.createdDate),g={name:o.name,orgId:o.orgId,type:o.type,edition:o.edition,instanceName:o.instanceName,apiVersion:n,userCount:i,customObjectCount:a,apexClassCount:d,flowCount:c,...u!==void 0?{namespacePrefix:u}:{},...l!==void 0?{createdDate:l}:{}};return this.cache.set(e,{data:g,fetchedAt:Date.now()}),g}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function Vk(s){return Object.entries(s).map(([e,{Max:t,Remaining:r}])=>({name:e,max:t,remaining:r,usedPercent:t>0?Math.round((t-r)/t*100):0}))}var zp=1440*60*1e3,Kk=7*zp,e$=500*1024,t$=900*1e3,r$=2,n$="trends",o$=new Set(Ui),s$=zp,Md=class{configStore;lastSaveTimestamps=new Map;constructor(e){this.configStore=e}trendKey(e){return`trend:${e}`}record(e,t){let r=Date.now();this.isRateLimited(e,r)||this.append(e,this.read(e),t,r)}recordAndGetTrends(e,t,r){let n=Date.now(),o=this.read(e),a=(this.isRateLimited(e,n)?o:this.append(e,o,t,n)).filter(u=>u.timestamp>=jd(n-Kk)),d=a.filter(u=>u.timestamp>=jd(n-s$)),c={};for(let u of r)c[u]=this.computeTrend(u,a,d);return c}getHistory(e,t=zp){let r=jd(Date.now()-t);return this.read(e).filter(n=>n.timestamp>=r)}getTrendData(e,t){let r=this.getHistory(e);return this.computeTrend(t,r,r)}purge(e){let t=this.trendKey(e);this.configStore.delete(t),this.lastSaveTimestamps.delete(e)}read(e){return this.configStore.get(this.trendKey(e))??[]}isRateLimited(e,t){return t-(this.lastSaveTimestamps.get(e)??0)<t$}append(e,t,r,n){let o=jd(n-Kk),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>o$.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,n$),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=Xk(e,t),{values:i}=Xk(e,r);if(i.length<2)return{limitName:e,direction:"stable",changePercent:0,sparklineData:n,timestamps:o};let a=i[0],d=i[i.length-1],c=d-a,u;Math.abs(c)<=r$?u="stable":c>0?u="up":u="down";let l;if(u==="up"&&d<100){let g=this.getTimeSpanMs(r);if(g>0){let p=c/g;if(p>0){let h=(100-d)/p;l=Math.round(h/(3600*1e3)*10)/10}}}return{limitName:e,direction:u,changePercent:Math.round(c*10)/10,predictedTimeToLimit:l,sparklineData:n,timestamps:o}}getTimeSpanMs(e){if(e.length<2)return 0;let t=new Date(e[0].timestamp).getTime();return new Date(e[e.length-1].timestamp).getTime()-t}trimToSizeLimit(e){let t=[...e];for(;t.length>0&&!(new TextEncoder().encode(JSON.stringify(t)).length<=e$);)t.shift();return t}};function jd(s){return new Date(s).toISOString()}function Xk(s,e){let t=[],r=[];for(let n of e){let o=n.limits.find(i=>i.name===s);o&&(t.push(o.usedPercent),r.push(n.timestamp))}return{values:t,timestamps:r}}var Ld=class{onNotify;definitions=new Map;activeAlerts=new Map;lastTriggered=new Map;constructor(e){this.onNotify=e}addDefinition(e){this.definitions.set(e.id,e)}removeDefinition(e){this.definitions.delete(e)}getDefinitions(){return[...this.definitions.values()]}evaluate(e,t,r){for(let n of this.definitions.values()){if(!n.enabled||n.metric!==e||!i$(n.condition,t))continue;let o=`${n.id}:${r}`;if(this.isInCooldown(n,o))continue;let i=this.createAlert(n,t,r);return this.activeAlerts.set(i.id,i),this.lastTriggered.set(o,Date.now()),this.onNotify(i),i}return null}getActiveAlerts(){return[...this.activeAlerts.values()].filter(e=>e.status==="active"||e.status==="acknowledged")}acknowledgeAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="acknowledged",t.acknowledgedAt=new Date().toISOString())}resolveAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="resolved",t.resolvedAt=new Date().toISOString())}restoreAlerts(e){for(let t of e)if(t.status==="active"||t.status==="acknowledged"){this.activeAlerts.set(t.id,t);let r=`${t.definitionId}:${t.orgId}`,n=Date.parse(t.triggeredAt);!Number.isNaN(n)&&n>(this.lastTriggered.get(r)??0)&&this.lastTriggered.set(r,n)}}dismissAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="dismissed")}isInCooldown(e,t){let r=this.lastTriggered.get(t);if(r===void 0)return!1;let n=e.cooldownMinutes*60*1e3;return Date.now()-r<n}createAlert(e,t,r){return{id:`alert-${globalThis.crypto.randomUUID()}`,definitionId:e.id,severity:e.severity,status:"active",message:`${e.name}: ${e.metric} is ${t} (threshold: ${e.condition.threshold})`,currentValue:t,threshold:e.condition.threshold,orgId:r,triggeredAt:new Date().toISOString()}}};function i$(s,e){switch(s.operator){case"gt":return e>s.threshold;case"gte":return e>=s.threshold;case"lt":return e<s.threshold;case"lte":return e<=s.threshold;case"eq":return e===s.threshold;case"neq":return e!==s.threshold}}var es="alert:state:",Gp="alerts";var Fd=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${es}active`,e,Gp)}loadAlerts(){let e=this.configStore.get(`${es}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${es}definitions`,e,Gp)}loadDefinitions(){let e=this.configStore.get(`${es}definitions`);return Array.isArray(e)?e:[]}saveHistory(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.id)),n=e.filter(a=>!r.has(a.id));if(n.length===0)return;let o=[...t,...n],i=o.length>500?o.slice(o.length-500):o;this.configStore.set(`${es}history`,i,Gp)}loadHistory(){let e=this.configStore.get(`${es}history`);return Array.isArray(e)?e:[]}};var Jp=[{id:"alert-api-critical",name:"API Requests Critical",description:"Fires when daily API request usage reaches 90% of the org limit",enabled:!0,metric:"DailyApiRequests",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-storage-critical",name:"Data Storage Critical",description:"Fires when data storage usage reaches 85% of the org limit",enabled:!0,metric:"DataStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-async-critical",name:"Async Apex Critical",description:"Fires when daily async Apex execution usage reaches 90% of the org limit",enabled:!0,metric:"DailyAsyncApexExecutions",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-email-warning",name:"Workflow Emails Warning",description:"Fires when daily workflow email usage reaches 80% of the org limit",enabled:!0,metric:"DailyWorkflowEmails",condition:{operator:"gte",threshold:80},severity:"warning",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-filestorage-critical",name:"File Storage Critical",description:"Fires when file storage usage reaches 85% of the org limit",enabled:!0,metric:"FileStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]}];var _d=class{queryErrors;errorCache=new Map;truncatedCache=new Map;constructor(e){this.queryErrors=e}async fetch(e){let t=new Date(Date.now()-864e5).toISOString(),{records:r,truncated:n}=await this.queryErrors(e,t);return this.errorCache.set(e,r),this.truncatedCache.set(e,n),r}getRecentErrors(e){return this.errorCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getErrorsByType(e){let t=this.getRecentErrors(e),r=new Map;for(let n of t){let o=r.get(n.errorType)??0;r.set(n.errorType,o+1)}return r}};var Ud=class{querySessions;sessionCache=new Map;truncatedCache=new Map;constructor(e){this.querySessions=e}async fetch(e){let{records:t,truncated:r}=await this.querySessions(e);return this.sessionCache.set(e,t),this.truncatedCache.set(e,r),t}getActiveSessions(e){return this.sessionCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getActiveUserCount(e){let t=this.getActiveSessions(e);return new Set(t.map(n=>n.userId)).size}};var Hd=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=a$(e),r=d$(e),n=c$(e),o=e.durationMs,i=u$(t,r,n,o);return{logId:e.id,totalDuration:e.durationMs,soqlQueries:t,dmlStatements:r,heapUsed:n,cpuTime:o,issues:i}}async fetchAndAnalyze(e,t=10){let{records:r,truncated:n}=await this.fetchLogs(e,t),o=r.map(i=>this.analyze(i));return this.analyses.set(e,o),this.truncatedCache.set(e,n),o}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentAnalyses(e){return this.analyses.get(e)??[]}getTopIssues(e){let t=this.analyses.get(e)??[],r=new Map;for(let n of t)for(let o of n.issues){let i=`${o.type}:${o.message}`,a=r.get(i);a?a.count++:r.set(i,{issue:o,count:1})}return[...r.values()].sort((n,o)=>o.count-n.count).map(n=>n.issue)}};function a$(s){return Math.min(Math.floor(s.logSize/500),100)}function d$(s){return Math.min(Math.floor(s.logSize/1e3),150)}function c$(s){return Math.min(s.logSize*10,6e6)}function u$(s,e,t,r){let n=[];return s>=100?n.push({type:"soql_in_loop",severity:"critical",message:`SOQL query limit reached: ${s}/100`}):s>=100*.8&&n.push({type:"governor_warning",severity:"warning",message:`Approaching SOQL query limit: ${s}/100`}),e>=150?n.push({type:"excessive_dml",severity:"critical",message:`DML statement limit reached: ${e}/150`}):e>=150*.6&&n.push({type:"governor_warning",severity:"warning",message:`Approaching DML statement limit: ${e}/150`}),t>=6e6?n.push({type:"large_heap",severity:"critical",message:`Heap size limit reached: ${t}/6000000`}):t>=6e6*.7&&n.push({type:"large_heap",severity:"warning",message:`Approaching heap size limit: ${t}/6000000`}),r>5e3&&n.push({type:"slow_query",severity:"warning",message:`Slow execution: ${r}ms exceeds 5000ms threshold`}),n}var l$=new Set(Nf);function Qk(s){return typeof s=="string"&&l$.has(s)?s:"Unknown"}function p$(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function Yk(s){return`${s.sandboxName}:${s.refreshDate}`}var Bd=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=p$()){this.querySandboxes=e,this.onRefreshDetected=t,this.seen=r}async fetch(e){let{supported:t,events:r,truncated:n}=await this.querySandboxes(e);if(this.refreshCache.set(e,r),this.supportedCache.set(e,t),this.truncatedCache.set(e,n),!t)return r;let o=r.filter(d=>d.status==="Completed"),i=this.seen.load(e);if(i!==void 0){let d=new Set(i);for(let c of o)d.has(Yk(c))||this.onRefreshDetected?.(c)}let a=o.map(Yk);return(i===void 0||a.some(d=>!i.includes(d)))&&this.seen.save(e,a),r}isSupported(e){return this.supportedCache.get(e)??!0}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentRefreshes(e){return this.refreshCache.get(e)??[]}isRefreshInProgress(e){return(this.refreshCache.get(e)??[]).some(r=>jf(r.status))}};var qd=class s{providers;constructor(e){this.providers=e}async computeHealth(e){let t=await Promise.all(this.providers.map(c=>c(e))),r=s.computeScore(t),n=r===null?"unknown":s.statusFromScore(r),o=t.find(c=>c.name==="apiLimits"),i=t.find(c=>c.name==="storage"),a=t.find(c=>c.name==="activeJobs"),d=t.find(c=>c.name==="recentErrors");return{orgId:e,overall:n,apiLimitsStatus:o?.status??"unknown",storageStatus:i?.status??"unknown",failedJobs:a?.status==="unknown"?null:a?.count??null,failedJobsOutOf:a?.status==="unknown"?null:a?.outOf??null,recentErrorLogs:d?.status==="unknown"?null:d?.count??null,lastChecked:new Date().toISOString()}}static computeScore(e){let t=e.filter(n=>n.status!=="unknown");if(t.length===0)return null;let r=t.reduce((n,o)=>n+o.score,0);return Math.round(r/t.length)}static statusFromScore(e){return e>=80?"healthy":e>=50?"degraded":"critical"}};var Zk=new Set(["Queued","Processing"]),Wd=class{queryJobs;jobCache=new Map;constructor(e){this.queryJobs=e}async fetch(e){let t=await this.queryJobs(e);return this.jobCache.set(e,t),t}getActiveJobs(e){return(this.jobCache.get(e)??[]).filter(r=>Zk.has(r.status))}getFailedJobs(e){return(this.jobCache.get(e)??[]).filter(r=>r.status==="Failed")}getJobStats(e){let t=this.jobCache.get(e)??[];return{total:t.length,active:t.filter(r=>Zk.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var g$=3e4,f$=1440*60*1e3,eO=100,tO=50,rO=20,nO="sandbox-process-seen:";function h$(s){return{load:e=>{let t=s.get(`${nO}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${nO}${e}`,t,"sandbox-refresh")}}}function m$(s){return s instanceof Oo?s.code==="ORG_AUTH_EXPIRED":uh(s)||il(s)!==void 0}function di(s){let e=il(s);return e!==void 0&&!(s instanceof Oo)?`the org could not be reached (${e})`:I(s)}function oO(s){let e=new Md(s.configStore),t=async(v,b,C)=>{try{return await C(await s.getConnection(v))}catch(k){if(!m$(k))throw k;s.log(`[WARN] monitor:${b} ${v}: ${di(k)}; read again on a new connection`);try{return await C(await s.getConnection(v,{again:!0}))}catch(T){throw T instanceof Oo&&T.code==="ORG_TEMPORARILY_UNREACHABLE"?k:T}}},r=new Fd(s.configStore),n=new Ld(v=>{s.log(`[ALERT] ${v.severity}: ${v.message}`);let b=v.severity==="critical"?"error":"warning";s.notify(b,v.message),r.saveAlerts(n.getActiveAlerts())}),o=r.loadDefinitions(),i=o.length>0?o:Jp;for(let v of i)n.addDefinition(v);o.length===0&&r.saveDefinitions(Jp);let a=r.loadAlerts();n.restoreAlerts(a);let d=new _d(async(v,b)=>{let C=await s.getConnection(v),{records:k,truncated:T}=await Cs(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${b} ORDER BY StartTime DESC LIMIT ${tO}`,tO);return xe(C.limitInfo,"monitor:error-logs apexLog"),{records:k.map(x=>({id:x.Id,errorType:x.Status,message:`${x.Operation} - ${x.Status}`,timestamp:x.StartTime,user:x.LogUser?.Username??void 0,context:x.Operation})),truncated:T}}),c=async(v,b)=>{let C=await v.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${b}`);return xe(v.limitInfo,"monitor:refresh apexLogCount"),C.totalSize},u=new Ud(async v=>{let b=await s.getConnection(v),{records:C,truncated:k}=await Cs(b,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${eO}`,eO);return xe(b.limitInfo,"monitor:sessions authSession"),{records:C.map(T=>({sessionId:T.Id,userId:T.UsersId,username:T.Users?.Username??T.UsersId,sessionType:T.SessionType??T.LoginType??"Unknown",loginTime:T.CreatedDate,sourceIp:T.SourceIp??""})),truncated:k}}),l=new Hd(async(v,b)=>{let C=await s.getConnection(v),{records:k,truncated:T}=await Cs(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${b}`,b);return xe(C.limitInfo,"monitor:apex-insights apexLog"),{records:k.map(x=>({id:x.Id,operation:x.Operation??"Unknown",status:x.Status,durationMs:x.DurationMilliseconds??0,logSize:x.LogLength??0,startTime:x.StartTime,user:x.LogUser?.Username??"Unknown"})),truncated:T}}),g=new Set,p=new Bd(async v=>{if(g.has(v))return{supported:!1,events:[],truncated:!1};let b=await s.getConnection(v),C;try{C=await Cs(b,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${rO}`,rO)}catch(k){let T=k instanceof Error?k.message:String(k);if(T.includes("SandboxProcess")&&T.includes("not supported"))return g.add(v),{supported:!1,events:[],truncated:!1};throw k}return xe(b.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:C.records.map(k=>({orgId:v,sandboxName:k.SandboxName??"Unknown",refreshDate:k.CreatedDate,status:Qk(k.Status),sourceOrg:k.Description??void 0})),truncated:C.truncated}},v=>s.onSandboxRefreshCompleted?.(v),h$(s.configStore)),f=new Map,h=async(v,b)=>{let C=f.get(v);if(C&&Date.now()-C.fetchedAt<g$)return C.data;let k=await b.request(`/services/data/${Ro}/limits`);return f.set(v,{data:k,fetchedAt:Date.now()}),k},m=async v=>{try{let C=(await t(v,"apiLimits",x=>h(v,x))).DailyApiRequests;if(!C||!C.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let k=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"apiLimits",status:k>80?"critical":k>60?"warning":"ok",score:100-k,message:`API usage at ${k}%`,percent:k}}catch(b){return{name:"apiLimits",status:"unknown",score:0,message:`Unable to fetch limits: ${di(b)}`}}},y=async v=>{try{let C=(await t(v,"storage",x=>h(v,x))).DataStorageMB;if(!C||!C.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let k=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"storage",status:k>85?"critical":k>70?"warning":"ok",score:100-k,message:`Storage usage at ${k}%`,percent:k}}catch(b){return{name:"storage",status:"unknown",score:0,message:`Unable to fetch storage: ${di(b)}`}}},R=async v=>{let b;try{let T=new Date(Date.now()-f$).toISOString();b=await t(v,"recentErrors",x=>c(x,T))}catch(T){return{name:"recentErrors",status:"unknown",score:0,message:`Unable to fetch error logs: ${di(T)}`}}let C=Math.max(0,100-b*5);return{name:"recentErrors",status:b>10?"critical":b>3?"warning":"ok",score:C,count:b,message:`${b} recent errors`}},S=async v=>{let b=await Lt(v,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${yn.monitorJobs}`);return xe(v.limitInfo,"monitor:refresh asyncJobs"),b.map(C=>({id:C.Id,jobType:C.JobType??"Batch",status:C.Status,createdBy:C.CreatedById,createdDate:C.CreatedDate,failedRecords:C.NumberOfErrors}))},w=new Wd(v=>t(v,"activeJobs",S)),O=async v=>{try{await w.fetch(v);let b=w.getJobStats(v),C=Math.max(0,100-b.failed*10);return{name:"activeJobs",status:b.failed>5?"critical":b.failed>0?"warning":"ok",score:C,count:b.failed,outOf:b.total,message:`${b.active} active, ${b.failed} failed of ${b.total} recent jobs`}}catch(b){return{name:"activeJobs",status:"unknown",score:0,message:`Unable to fetch jobs: ${di(b)}`}}},P=new qd([m,y,R,O]);return{trendStorage:e,alertStateStore:r,alertEngine:n,errorLogMonitor:d,userSessionMonitor:u,apexLogAnalyzer:l,sandboxRefreshTracker:p,healthCheck:P,healthSignals:{apiLimits:m,storage:y,recentErrors:R,activeJobs:O},getOrFetchLimits:h,forgetOrg:v=>{f.delete(v)}}}var sO=25e3,iO=20,y$=20,w$=20,b$=500,cO=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${yn.monitorJobs}`,R$=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${yn.monitorJobs}`,v$=new Set([cO,R$]),S$=new Set(["Queued","Preparing","Processing"]),k$=new Set(["BatchApex","Queueable","Future"]),ci=3600*1e3,aO=ci,dO=3;function Vp(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function O$(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function I$(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&O$(o,n)){r.set(n.id,o);continue}r.set(n.id,{status:n.status,batchesProcessed:n.batchesProcessed,totalBatches:n.totalBatches,unchangedSinceMs:t,movedWhileWatched:o!==void 0})}return r}function A$(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!S$.has(a.status)||!k$.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,u=a.batchesProcessed,l=a.totalBatches;if(a.status==="Processing"&&u!==null&&l!==null&&u<l&&c!==null&&c>=ci){n.push({job:a,stillMs:c,done:u,total:l});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<ci)continue;let g=t-Date.parse(a.createdDate);g>=aO&&o.push({job:a,ageMs:g,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:u}of n){let l=Vp(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${l}`,detail:`${c} of ${u} batches processed, unchanged across ${l} of observation by this dashboard while ${a.status} (stall bound ${ci/6e4}m).`,affectedJobs:[a.id],recommendation:"Check the job in Setup > Apex Jobs first. If it is still at the same batch, abort it and re-run it once the cause is known."})}let i=new Map;for(let a of s){if(a.status==="Aborted"||a.status!=="Failed"&&a.failedRecords<=0)continue;let d=i.get(a.jobType)??[];d.push(a),i.set(a.jobType,d)}for(let[a,d]of i){if(d.length<dO)continue;let c=d.reduce((u,l)=>u+(l.failedRecords||0),0);r.push({type:"frequent_failures",severity:"critical",title:`${d.length} ${a} jobs failed`,detail:`${d.length} of the last ${s.length} jobs are ${a} failures (${c} failed batch execution(s) reported) \u2014 at or above the ${dO}-failure pattern threshold.`,affectedJobs:d.map(u=>u.id),recommendation:`Open the most recent ${a} failure and read its extended status: a repeat at this rate is a defect or a data problem, not contention.`})}if(o.length>0){o.sort((g,p)=>p.ageMs-g.ageMs);let a=o[0],d=Vp(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:u}=a.job,l=c===null||u===null||u<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${u} batches processed, first seen at these values on this refresh`:`${c} of ${u} batches processed, unchanged over the ${Vp(Math.floor(a.stillMs/6e4))} watched so far`;r.push({type:"long_running",severity:"warning",title:o.length===1?`1 job unfinished ${d} after submission`:`${o.length} jobs unfinished ${aO/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${l}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:g})=>g.id),recommendation:`Keep this dashboard refreshing to measure progress, or check the job in Setup > Apex Jobs. A batch is called stuck only once its batch counter stays unchanged for ${ci/6e4}m of watching; a job without batch counters never is.`})}return r}var T$=new Set(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"]),zd=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new Mr;let r=oO({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Ie(e,n,"Alert",o),getConnection:async(n,o)=>(o?.again===!0&&Io().remove(n),this.withSharedJobQuery(n,await q(n,e.orgRegistry,e.orgManager))),onSandboxRefreshCompleted:n=>{e.sandboxRefreshes?.noteCompletedRefresh(n)}});this.trendStorage=r.trendStorage,this.forgetServicesOrg=r.forgetOrg,this.alertStateStore=r.alertStateStore,this.alertEngine=r.alertEngine,this.errorLogMonitor=r.errorLogMonitor,this.userSessionMonitor=r.userSessionMonitor,this.apexLogAnalyzer=r.apexLogAnalyzer,this.sandboxRefreshTracker=r.sandboxRefreshTracker,this.healthCheck=r.healthCheck,this.healthSignals=r.healthSignals,this.getOrFetchLimits=r.getOrFetchLimits}deps;trendStorage;orgInfoFetcher=new Nd;healthCalculator=new Dd;liveOperationTracker;getOrFetchLimits;forgetServicesOrg;errorLogMonitor;userSessionMonitor;apexLogAnalyzer;sandboxRefreshTracker;healthCheck;healthSignals;alertEngine;alertStateStore;inFlightJobRecords=new Map;jobProgress=new Map;externalBrowser;setLiveOperationTracker(e){this.liveOperationTracker=e,e.onChange(this.onLiveOperationsChange)}onLiveOperationsChange=()=>this.pushLiveOperationsSoon();livePush;dispose(){this.livePush!==void 0&&(clearTimeout(this.livePush),this.livePush=void 0),this.liveOperationTracker?.offChange(this.onLiveOperationsChange)}pushLiveOperationsSoon(){this.livePush===void 0&&(this.livePush=setTimeout(()=>{this.livePush=void 0;let e={id:this.deps.nextId(),type:"monitor:live-operations:changed",timestamp:Date.now(),payload:{operations:(this.liveOperationTracker?.getAll()??[]).map(t=>({...t}))}};this.deps.broker.postToWebview(e)},b$),this.livePush.unref?.())}async readOrgHealth(e,t){let r=[];for(let n of t)r.push(await this.healthSignals[n](e));return r}getAlertEngine(){return this.alertEngine}forgetOrg(e){this.forgetServicesOrg(e),this.orgInfoFetcher.clearCache(e),this.jobProgress.delete(e),this.trendStorage.purge(e)}async handle(e){if(!T$.has(e.type))return!1;switch(e.type){case"monitor:refresh":return await this.handleRefresh(e),!0;case"monitor:open-apex-jobs":return await this.handleOpenApexJobs(e),!0;case"monitor:live-operations":return this.handleLiveOperations(e),!0;case"monitor:storage":return await this.handleStorage(e),!0;case"monitor:deployments":return await this.handleDeployments(e),!0;case"monitor:api-usage":return await this.handleApiUsage(e),!0;case"monitor:error-logs":return await this.handleErrorLogs(e),!0;case"monitor:sessions":return await this.handleSessions(e),!0;case"monitor:apex-insights":return await this.handleApexInsights(e),!0;case"monitor:sandbox-refresh":return await this.handleSandboxRefresh(e),!0;case"monitor:alerts":return this.handleAlerts(e),!0;case"monitor:alert:acknowledge":return this.handleAlertAcknowledge(e),!0;case"monitor:alert:dismiss":return this.handleAlertDismiss(e),!0;default:return!1}}withSharedJobQuery(e,t){return new Proxy(t,{get:(r,n)=>{if(n==="query")return i=>{let a=this.inFlightJobRecords.get(e);return a!==void 0&&v$.has(i)?Promise.resolve({done:!0,totalSize:a.length,records:a}):r.query(i)};let o=Reflect.get(r,n,r);return typeof o=="function"?o.bind(r):o}})}pastDeadline(e,t){return e.aborted?(this.deps.log(`[WARN] monitor:refresh outlived its ${sO}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new ge(sO).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){E(this.deps,"monitor:refresh","monitor:error",e,n)}}async executeRefresh(e,t,r){try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),[o,i]=await Promise.allSettled([this.getOrFetchLimits(t.orgId,n),Lt(n,cO)]);if(o.status==="rejected")throw o.reason;let a=Vk(o.value);xe(n.limitInfo,"monitor:refresh limits");let d=[];for(let v of a){let b=this.alertEngine.evaluate(v.name,v.usedPercent,t.orgId);b&&d.push(b)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if(xe(n.limitInfo,"monitor:refresh asyncJobs"),this.inFlightJobRecords.set(t.orgId,c),this.pastDeadline(r,"org info and health check"))return;let u=Date.now(),l=c.map(v=>({id:v.Id,jobType:v.JobType??"Unknown",status:v.Status,createdBy:v.CreatedById,createdDate:v.CreatedDate,failedRecords:v.NumberOfErrors,batchesProcessed:v.JobItemsProcessed??null,totalBatches:v.TotalJobItems??null})),g=c.length>=yn.monitorJobs,p=l.map(({id:v,jobType:b,status:C,createdBy:k,createdDate:T,failedRecords:x})=>({id:v,jobType:b,status:C,createdBy:k,createdDate:T,failedRecords:x})),f=I$(this.jobProgress.get(t.orgId),l,u);this.jobProgress.set(t.orgId,f);let h=A$(l,f,u),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,Ui),[R,S]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);R&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:R.orgId,instanceName:R.instanceName||void 0},"monitor");let w=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:R}),O=w.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let P=A(this.deps,e,"monitor:data",{limits:a,jobs:p,jobsTruncated:g,healthScore:O,healthReport:w,trends:y,jobInsights:h,orgInfo:R,orgHealthStatus:S,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${I(n)}"`))return;E(this.deps,"monitor:refresh","monitor:error",e,n)}finally{this.inFlightJobRecords.delete(t.orgId)}}async computeOrgHealth(e){try{return await this.healthCheck.computeHealth(e)}catch(t){this.deps.log(`[WARN] HealthCheck failed: ${String(t)}`);return}}async fetchOrgInfo(e,t){try{let r={latestApiVersion:async()=>Jk(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await Lt(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");xe(t.limitInfo,"monitor:refresh orgInfo");let i=o[0];return{name:i?.Name??n?.alias??"",orgId:i?.Id??e,type:n?.orgType??"Production",edition:i?.OrganizationType??n?.metadata.edition??"",instanceName:i?.InstanceName??"",namespacePrefix:i?.NamespacePrefix,createdDate:i?.CreatedDate}},queryCount:async n=>(await t.query(n)).totalSize};return await this.orgInfoFetcher.fetch(e,r)}catch(r){this.deps.log(`[WARN] OrgInfo fetch failed: ${String(r)}`);return}}handleLiveOperations(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.liveOperationTracker?.getAll()??[],r=A(this.deps,e,"monitor:live-operations:response",{operations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleStorage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await n.request(`/services/data/${Ro}/limits/recordCount`);xe(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(p=>p.count>0).sort((p,f)=>f.count-p.count),a=i.slice(0,w$),d=a.map(p=>p.name).filter(p=>/^[A-Za-z][A-Za-z0-9_]*$/.test(p)),c=new Map;if(d.length>0){let p=await Lt(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(f=>`'${f}'`).join(", ")})`);xe(n.limitInfo,"monitor:storage entityDefinition");for(let f of p)f.Label&&c.set(f.QualifiedApiName,f.Label)}let u=a.map(p=>({objectName:p.name,label:c.get(p.name)??p.name,recordCount:p.count})),l=i.reduce((p,f)=>p+f.count,0),g=A(this.deps,e,"monitor:storage:response",{success:!0,objects:u,totalRecords:l,objectCount:i.length});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){E(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=(await n.tooling.query(`SELECT Id, Status, StartDate, CompletedDate, CreatedBy.Name, NumberComponentsTotal, NumberComponentErrors FROM DeployRequest ORDER BY StartDate DESC LIMIT ${iO}`)).records;xe(n.limitInfo,"monitor:deployments deployRequest");let a=i.map(c=>({id:c.Id,status:c.Status,startDate:c.StartDate,completedDate:c.CompletedDate??void 0,createdBy:c.CreatedBy?.Name??"Unknown",componentCount:c.NumberComponentsTotal??0,errorCount:c.NumberComponentErrors??0})),d=A(this.deps,e,"monitor:deployments:response",{success:!0,deployments:a,truncated:i.length>=iO});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.getOrFetchLimits(r.orgId,n);xe(n.limitInfo,"monitor:api-usage limits");let i=["DailyApiRequests","DailyBulkApiBatches","DailyBulkV2QueryJobs","DailyBulkV2QueryFileStorageMB","DailyStreamingApiEvents","DailyGenericStreamingApiEvents","DailyDurableStreamingApiEvents","DailyAsyncApexExecutions","HourlyAsyncReportRuns","HourlyTimeBasedWorkflow","DailyWorkflowEmails","MassEmail","SingleEmail","HourlyPublishedPlatformEvents","DailyStandardVolumePlatformEvents"],a=[];for(let c of i){let u=o[c];if(u&&typeof u.Max=="number"){let l=u.Max-u.Remaining,g=u.Max>0?Math.round(l/u.Max*100):0;a.push({category:c,used:l,max:u.Max,usedPercent:g})}}a.sort((c,u)=>u.usedPercent-c.usedPercent);let d=A(this.deps,e,"monitor:api-usage:response",{success:!0,categories:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ey,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND"});return}let n=SS(r.instanceUrl);if(!n.ok){let o=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";E(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${ye(r)}": ${o}.`),{code:"INVALID_INSTANCE_URL"});return}try{let o=await this.externalBrowser.open(n.url),i=A(this.deps,e,"monitor:open-apex-jobs:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}catch(o){E(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.errorLogMonitor.fetch(r.orgId),i=[...this.errorLogMonitor.getErrorsByType(r.orgId).entries()].map(([d,c])=>({type:d,count:c})),a=A(this.deps,e,"monitor:error-logs:response",{success:!0,errors:n,errorsByType:i,totalCount:n.length,truncated:this.errorLogMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){E(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.userSessionMonitor.fetch(r.orgId),o=this.userSessionMonitor.getActiveUserCount(r.orgId),i=A(this.deps,e,"monitor:sessions:response",{success:!0,sessions:n,activeUserCount:o,truncated:this.userSessionMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,y$),o=this.apexLogAnalyzer.getTopIssues(r.orgId),i=A(this.deps,e,"monitor:apex-insights:response",{success:!0,analyses:n,topIssues:o,truncated:this.apexLogAnalyzer.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:apex-insights","monitor:error",e,n)}}async checkSandboxIdentity(e){let t=this.deps.sandboxRefreshes;if(!(!t||this.deps.orgManager.getOrg(e)?.orgType!=="Sandbox"))try{let r=await q(e,this.deps.orgRegistry,this.deps.orgManager),[n]=await Lt(r,"SELECT Id, InstanceName FROM Organization");xe(r.limitInfo,"monitor:sandbox-refresh organization"),n&&t.observe(e,{organizationId:n.Id,instanceName:n.InstanceName??void 0},"monitor")}catch(r){this.deps.log(`[WARN] monitor:sandbox-refresh identity check: ${I(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await this.checkSandboxIdentity(r.orgId);let n=await this.sandboxRefreshTracker.fetch(r.orgId),o=this.sandboxRefreshTracker.isRefreshInProgress(r.orgId),i=A(this.deps,e,"monitor:sandbox-refresh:response",{success:!0,supported:this.sandboxRefreshTracker.isSupported(r.orgId),refreshes:n,inProgress:o,truncated:this.sandboxRefreshTracker.isTruncated(r.orgId),detected:this.deps.sandboxRefreshes?.refreshesOf(r.orgId)??[]});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:sandbox-refresh","monitor:error",e,n)}}handleAlerts(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.alertEngine.getActiveAlerts(),r=this.alertStateStore.loadHistory(),n=A(this.deps,e,"monitor:alerts:result",{alerts:t,history:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertAcknowledge(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Rl,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.acknowledgeAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:acknowledge:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertDismiss(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Rl,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.dismissAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:dismiss:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}};var Kp="seed:template:",uO="seedTemplates",un=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Kp}${e.id}`,e,uO)}load(e){return this.configStore.get(`${Kp}${e}`)}list(){let e=this.configStore.getByCategory(uO);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Kp}${e}`)}};var Gd=class{templates=new Map;generateId;now;store;constructor(e,t,r){this.generateId=e,this.now=t,this.store=r}create(e){let t=this.now(),r={...e,id:this.generateId(),createdAt:t,updatedAt:t};return this.templates.set(r.id,r),this.store?.save(r),r}get(e){let t=this.templates.get(e);if(t)return t;if(this.store){let r=this.store.load(e);return r&&this.templates.set(e,r),r}}list(){return Array.from(this.templates.values()).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}update(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n={...r,...t,id:r.id,createdAt:r.createdAt,updatedAt:this.now()};return this.templates.set(e,n),this.store?.save(n),n}delete(e){let t=this.templates.delete(e);return this.store&&this.store.delete(e)||t}duplicate(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n=this.now(),o={...r,id:this.generateId(),name:t,version:1,createdAt:n,updatedAt:n};return this.templates.set(o.id,o),this.store?.save(o),o}};var lO=[{id:"assureur-fr",name:"Assureur fran\xE7ais",description:"Compagnie d'assurance fran\xE7aise avec contrats, sinistres et assur\xE9s.",industry:"Insurance",locale:"fr-FR",dataPatterns:{Name:{fieldType:"string",generator:"faker",params:{method:"company.name",locale:"fr"},examples:["AXA Pr\xE9voyance","Mutuelle du Soleil","Groupe Assurancia"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["Jean","Marie","Philippe"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Dupont","Martin","Lefebvre"]},SIRET__c:{fieldType:"string",generator:"pattern",params:{pattern:"###########00##"},examples:["12345678900012","98765432100034","55566677800015"]},Contract_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Auto","Habitation","Sant\xE9","Vie","Responsabilit\xE9 Civile"]},examples:["Auto","Habitation","Sant\xE9"]},Premium__c:{fieldType:"currency",generator:"range",params:{min:200,max:5e3,currency:"EUR"},examples:["450.00","1200.50","3200.00"]}}},{id:"hospital-us",name:"H\xF4pital am\xE9ricain",description:"Hospital system with patients, procedures, and medical codes.",industry:"Healthcare",locale:"en-US",dataPatterns:{FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"en_US"},examples:["James","Sarah","Michael"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"en_US"},examples:["Johnson","Williams","Smith"]},MRN__c:{fieldType:"string",generator:"sequence",params:{prefix:"MRN-",padLength:8},examples:["MRN-00000001","MRN-00000002","MRN-00000003"]},ICD10_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["J06.9","I10","E11.9","M54.5","J18.9","K21.0","N39.0"]},examples:["J06.9","I10","E11.9"]},CPT_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["99213","99214","99215","99203","99204","36415","71046"]},examples:["99213","99214","36415"]},Insurance_Provider__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Blue Cross","Aetna","UnitedHealth","Cigna","Medicare","Medicaid"]},examples:["Blue Cross","Aetna","Medicare"]}}},{id:"ecommerce-b2c",name:"E-commerce B2C",description:"Online retail with products, orders, customers, and reviews.",industry:"Retail",locale:"en-US",dataPatterns:{Product_Name__c:{fieldType:"string",generator:"faker",params:{method:"commerce.productName"},examples:["Ergonomic Steel Chair","Wireless Bluetooth Headphones","Organic Cotton T-Shirt"]},SKU__c:{fieldType:"string",generator:"sequence",params:{prefix:"SKU-",padLength:6},examples:["SKU-000001","SKU-000002","SKU-000003"]},Price__c:{fieldType:"currency",generator:"range",params:{min:9.99,max:999.99,currency:"USD"},examples:["29.99","149.50","499.00"]},Order_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Pending","Processing","Shipped","Delivered","Returned","Cancelled"]},examples:["Pending","Shipped","Delivered"]},Rating__c:{fieldType:"number",generator:"range",params:{min:1,max:5},examples:["4","5","3"]},Review_Text__c:{fieldType:"textarea",generator:"ai_generate",params:{prompt:"Product review, 1-3 sentences, realistic tone"},examples:["Great product, fast shipping!","Good quality but runs small.","Exactly as described."]}}},{id:"banque-eu",name:"Banque europ\xE9enne",description:"European bank with accounts, transactions, IBAN/BIC codes.",industry:"Banking",locale:"fr-FR",dataPatterns:{IBAN__c:{fieldType:"string",generator:"faker",params:{method:"finance.iban",locale:"fr"},examples:["FR7630006000011234567890189","DE89370400440532013000","ES9121000418450200051332"]},BIC__c:{fieldType:"string",generator:"faker",params:{method:"finance.bic"},examples:["BNPAFRPPXXX","DEUTDEFFXXX","BBVAESMMXXX"]},Transaction_Amount__c:{fieldType:"currency",generator:"range",params:{min:-1e4,max:5e4,currency:"EUR"},examples:["1250.00","-450.75","15000.00"]},Transaction_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Virement","Pr\xE9l\xE8vement","Carte","Ch\xE8que","Esp\xE8ces"]},examples:["Virement","Carte","Pr\xE9l\xE8vement"]},Account_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Courant","\xC9pargne","PEL","Titre","Professionnel"]},examples:["Courant","\xC9pargne","PEL"]},Risk_Score__c:{fieldType:"number",generator:"range",params:{min:0,max:100},examples:["15","42","78"]}}},{id:"startup-saas",name:"Startup SaaS",description:"SaaS company with subscriptions, MRR metrics, churn tracking.",industry:"Technology",locale:"en-US",dataPatterns:{Company_Name__c:{fieldType:"string",generator:"faker",params:{method:"company.name"},examples:["Acme Cloud","DataSync Pro","NeuralFlow AI"]},Plan__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Free:.4,Starter:.25,Pro:.2,Enterprise:.15}},examples:["Free","Pro","Enterprise"]},MRR__c:{fieldType:"currency",generator:"range",params:{min:0,max:25e3,currency:"USD"},examples:["0.00","499.00","12500.00"]},Churn_Risk__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Low","Medium","High","Critical"]},examples:["Low","Medium","High"]},Active_Users__c:{fieldType:"number",generator:"range",params:{min:1,max:500},examples:["12","85","250"]},NPS_Score__c:{fieldType:"number",generator:"range",params:{min:-100,max:100},examples:["72","-15","45"]}}},{id:"immobilier",name:"Immobilier",description:"Agence immobili\xE8re avec biens, mandats et visites.",industry:"Real Estate",locale:"fr-FR",dataPatterns:{Property_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Appartement","Maison","Studio","Loft","Terrain","Local commercial"]},examples:["Appartement","Maison","Studio"]},Surface__c:{fieldType:"number",generator:"range",params:{min:15,max:300,unit:"m\xB2"},examples:["45","120","85"]},Price__c:{fieldType:"currency",generator:"range",params:{min:5e4,max:2e6,currency:"EUR"},examples:["185000","450000","1200000"]},City__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris","Lyon","Marseille","Bordeaux","Toulouse","Nantes","Lille"]},examples:["Paris","Lyon","Bordeaux"]},Mandate_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Exclusif","Simple","Semi-exclusif"]},examples:["Exclusif","Simple","Semi-exclusif"]},DPE__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{A:.05,B:.1,C:.2,D:.3,E:.2,F:.1,G:.05}},examples:["C","D","B"]}}},{id:"education",name:"\xC9ducation",description:"Educational institution with students, courses, and grades.",industry:"Education",locale:"fr-FR",dataPatterns:{Student_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"STU-",padLength:6},examples:["STU-000001","STU-000002","STU-000003"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["L\xE9a","Hugo","Emma"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Bernard","Petit","Robert"]},Course_Name__c:{fieldType:"string",generator:"random_pick",params:{values:["Math\xE9matiques","Physique","Histoire","Anglais","Informatique","Philosophie"]},examples:["Math\xE9matiques","Physique","Informatique"]},Grade__c:{fieldType:"number",generator:"range",params:{min:0,max:20,precision:1},examples:["14.5","8.0","17.5"]},Semester__c:{fieldType:"picklist",generator:"random_pick",params:{values:["S1","S2","S3","S4","S5","S6"]},examples:["S1","S2","S3"]}}},{id:"logistique",name:"Logistique",description:"Logistics company with parcels, warehouses, and shipment tracking.",industry:"Logistics",locale:"fr-FR",dataPatterns:{Tracking_Number__c:{fieldType:"string",generator:"sequence",params:{prefix:"TRK-",padLength:10},examples:["TRK-0000000001","TRK-0000000002","TRK-0000000003"]},Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["En pr\xE9paration","Exp\xE9di\xE9","En transit","En livraison","Livr\xE9","Retourn\xE9"]},examples:["Exp\xE9di\xE9","En transit","Livr\xE9"]},Weight__c:{fieldType:"number",generator:"range",params:{min:.1,max:500,unit:"kg"},examples:["2.5","15.0","125.0"]},Warehouse__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris-Nord","Lyon-Est","Marseille-Port","Bordeaux-Sud","Lille-Centre"]},examples:["Paris-Nord","Lyon-Est","Marseille-Port"]},Carrier__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Colissimo","Chronopost","DHL","FedEx","UPS","GLS"]},examples:["Colissimo","Chronopost","DHL"]},Delivery_Date__c:{fieldType:"date",generator:"relative_date",params:{minDaysFromNow:1,maxDaysFromNow:14},examples:["2026-03-01","2026-03-05","2026-03-12"]}}},{id:"rh",name:"Ressources humaines",description:"HR department with employees, leaves, payroll, and performance.",industry:"Human Resources",locale:"fr-FR",dataPatterns:{Employee_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"EMP-",padLength:5},examples:["EMP-00001","EMP-00002","EMP-00003"]},Department__c:{fieldType:"picklist",generator:"random_pick",params:{values:["R&D","Marketing","Ventes","RH","Finance","Support","Direction"]},examples:["R&D","Marketing","Finance"]},Contract_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{CDI:.6,CDD:.2,Stage:.1,Alternance:.1}},examples:["CDI","CDD","Stage"]},Salary__c:{fieldType:"currency",generator:"range",params:{min:25e3,max:12e4,currency:"EUR"},examples:["35000","55000","85000"]},Leave_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Cong\xE9s pay\xE9s","RTT","Maladie","Sans solde","Maternit\xE9","Formation"]},examples:["Cong\xE9s pay\xE9s","RTT","Maladie"]},Leave_Days__c:{fieldType:"number",generator:"range",params:{min:.5,max:25},examples:["1","5","12"]}}},{id:"ong",name:"ONG/Association",description:"Non-profit organization with donors, campaigns, and volunteers.",industry:"Non-Profit",locale:"fr-FR",dataPatterns:{Donor_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Particulier:.7,Entreprise:.2,Fondation:.1}},examples:["Particulier","Entreprise","Fondation"]},Donation_Amount__c:{fieldType:"currency",generator:"range",params:{min:5,max:5e4,currency:"EUR"},examples:["25.00","150.00","5000.00"]},Campaign_Name__c:{fieldType:"string",generator:"ai_generate",params:{prompt:"Charity campaign name, inspiring and concise"},examples:["Solidarit\xE9 Hiver 2026","Course pour la Vie","Un Toit Pour Tous"]},Volunteer_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Actif","Inactif","En formation","Suspendu"]},examples:["Actif","En formation","Inactif"]},Hours_Volunteered__c:{fieldType:"number",generator:"range",params:{min:1,max:200},examples:["8","40","120"]},Tax_Receipt__c:{fieldType:"boolean",generator:"weighted_pick",params:{values:{true:.8,false:.2}},examples:["true","false","true"]}}}],Jd=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...lO]}getPersona(e){let t=lO.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=P$(e),n=await t(r),o=$$(n);this.customCounter+=1;let i=`custom-${Date.now()}-${this.customCounter}`,a={id:i,name:o.name,description:o.description,industry:o.industry,locale:o.locale,dataPatterns:o.dataPatterns};return this.customPersonas.set(i,a),a}getCustomPersonas(){return Array.from(this.customPersonas.values())}},pO=uf(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Te().finite()),io=pO.optional().catch(void 0),Xp=j().min(1).optional().catch(void 0),Yp={faker:V({method:j().transform((s,e)=>{let t=Lf(s);return t||(e.addIssue({code:lf.custom,message:`unknown faker method ${s}`}),df)}),locale:Xp}),random_pick:V({values:ve(cf([j(),Te(),Ke()]).transform(String)).min(1)}),weighted_pick:V({values:Li(j(),pO).refine(s=>Object.keys(s).length>0)}),range:V({min:io,max:io,currency:Xp}),sequence:V({prefix:Xp,start:io,step:io,padLength:io}),pattern:V({pattern:j().min(1)}),ai_generate:V({prompt:j().min(1)}),relative_date:V({minDaysFromNow:io,maxDaysFromNow:io})},E$={faker:'{ "method": one of the faker methods below, "locale" (optional): e.g. "fr_FR" }',random_pick:'{ "values": ["value1", "value2"] }',weighted_pick:'{ "values": { "value1": 0.7, "value2": 0.3 } }',range:'{ "min": number, "max": number, "currency" (optional): e.g. "EUR" }',sequence:'{ "prefix": "INV-", "start" (optional): integer, "step" (optional): integer }',pattern:'{ "pattern": a mask where # stands for a digit, e.g. "FR-#####" }',ai_generate:'{ "prompt": what to write in the field }, only on string and textarea fields',relative_date:'{ "minDaysFromNow": integer, "maxDaysFromNow": integer, negative for the past }'};function P$(s){let e=Object.keys(Yp);return["You are a data generation expert. Based on the following description, create a data generation persona for Salesforce.","",`Description: ${s}`,"","Respond with ONLY a JSON object in this exact format (no markdown, no extra text):","{",' "name": "Persona name",',' "description": "Brief description",',' "industry": "Industry name",',' "locale": "locale code (e.g. en-US, fr-FR)",',' "dataPatterns": {',' "FieldApiName": {',' "fieldType": "string|number|picklist|currency|date|boolean|textarea",',` "generator": "${e.join("|")}",`,' "params": the params of that generator, listed below,',' "examples": ["example1", "example2", "example3"]'," }"," }","}","","Params of each generator:",...e.map(r=>`- ${r}: ${E$[r]}`),"",`Faker methods: ${Mf.join(", ")}.`,"A pattern that uses another generator, another faker method or other params is discarded.","","Include at least 5 relevant field patterns for the described industry."].join(`
|
|
16
|
-
`)}function C$(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(Yp,e))return null;let r=Yp[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!Cf(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function $$(s){let e;try{e=Of(If,s)}catch{throw new Error("AI response is not a valid JSON object. The AI model returned an unexpected format \u2014 try again or check the AI provider configuration.")}let t={};for(let[a,d]of Object.entries(e.dataPatterns))if(typeof d=="object"&&d!==null){let c=C$(d);c&&(t[a]=c)}let{name:r,description:n,industry:o,locale:i}=e;return{name:r,description:n,industry:o,locale:i,dataPatterns:t}}var ts="SEED_WRITE_DECLINED",gO=6e4;function ln(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var wO="the checkpoints of this window are not open to the Seed page",Jt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function ui(s,e){try{if(!s)throw new Error(wO);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Jt(Cn,kr(t))}}async function li(s,e,t,r,n){let o=await qa(async()=>{if(!s)throw new Error(wO);return s.take(e.ask,{runId:t},{planned:e.planned,signal:r,onProgress:({percentage:i,processedObjects:a,totalObjects:d})=>n(Math.round(i),a,d,jo(i))})});if("stop"in o)throw new Jt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function Ln(s,e,t,r,n){if(!(!e||!s))try{return await s.settle(e,t)}catch(o){return r(`[WARN] ${n}: the checkpoint '${e.name}' taken before the run is kept: `+I(o)),e}}function pi(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function Xd(s,e){return typeof s.unread=="string"?{firing:[]}:Vr(s,void 0,e)}function fO(s,e,t){return t==="refuse"?{code:vt.unanswered,message:`The seed needed an answer before it wrote \u2014 ${e} delivers the emails what still runs sends, or would not say whether it does \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}:{code:fR,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var x$={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function D$(s,e){let t=[];return s.check.verdict==="unread"&&t.push(`the data storage ${e} has left could not be read (${s.check.unread})`),s.api.verdict==="near"&&t.push(`it would leave ${e} ${s.api.remaining-s.api.estimate} of its ${s.api.max} daily API requests`),t.join(", and ")}function hO(s,e){return`The seed needed an answer before it wrote \u2014 ${D$(s,e)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}function mO(s,e,t){if(Os(s))return t(`[OFFLINE] seed NOT queued for replay (inserts are not idempotent): ${e}`),{offlineReplayAvailable:!1,retryHint:"Seed operations are not queued for offline replay (inserts are not idempotent \u2014 replaying could duplicate records). Re-run the template manually once the org is reachable again."}}var Vd=1e3;function N$(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>Vd||e.errors.length>Vd;return t?{...e,createdIds:e.createdIds.slice(0,Vd),errors:e.errors.slice(0,Vd),truncated:t}:e})}:s}function yO(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function j$(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var M$=new Set(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"]),Kd=class{constructor(e){this.deps=e;this.seedTemplateStore=new un(e.configStore),this.templateManager=new Gd(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new Jd}deps;seedTemplateStore;templateManager;personaManager;registry;liveTracker;runCreations;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}runningRuns=new Set;isRunning(e){return this.runningRuns.has(e)}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}readAutomation(e,t,r,n,o,i,a){let d=this.targetAutomation;return pd({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new ge(gO).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>Tr(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Pe(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(zt):Gt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{Fe(this.deps,e,t,r,n,o),this.liveTracker?.updateProgress(e,t,r,n,o)}}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Cm,e,"seed:automation:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=this.deps.orgManager.getOrg(t.orgId),o=await this.readAutomation(t.orgId,r,t.objects,ye(n,t.orgId),oS(t.objects,t.publishes===!0));if("error"in o)throw new Error(o.error);let i=A(this.deps,e,"seed:automation:response",{orgId:t.orgId,objects:t.objects,preview:o.preview});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){E(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!M$.has(e.type))return!1;switch(e.type){case"seed:describe-global":return await this.handleDescribeGlobal(e),!0;case"seed:describe-object":return await this.handleDescribeObject(e),!0;case"seed:execute":return await this.handleExecute(e),!0;case"seed:automation":return await this.handleAutomation(e),!0;case"seed:template:save":return await this.handleTemplateSave(e),!0;case"seed:template:load":return await this.handleTemplateLoad(e),!0;case"seed:template:list":return await this.handleTemplateList(e),!0;case"seed:template:delete":return await this.handleTemplateDelete(e),!0;case"seed:list-personas":return await this.handleListPersonas(e),!0;case"seed:create-persona":return await this.handleCreatePersona(e),!0;case"seed:scenario:packs":return await this.handleScenarioPacks(e),!0;case"seed:scenario:prepare":return await this.handleScenarioPrepare(e),!0;case"seed:scenario:execute":return await this.handleScenarioExecute(e),!0;case"seed:scenario:agents":return await this.handleScenarioAgents(e),!0;case"seed:scenario:save":return await this.handleScenarioSave(e),!0;case"seed:scenario:test-file":return await this.handleScenarioTestFile(e),!0;default:return!1}}workspaceFolders(){return this.deps.services?.getWorkspaceFolders?.()??[]}answerScenario(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScenarioPacks(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!!$(Nm,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-PT2E2HFD.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){E(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(jm,e,"seed:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{prepareScenario:n,readScenarioCaseStatus:o,scenarioKnowledge:i}=await import("./chunk-GHUA6OQQ.mjs"),{seedObjectAccess:a}=await import("./chunk-57QRXYAZ.mjs"),d=await o(async l=>(await r.query(l)).records),c=await i(a(r),l=>r.describe(l)),u=n(t.pack,{caseStatus:d,knowledge:c,...t.seed!==void 0?{seed:t.seed}:{},...t.articleBodyField!==void 0?{articleBodyField:t.articleBodyField}:{}});this.answerScenario(e,"seed:scenario:prepare:response",{...u})}catch(r){E(this.deps,"seed:scenario:prepare","seed:error",e,r,{retryable:!0})}}async handleScenarioExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Mm,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-4D6OHSX3.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;E(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=Po.safeParse(o.template);if(!i.success){E(this.deps,"seed:scenario:execute","seed:error",e,new Error(`The scenario compiled to a template the seed refuses: ${i.error.issues[0]?.message??"invalid"}`),{code:"SCENARIO_INVALID",retryable:!1});return}await this.runAsked(e,{orgId:t.orgId,template:i.data,...t.locale!==void 0?{locale:t.locale}:{},...t.muteAutomation!==void 0?{muteAutomation:t.muteAutomation}:{},...t.checkpointFirst?{checkpointFirst:t.checkpointFirst}:{}},{pack:t.pack,options:t.options,compiled:o})}async keepScenario(e,t,r){let{compiled:n,pack:o}=t,i=n.tests.filter(l=>l.openCase!==void 0),a=new Set(i.map(l=>l.openCase?.caseKey)),d=Object.keys(r).filter(l=>a.has(l)).length,c={packId:o.id,packName:o.name,tests:n.tests.length,openCasesWritten:d,openCases:a.size};if(d===0)return{...c,companion:{kind:"none"}};let u=this.runCreations;if(!u)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:l,scenarioRunSidecar:g,writeScenarioRunSidecar:p}=await import("./chunk-EFHM2U4D.mjs");return await p(l(),u.storagePath,g({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(l){let g=I(l);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${g}`),{...c,companion:{kind:"failed",message:g}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Lm,e,"seed:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:n}=await import("./chunk-JPEVIXNH.mjs"),{scenarioCasePicklists:o,toolingQueryAll:i}=await import("./chunk-GHUA6OQQ.mjs"),{scenarioProjectOf:a}=await import("./chunk-X3MBY2RX.mjs"),d=await n(i(yO(r))),c=await o(u=>r.describe(u));this.answerScenario(e,"seed:scenario:agents:response",{orgId:t.orgId,agents:d.kind==="agents"?{kind:"agents",agents:d.catalog.agents}:d,project:await a(this.workspaceFolders()),...c?{casePicklists:c}:{}})}catch(r){E(this.deps,"seed:scenario:agents","seed:error",e,r,{retryable:!0})}}async handleScenarioSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Fm,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-PT2E2HFD.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){E(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(_m,e,"seed:error",this.deps);if(!t)return;let r=n=>this.answerScenario(e,"seed:scenario:test-file:response",{runId:t.runId,outcome:n});try{let n=this.runCreations,o=n?await n.get(t.runId):void 0,i=o?this.deps.orgManager.getOrg(o.targetOrgId):void 0;if(!n||!o||!i){r({kind:"unavailable",reason:"run-unknown",message:o?"The org this run wrote to is no longer connected to SandForge: reconnect it on the Organizations page, then write the test file again.":"Nothing of this run is kept any more."});return}let a=await q(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:d}=await import("./chunk-JPEVIXNH.mjs"),{nodeAgentTestSpecFiles:c}=await import("./chunk-KATBU46O.mjs"),{toolingQueryAll:u}=await import("./chunk-GHUA6OQQ.mjs"),{findScenarioPack:l,nodeScenarioPackFiles:g}=await import("./chunk-PT2E2HFD.mjs"),{nodeScenarioSidecarFiles:p}=await import("./chunk-EFHM2U4D.mjs"),{scenarioProjectOf:f,writeRunTestFile:h}=await import("./chunk-X3MBY2RX.mjs"),m=this.workspaceFolders(),y=await h({sidecar:p(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await f(m),alias:ye(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(u(yO(a))),findPack:(R,S)=>l(g(),m,R,S)});r(y)}catch(n){E(this.deps,"seed:scenario:test-file","seed:error",e,n,{retryable:!0})}}async handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(xm,e,"seed:error",this.deps);if(t)try{let r=t.template;if(r.id&&this.templateManager.get(r.id)){let n=this.templateManager.update(r.id,r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}else{let n=this.templateManager.create(r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}}catch(r){E(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(yl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.load(t.id),n=A(this.deps,e,"seed:template:load:response",{template:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:template:load","seed:error",e,r)}}async handleTemplateList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.seedTemplateStore.list().map(o=>({id:o.id,name:o.name,description:o.description,tags:o.tags,updatedAt:o.updatedAt,objectCount:o.objects.length,totalRecords:o.objects.reduce((i,a)=>i+a.recordCount,0)})),n=A(this.deps,e,"seed:template:list:response",{templates:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){E(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(yl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.delete(t.id),n=A(this.deps,e,"seed:template:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:template:delete","seed:error",e,r)}}async handleListPersonas(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.personaManager.getBuiltInPersonas(),r=this.personaManager.getCustomPersonas(),n=[...t,...r].map(i=>({id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns})),o=A(this.deps,e,"seed:list-personas:response",{personas:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){E(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Dm,e,"seed:error",this.deps);if(t)try{let r=t;if(!r.description||r.description.trim().length===0){let c=A(this.deps,e,"seed:create-persona:response",{persona:{id:"",name:"",description:"",industry:"",locale:"",dataPatterns:{}},success:!1,error:"Description is required to create a custom persona"});this.deps.broker.postToWebview(c);return}let n=this.deps.services;if(!n?.isAIEnabled())throw new Error("AI is disabled. Enable sandforge.ai.enabled and add your Anthropic API key in SandForge Settings > AI > API key to create custom personas.");let o=async c=>(await n.aiClient().chat({messages:[{role:"user",content:c}]})).text,i=await this.personaManager.createCustomPersona(r.description,o),a={id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns},d=A(this.deps,e,"seed:create-persona:response",{persona:a,success:!0});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(r){E(this.deps,"seed:create-persona","seed:error",e,r)}}buildSeedCallAI(){let e=this.deps.services;return e?.isAIEnabled()?async t=>{try{return(await e.aiClient().chat({messages:[{role:"user",content:t}]})).text}catch(r){return this.deps.log(`[AI] seed data generation failed, falling back to faker: ${I(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Pm,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new ge(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(u=>u.createable).filter(u=>!qi(u.name)).map(u=>({apiName:u.name,label:u.label,recordCount:0,dependencies:[]})),c=A(this.deps,e,"seed:describe-global:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(o){E(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$($m,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=wt(r.objectApiName),d=await new ge(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(g=>g.createable).map(g=>({fieldApiName:g.name,label:g.label,type:g.type,required:!g.nillable&&!g.defaultedOnCreate,picklistValues:g.picklistValues?.map(p=>p.value)??[],referenceTo:g.referenceTo??[],length:g.length,integerDigits:Ff(g),objectApiName:r.objectApiName})),u=eS(i,d.recordTypeInfos,i===Ao?await Zl(o):[]),l=A(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:u});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){E(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Em,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){E(this.deps,"seed:execute","seed:error",e,new Error('Seed has no dry run: remove "dryRun" from this request to run the seed.'),{code:"DRY_RUN_UNSUPPORTED",retryable:!1});return}await this.runAsked(e,r)}async runAsked(e,t,r){let n=e.id,o={module:"seed",operation:e.type};try{let i=await this.clearSeed(t,n,o,x$,r!==void 0);if("refusal"in i){let{refusal:u}=i;E(this.deps,"seed:execute","seed:error",e,new Error(u.message),{code:u.code,retryable:!1,...u.extraPayload?{extraPayload:u.extraPayload}:{}}),u.failed&&je(this.deps,n,u.message,!1,{context:o,...u.failed.authored?{authored:!0}:{}});return}let a=r?`Seed of the scenario ${r.pack.name}`:"Seed data generation",{abortController:d,execution:c}=this.beginSeed(e,i,n,o,a,void 0,r);this.registry?this.registry.register(n,"seed",a,c,d):await c}catch(i){this.deps.infraServices?.performanceTracker?.complete(n),this.liveTracker?.fail(n,I(i));let a=mO(i,n,this.deps.log);E(this.deps,"seed:execute","seed:error",e,i,{code:Eo(i),retryable:!0,extraPayload:a}),je(this.deps,n,I(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1,i=!1){let a=z=>{i||Q(this.deps,z)},d=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,c=e.template.objects.map(z=>({...z,batchSize:z.batchSize??d}));Object.assign(r,Xr(c));let u=await q(e.orgId,this.deps.orgRegistry,this.deps.orgManager),l={...e.template,objects:c},g=l.objects.some(z=>z.objectApiName===Ao)?tS(l,await Zl(u)):{template:l,personObjects:[]};if("refusal"in g)return{refusal:{code:"RECORD_TYPES_MIXED",message:g.refusal}};let p={orgId:e.orgId,template:g.template,personObjects:g.personObjects,locale:await rS(e.locale,u)},f=e.template.objects.reduce((z,oe)=>z+oe.recordCount,0),h=[],m=z=>{h.push(z),this.deps.log(`[WARN] seed:execute ${t}: ${z}`)},y=this.deps.orgManager.getOrg(p.orgId),R=ye(y,p.orgId),S=g.template.objects.map(z=>({objectApiName:z.objectApiName,recordCount:z.recordCount})),w=this.targetAutomation,O=await new ge(gO).withTimeout("seed automation",()=>w.read(p.orgId,S.map(z=>z.objectApiName))).catch(z=>({unread:I(z)})),P=nS(g.template,o),v;if("muteAutomation"in e&&e.muteAutomation===!0)try{v=await Ot(async()=>_t(u),O,{...this.muteLeases,writes:P})}catch(z){if(!Dt(z))throw z;return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:z.code}),{refusal:{code:z.code,message:z.message,extraPayload:{},failed:{authored:!0}}}}v&&(p.mute=v);let b=dS(e.fit,f);b&&(p.fit=b);let{describedFieldsOf:C,requiredForAccountKinds:k}=await import("./chunk-SU24AE3H.mjs"),T=0,x=C(async z=>(T++,u.describe(z))),J=sS(O,v?.plan,P,await iS(g.template,O,x.unset)),U=await dr({read:O,...v?.plan?{plan:v.plan}:{},writes:P,readDeliverability:()=>Pe(y)==="production"?Promise.resolve(zt):Gt(u),accepted:!1,target:R,run:"seed",keepsAddresses:!0}),K={read:U,accepted:!1};p.emails=K;let re=U.gate.verdict==="asks",N;if(e.checkpointFirst!==void 0){let z={module:"seed",orgId:p.orgId,operationId:t,written:S.filter(oe=>oe.recordCount>0).map(oe=>oe.objectApiName),running:J.running??{firing:[]},request:e.checkpointFirst};try{N=await ui(this.beforeRunCheckpoints,z)}catch(oe){if(!(oe instanceof Jt))throw oe;return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:oe.code}),{refusal:{code:oe.code,message:oe.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:L,templateTheOrgTakes:B}=await import("./chunk-57QRXYAZ.mjs"),te=await B(g.template,L(u)),se=Hv(Ts(this.deps.services),g.template),H=await Uv(te,{describeCreateableFields:x.createable,describeRequiredFields:k(x,g.personObjects)},se),X={duplicateRules:Uo(O),partition:se,slices:H,slicesRead:T,bulkThreshold:lt(this.deps).bulk.threshold,automationRead:$n(O)},ae=await Gv(cr(u,p.orgId),te,g.personObjects,ye(y,p.orgId),N?.planned,{...xn(U.ofRun),...kb(v?.plan)},X,J.room);if(ae.check.verdict==="unread"&&m(`the data storage the org has left could not be read (${ae.check.unread}): whether the records fit is not known`),ae.refusal){let z=ae.refusedFor==="checkpoint",oe=z?Cn:ae.refusedFor==="apiRequests"?Mo:Ql,ee=z?ae.checkpointRefusal?.code:void 0;a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:oe,...ee!==void 0?{details:{checkpointRefusal:ee}}:{}});let fe=ae.check,D=z?void 0:aS(Jv(ae),te,g.personObjects,J.room,X);return{refusal:{code:oe,message:ae.refusal,extraPayload:{...fe.verdict==="unread"||oe!==Ql?{}:{estimateMB:Number(Ws(fe.estimateMB)),remainingMB:fe.remainingMB,...Ar(fe),maxMB:fe.maxMB,org:ye(y,p.orgId)},...ee!==void 0?{checkpointRefusal:ee}:{},...D?{fit:D}:{}},failed:{authored:!0}}}}let me=await this.readAutomation(p.orgId,u,S.map(z=>z.objectApiName),R,P,v?.automation??O,U.gate.deliverability),ce=gd(me,S,R);for(let z of ce.unknown??[])m(z);if(ce.refusal)return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:ep}),{refusal:{code:ep,message:ce.refusal,extraPayload:{...ce.figures?{...ce.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};if(i)return{preview:{records:te.objects.reduce((z,oe)=>z+oe.recordCount,0),objects:te.objects.length,storage:ae.check,apiRequests:ae.api,automation:tp(me,R),warnings:h},storage:ae,asks:ae.check.verdict==="unread"||ae.api.verdict==="near"||N!==void 0||re,emailsAsked:re,emails:U};let be=this.deps.infraServices?.productionGuard;if(!be)return Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:Re.code}),{refusal:{code:Re.code,message:Re.message,failed:{authored:!1}}};let Ye={orgId:p.orgId,orgTier:Pe(y),operation:"insert",objectName:"SeedData",recordCount:f,module:"seed"},{check:De,decision:_e}=await et(be,Ye);if((_e==="refused"||_e==="declined")&&Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e}),_e==="refused")throw Rn(De.blockedReason??De.impactSummary);if(_e==="declined")return{refusal:{code:xt.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(ae.check.verdict==="unread"||ae.api.verdict==="near"||N!==void 0||re){let z=await n.ask(be,{stage:"write",module:"seed",org:R,orgTier:Pe(y),objects:g.template.objects.map(oe=>({objectApiName:oe.objectApiName,rows:oe.recordCount})).sort((oe,ee)=>ee.rows-oe.rows),total:f,storage:Dn(ae.check),counted:!0,...Lo(ae.api),...N?{checkpoint:N.planned}:{},...U.gate.confirmation});if(z==="confirmed"&&re&&(K.accepted=!0),z==="declined")return Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:ts,...ln(K)}),{refusal:{code:ts,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(z==="unavailable"&&re){let oe=fO(U,R,n.unanswered);return Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:oe.code,...ln(K)}),{refusal:{...oe,failed:{authored:!0}}}}if(z==="unavailable"&&N!==void 0)return Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:vt.unanswered}),{refusal:{code:vt.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${R} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(z==="unavailable"&&n.unanswered==="refuse")return Q(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:vt.unanswered}),{refusal:{code:vt.unanswered,message:hO(ae,R),failed:{authored:!0}}};z==="unavailable"&&this.deps.log(`[WARN] seed:execute ${t}: nobody could be asked about the storage or the API requests the org has left; the seed goes on`)}return{conn:u,run:p,plannedRecords:f,storageMB:ae.check.estimateMB,guardDecision:_e,automation:me,orgName:R,warnings:h,...N?{checkpoint:N}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),Je(this.deps,r,"seed",o),this.liveTracker?.register(r,"seed",o,t.plannedRecords),br({action:"seed_execute",orgId:t.run.orgId,operationId:r},t.storageMB);let d=new AbortController,c=this.executeSeed(e,t.conn,t.run,r,d,n,t.guardDecision,i,a,t.checkpoint);return{abortController:d,execution:c}}pipelineSeedOf(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)throw gr(vt.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let r=nk(Pe(t),e.answer,ye(t,e.orgId));if(r)throw r;let n=Yo(e.orgId,e.templateId,o=>this.seedTemplateStore.load(o));if("refusal"in n)throw n.refusal;return n.asked}async previewForPipeline(e,t){let r=this.pipelineSeedOf(e),n={module:"seed",operation:"seed:pipeline"},o={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"},i=await this.clearSeed(r,crypto.randomUUID(),n,o,!1,!0);if("refusal"in i)throw gr(i.refusal.code,i.refusal.message);if(t?.aborted)throw new Rt("The simulation of the seed was stopped before it said what the seed would meet. Nothing was written.");if(i.asks&&!e.answer.approved){let a=ye(this.deps.orgManager.getOrg(e.orgId),e.orgId);if(i.emailsAsked){let d=fO(i.emails,a,o.unanswered);throw gr(d.code,d.message)}throw gr(vt.unanswered,hO(i.storage,a))}return i.preview}async seedForPipeline(e,t){let r=this.pipelineSeedOf(e),n=vn("seed:pipeline",crypto.randomUUID(),"seed:execute"),o=n.id,i={module:"seed",operation:n.type},a={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"};return Ca(e.answer,async()=>{let d=await this.clearSeed(r,o,i,a);if("refusal"in d)throw gr(d.refusal.code,d.refusal.message);if(t?.aborted)throw Q(this.deps,{action:"seed_execute",module:"seed",operationId:o,orgId:e.orgId,outcome:"stopped",guard:d.guardDecision,code:bt}),new Rt("The seed was cancelled before it wrote anything. Nothing was written.");let c=tp(d.automation,d.orgName);for(let m of c)this.deps.log(`[INFO] seed:execute ${o}: ${m}`);let u,l=`Pipeline seed of ${r.template.name}`,{abortController:g,execution:p}=this.beginSeed(n,d,o,i,l,{pipeline:e.pipeline,ended:m=>{u=m}});this.registry?.register(o,"seed",l,p,g);let f=()=>{this.registry?this.registry.abort(o):g.abort()};t?.addEventListener("abort",f,{once:!0});try{await p}finally{t?.removeEventListener("abort",f)}let h=u;if(h===void 0)throw new Error("The seed ended without a result.");if("error"in h)throw h.error instanceof Error?h.error:new Error(I(h.error));return{operationId:o,runId:h.result.operationId,result:h.result,automation:c,warnings:d.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,u){let l=lt(this.deps),g=new Date().toISOString(),p,f=!1,h={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let R=Rr(this.deps),S=new Qa({retryConfig:l.retry,signal:o.signal,onRetry:(ie,Ee,Ne)=>{this.deps.log(`[RETRY] seed insert attempt=${ie} code=${Ee.originalError.statusCode} delay=${Ne}ms`)}}),w=this.deps,O=crypto.randomUUID(),P=d?this.deps.orgManager.getOrg(r.orgId)?.orgId:void 0,v=this.runCreations?.recorder({runId:O,targetOrgId:r.orgId,startedAt:g,...d?{pipeline:d.pipeline}:{},...P?{targetOrganizationId:P}:{}});Er(v,()=>t.identity(),`seed:execute ${n}`);let b={base:0,total:0},C=(ie,Ee,Ne)=>{let st=b.base+ie,Be=Math.max(b.total,st,Ee,1),Ve=Math.round(st/Be*100);Fe(w,n,Ve,st,Be,Ne),this.liveTracker?.updateProgress(n,Ve,st,Be,Ne)},k=Rv({conn:t,bulkThreshold:l.bulk.threshold,bulkManager:R,retry:S,signal:o.signal,label:`seed:execute ${n}`,log:ie=>this.deps.log(ie),onProgress:C,...v?{calls:{sending:(ie,Ee,Ne)=>v.sending(ie,Ee,Ne),answered:(ie,Ee)=>v.answered(ie,Ee)}}:{}}),T=async(ie,Ee,Ne,st)=>{Ne.length>0&&(f=!0);let Be=await k(ie,Ee,Ne,st);return v?.note(Ee,Be.successIds),Be},x=ie=>this.deps.log(`[WARN] seed:execute ${n}: what the run created could not all be kept, so removing it may leave some of it in the org: ${I(ie)}`),{SeedValidator:J}=await import("./chunk-JRI6A24G.mjs"),{DataPlanBuilder:U}=await import("./chunk-F44EHXLI.mjs"),{FieldMapper:K}=await import("./chunk-LNAZHI3J.mjs"),{ReferenceLinker:re}=await import("./chunk-PGG4ULEW.mjs"),{AIDataGenerator:N}=await import("./chunk-MN3XBJPE.mjs"),{FakerFallback:L}=await import("./chunk-ZP3WJGS3.mjs"),{readExistingParentIds:B,readPresentParentIds:te}=await import("./chunk-FM5ESRH6.mjs"),{seedObjectAccess:se}=await import("./chunk-57QRXYAZ.mjs"),{describedFieldsOf:H,requiredForAccountKinds:X}=await import("./chunk-SU24AE3H.mjs"),{seedTargetOf:ae}=await import("./chunk-7ZYCRIHE.mjs"),me=c?(await import("./chunk-LY6EPMIP.mjs")).seedKnowledge:void 0,ce=new N(this.buildSeedCallAI()),be=new L(r.locale),Ye=new K({aiGenerator:ce,fakerFallback:be}),De=new re,_e=new J,z=new U,{SeedGrappeAdapter:oe}=await import("./chunk-PTTHSSQO.mjs"),ee=Ts(this.deps.services),fe=H(ie=>t.describe(ie)),D={validator:_e,describeCreateableFields:fe.createable,describeVisibleFields:fe.visible,describeComputedFields:fe.computed,describePicklistValues:fe.picklistValues,describeFieldLengths:fe.lengths,describeRequiredFields:X(fe,r.personObjects),objectAccess:se(t),readExistingParentIds:(ie,Ee,Ne)=>B(t,ie,Ee,Ne),readPresentParentIds:(ie,Ee)=>te(t,ie,Ee),describeKeyPrefix:fe.keyPrefix,...ae(t),planBuilder:z,fieldMapper:Ye,referenceLinker:De,insert:T,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new oe(()=>crypto.randomUUID(),ee?.grappeSize),grappeConfig:ee,onGrappeEvent:ie=>ia(this.deps,ie),onProgress:ie=>{b.base=ie.processedRecords,b.total=ie.totalRecords,C(0,ie.totalRecords,`Insert ${ie.objectApiName}`)},signal:o.signal,...c&&me?{onRowIds:(ie,Ee)=>{ie==="Case"&&Object.assign(h,Ee)},knowledge:me({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...v?{journal:v}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let W=this.deps.services.seedOrchestrator(D),Y=r.template;Fe(this.deps,n,0,0,1,"Validating template and building plan");let F;this.runningRuns.add(O);let Z=r.mute,_=Z?.muted;try{u&&(p=await li(this.beforeRunCheckpoints,u,O,o.signal,this.checkpointProgress(n)),v?.checkpoint?.(p));let ie=Z?.prepared?await Z.prepared.acquire(O):void 0;ie&&(_=ie.outcome);let Ee=ie&&r.emails?r.emails.read.afterLease(ie.outcome,r.emails.accepted):void 0;if(ie&&Ee)throw _=await ie.release(),new Jt(Ee.code,Ee.message);F=await W.execute(Y,r.orgId,O).finally(async()=>{ie&&(_=await ie.release())}),_&&(F={...F,mutedAutomation:_});let Ne=await Ln(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:execute ${n}`);p=void 0,Ne&&(F={...F,checkpoint:Ne})}catch(ie){throw await v?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(x),this.runningRuns.delete(O),ie}await v?.end({finishedAt:new Date().toISOString(),status:F.status,...F.cancelled?{cancelled:!0}:{},objectResults:F.objectResults}).catch(x),c&&(F={...F,scenario:await this.keepScenario(F,c,h)}),this.runningRuns.delete(O),F.cancelled||Fe(this.deps,n,100,1,1,"Seed complete");let de=F.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,de,1),this.deps.infraServices?.performanceTracker?.complete(n),F.cancelled?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:de}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:F.status,totalRecords:de}),F.status==="failure"?this.liveTracker?.fail(n,j$(F)):F.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Se=F.objectResults.some(ie=>ie.recordsCreated+ie.recordsFailed>0),Ue=F.cancelled===!0?Se?"cancelled":"stopped":F.status;Q(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:Ue,...Ue==="stopped"?{code:rt}:{},guard:a,objects:F.objectResults.map(ie=>({...mt(ie.objectApiName),created:ie.recordsCreated,failed:ie.recordsFailed})),source:y,...F.mutedAutomation?{muted:ut(F.mutedAutomation)}:{},...F.checkpoint?.state==="taken"?{checkpointId:F.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...ln(r.emails)});let He=A(this.deps,e,"seed:execute:response",N$(F));if(this.deps.broker.postToWebview(He),this.deps.log(`[TX] ${He.type} id=${He.id}`),d?.ended({result:F}),F.status==="failure"&&!F.cancelled)return{status:"failure"}}catch(R){this.deps.infraServices?.performanceTracker?.complete(n);let S=await Ln(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:execute ${n}`),w=S?.state==="deleted"?`${I(R)} ${tn}`:void 0,O=w!==void 0?new Error(w):R;if(R instanceof Jt){if(R.code===rt)this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let C=I(O);this.liveTracker?.fail(n,C),je(this.deps,n,C,!1,{context:i,authored:!0})}let b=R.refusal?.code;return Q(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:R.code,...b!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...ln(r.emails).details,...b!==void 0?{checkpointRefusal:b}:{}}}:{}}),E(this.deps,"seed:execute","seed:error",e,O,{code:R.code,retryable:!1,...b!==void 0?{extraPayload:{checkpointRefusal:b}}:{}}),d?.ended({error:R}),R.code===rt?void 0:{status:"failure"}}this.liveTracker?.fail(n,I(O));let P=Dt(R)?R:void 0;Q(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:P?"stopped":"failure",guard:a,source:y,...P?{code:P.code}:{},...S?.state==="taken"?{checkpointId:S.checkpointId}:{},...r.fit?{fit:r.fit}:{},...ln(r.emails)});let v=mO(R,n,this.deps.log);return E(this.deps,"seed:execute","seed:error",e,R,{...P?{code:P.code}:{},retryable:!0,extraPayload:{...v,...S?{checkpoint:S}:{}}}),je(this.deps,n,I(O),!0,{extraPayload:v,context:i}),d?.ended({error:O}),{status:"failure"}}}};function L$(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return vh(s)}var gi=class{log;described=new WeakMap;constructor(e){this.log=e.log}describe(e,t){let r=this.described.get(e);r||(r=new Map,this.described.set(e,r));let n=r.get(t);return n||(n=e.describe(t),r.set(t,n)),n}async fetchRecords(e,t,r){let n=await this.getQueryFields(e,t),o=this.buildSoql(n,t,r),i=this.cleanRecords(await Ps(o,async a=>{let d=[],c=await e.query(a);for(d.push(...c.records);!c.done&&c.nextRecordsUrl;)c=await e.queryMore(c.nextRecordsUrl),d.push(...c.records);return d}));return this.log(`[CloneRecordFetcher] Fetched ${i.length} records from ${t}`),i}async countRecords(e,t,r,n=[]){let o=`SELECT COUNT() FROM ${ze(t)}${this.whereOf(r,n)}`;return(await e.query(o)).totalSize}async fetchSample(e,t,r,n,o=[]){let i=await this.getQueryFields(e,t),a=this.buildSoql(i,t,n,o);return a+=` LIMIT ${r}`,this.cleanRecords(await Ps(a,async d=>(await e.query(d)).records))}async getQueryFields(e,t){let r=await this.describe(e,t),n=new Set;n.add("Id");for(let o of r.fields)(o.createable||o.type==="reference")&&n.add(o.name);return Array.from(n)}buildSoql(e,t,r,n=[]){return`SELECT ${e.join(", ")} FROM ${ze(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?L$(e):void 0;return t.length===0?r?` WHERE ${r}`:"":` WHERE ${[...r?[`(${r})`]:[],...t].join(" AND ")}`}cleanRecords(e){return e.map(t=>{let r={...t};return delete r.attributes,r})}};var fi=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(l=>l.from!==l.to&&r.has(l.from)&&r.has(l.to)),o=new Map(e.map(l=>[l,new Set])),i=new Map(e.map(l=>[l,new Set])),a=new Map(e.map(l=>[l,new Set]));for(let l of n)o.get(l.to)?.add(l.from),l.required&&(Qp(l)?a:i).get(l.to)?.add(l.from);let d=ea(i).filter(l=>l.length>1);if(d.length>0)throw new Error(_$(d,n.filter(l=>!Qp(l))));let c=new Map(e.map(l=>[l,new Set([...i.get(l)??[],...a.get(l)??[]])])),u=ea(c).some(l=>l.length>1)?i:c;return F$(ea(o),o,e).flatMap(l=>l.length>1?Rh(l,u):l)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!Qp(r)).map(r=>({field:r.fieldApiName,referenceTo:r.from}))}lookupsFilledAfter(e,t){let r=new Map(e.map((n,o)=>[n,o]));return t.filter(n=>{let o=r.get(n.to),i=r.get(n.from);return!n.required&&o!==void 0&&i!==void 0&&i>=o})}detectSelfReferentialEdges(e){return e.filter(t=>t.from===t.to)}buildEdgesFromDescribe(e,t){let r=new Set(e),n=[];for(let o of e){let i=t.get(o);if(i){for(let a of i.fields)if(a.createable!==!1&&!(o===nr&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=ws(o,a.name,a.nillable)||a.updateable===!1;for(let c of a.referenceTo)r.has(c)&&n.push({from:c,to:o,fieldApiName:a.name,relationshipType:"lookup",required:d})}}}for(let o of pl(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function F$(s,e,t){let r=new Map;t.forEach((c,u)=>{r.has(c)||r.set(c,u)});let n=new Map;s.forEach((c,u)=>c.forEach(l=>n.set(l,u)));let o=s.map(c=>Math.min(...c.map(u=>r.get(u)??1/0))),i=s.map((c,u)=>{let l=new Set;for(let g of c)for(let p of e.get(g)??[]){let f=n.get(p);f!==void 0&&f!==u&&l.add(f)}return l}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let u=0;u<s.length;u++)a.has(u)||[...i[u]].some(l=>!a.has(l))||(c===-1||o[u]<o[c])&&(c=u);if(c===-1)break;a.add(c),d.push(s[c])}return d}function Qp(s){return pl(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function _$(s,e){let t=s.flatMap(r=>{let n=new Set(r);return e.filter(o=>o.required&&n.has(o.from)&&n.has(o.to)).map(o=>`${o.to}.${o.fieldApiName}`)});return`Cycle detected among objects: ${s.flat().join(", ")}. ${U$(t)} must be set when the record is created, so no object of the cycle can be written first.`}function U$(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function Zp(s){return s==="insert"||s==="upsert"}function Yd(s,e){return{sending:(t,r,n)=>{Zp(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{Zp(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!Zp(r))return;let o=ud(r,n);s.answered(t,o),e?.(o.length)}}}var B$=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),q$=5,W$=10,z$=-1,bO="Operation blocked by Production Guard: ",Lr={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},G$=3;function J$(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:En(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=Ir({storageBytes:t.reduce((n,o)=>n+o.bytes,0)},e);if(r.verdict==="exceeds")return{estimateMB:r.estimateMB,remainingMB:r.remainingMB,maxMB:r.maxMB,...Ar(r),heaviest:t.slice(0,G$).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function RO(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function TO(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${RO(r.mb)} MB)`).join(", ");return`its records take about ${RO(s.estimateMB)} MB of data storage, and ${e} has ${s.remainingMB} MB left of ${s.maxMB} MB${Wa(s,e)}. The heaviest: ${t}. Narrow their filter or leave them out, then preview again; or copy a sample of the source that fits with Forge (Depth ALL, Records per object: A sample that fits the target).`}function V$(s,e){return`The clone was refused before it wrote anything: ${TO(s,e)} Nothing was written.`}var K$=6e4,X$={neutralized:!1,fields:[],values:0},Y$="PREVIEWED_FOR_OTHER_ORGS",Q$="NOT_PREVIEWED",Z$="PREVIEW_NOT_HELD",ex=50,Zd=class{constructor(e){this.deps=e}deps;registry;liveTracker;previewedOrgs=new Map;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async emailGate(e,t,r,n,o,i){let a=r.filter(c=>c.recordCount>0);if(a.length===0)return;let d=await pd({org:n,objects:a.map(c=>c.objectApiName),readAutomation:c=>o===void 0?this.readTargetAutomation(e,c):typeof o.unread=="string"?Promise.reject(new Error(o.unread)):Promise.resolve(o),readLimits:()=>Tr(t),...i?{deliverability:i}:{}});return gd(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(K$).withTimeout("clone automation",()=>r.read(e,t))}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:clone:execute ${t}: what the clone created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===rt){Q(this.deps,{...t,outcome:"stopped",source:void 0,code:rt}),this.registry?.abort(i),pe(this.deps,i,{aborted:!0,totalInserted:0,totalFailed:0}),this.liveTracker?.cancel(i);let c={status:"partial",objectResults:[],totalSourceRecords:0,totalInserted:0,totalFailed:0,durationMs:o,cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:clone:execute:response",c));return}let a=r.refusal?.code,d=a!==void 0?{checkpointRefusal:a}:{};Q(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),je(this.deps,i,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...d}}),this.liveTracker?.fail(i,r.message)}async handle(e){if(!B$.has(e.type))return!1;switch(e.type){case"seed:clone:describe-source":return await this.handleDescribeSource(e),!0;case"seed:clone:preview":return await this.handlePreview(e),!0;case"seed:clone:execute":return await this.handleExecute(e),!0;default:return!1}}async handleDescribeSource(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Um,e,"seed:clone:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describeGlobal();xe(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!qi(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:z$})),i=A(this.deps,e,"seed:clone:describe-source:response",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){E(this.deps,"seed:clone:describe-source","seed:clone:error",e,r)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wl,e,"seed:clone:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=new gi({log:this.deps.log}),i=new fi,a=t.objects.map(w=>w.objectApiName),d=new Map(t.objects.map(w=>[w.objectApiName,w.whereClause])),c=new Map,u=new Map,l=[];for(let w of t.objects){let[O,P]=await Promise.all([Qd("target",w.objectApiName,()=>n.describe(w.objectApiName)),Qd("source",w.objectApiName,()=>o.describe(r,w.objectApiName))]);xe(n.limitInfo,`seed:clone:preview describe ${w.objectApiName} in the target`),xe(r.limitInfo,`seed:clone:preview describe ${w.objectApiName}`),c.set(w.objectApiName,O),u.set(w.objectApiName,P);let v=kh(w.objectApiName,SO(w.objectApiName,c.get(w.objectApiName),u.get(w.objectApiName)),d),[b,C,k]=await Promise.all([o.countRecords(r,w.objectApiName,w.whereClause,v),o.fetchSample(r,w.objectApiName,q$,w.whereClause,v),v.length>0?o.countRecords(r,w.objectApiName,w.whereClause):void 0]),T=k===void 0?0:k-b;l.push({objectApiName:w.objectApiName,recordCount:b,...T>0?{leftToThePlatform:T}:{},sampleRecords:C.map(x=>ux(x,W$))})}let g=i.buildEdgesFromDescribe(a,kO(c,u)),p=i.resolveInsertOrder(a,g),f=l.map(w=>({...w,relationships:i.lookupsOf(w.objectApiName,g)})),h=ox(i.lookupsFilledAfter(p,g),p),m=sx(p,u,c),y=ix(p,c,u),R={objects:f,insertOrder:p,...h.length>0?{filledAfterInsert:h}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},S=A(this.deps,e,"seed:clone:preview:response",R);this.deps.broker.postToWebview(S),this.deps.log(`[TX] ${S.type} id=${S.id}`),this.rememberPreview(e.id,t,new Map(l.map(w=>[w.objectApiName,w.recordCount])),new Set(i.lookupsFilledAfter(p,g).map(w=>w.to)))}catch(r){let n=r instanceof ec?r:void 0;E(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:rx,retryable:!1,extraPayload:{objectApiName:n.objectApiName,org:ye(this.deps.orgManager.getOrg(t.targetOrgId),t.targetOrgId)}}:{}})}}rememberPreview(e,t,r,n){this.previewedOrgs.set(e,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,recordCounts:r,secondPass:n});for(let o of this.previewedOrgs.keys()){if(this.previewedOrgs.size<=ex)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:Q$,reason:"Clone refused: it names no preview. Preview it, then run the preview shown."};let t=this.previewedOrgs.get(e.previewId);if(!t)return{code:Z$,reason:"Clone refused: the preview it names is not one SandForge answered, or no longer holds. Preview it again."};if(t.sourceOrgId!==e.sourceOrgId||t.targetOrgId!==e.targetOrgId)return{code:Y$,reason:"Clone refused: its preview was made for another source or target org. Preview it again."}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wl,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){E(this.deps,e.type,"seed:clone:error",e,new Error(r.reason),{code:r.code});return}let n=e.id,o=Date.now(),i={module:"seed",operation:e.type,...Xr(t.objects.map(w=>({objectApiName:w.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((w,O)=>{d=P=>P===void 0?w():O(P)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let u={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},l=!1,g,p=0,f,h=!1,m=[],y=!!(t.upsert&&t.externalIdField),R=Pv(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),S=()=>R?.report()??X$;try{let w=this.deps.infraServices?.productionGuard;if(!w){Q(this.deps,{...u,outcome:"stopped",source:void 0,code:Re.code}),je(this.deps,n,Re.message,!1,{context:i,extraPayload:{code:Re.code}}),d(new Error(Re.message));return}let O=this.deps.orgManager.getOrg(t.targetOrgId),P={orgId:t.targetOrgId,orgTier:Pe(O),operation:t.upsert?"upsert":"insert",objectName:t.objects.map(M=>M.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:v,decision:b}=await et(w,P);if(u.guard=b,(b==="refused"||b==="declined")&&Q(this.deps,{...u,outcome:"stopped",source:void 0}),b==="refused")throw new Error(`${bO}${v.blockedReason??v.impactSummary}`);if(b==="declined"){let M="Operation cancelled by user (confirmation declined).";je(this.deps,n,M,!1,{context:i,extraPayload:{code:Lr.confirmationDeclined}}),d(new Error(M));return}let C=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),k=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),T=ye(O,t.targetOrgId),x=this.previewedOrgs.get(t.previewId??""),J=x?.recordCounts,U=t.objects.map(M=>({objectApiName:M.objectApiName,recordCount:J?.get(M.objectApiName)??0})),K=U.filter(M=>M.recordCount>0).map(M=>M.objectApiName),re=(M,G,le)=>{let ke=le!==void 0?{checkpointRefusal:le}:{};Q(this.deps,{...u,outcome:"stopped",source:void 0,code:M,...le!==void 0?{details:ke}:{}}),je(this.deps,n,G,!1,{context:i,authored:!0,extraPayload:{code:M,...ke}}),d(new Error(G))},N,L=K.length>0?await this.readTargetAutomation(t.targetOrgId,K).catch(M=>({unread:I(M)})):{unread:"the clone sends no record"},B=K.length>0?await dr({read:L,writes:pi(K,!0),readDeliverability:()=>Pe(O)==="production"?Promise.resolve(zt):Gt(k),accepted:!1,target:T,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,te=B?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{N=await ui(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:K,running:Xd(L,pi(K,!0)),request:t.checkpointFirst})}catch(G){if(!(G instanceof Jt))throw G;re(G.code,G.message);return}let M=Ba(N.planned);if(M){re(M.code,M.message,M.refusal.code);return}}let se=await this.emailGate(t.targetOrgId,k,U,T,L,B?.gate.deliverability);for(let M of se?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${M}`);let H=await Or(cr(k,t.targetOrgId)).catch(M=>({unread:I(M)})),X=t.upsert?void 0:J$(U,H);if(se?.refusal&&se.figures){let M=tx(se.figures,X?`It would be refused for its data storage too: ${TO(X,T)}`:void 0);Q(this.deps,{...u,outcome:"stopped",source:void 0,code:Lr.emailsExceeded}),je(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Lr.emailsExceeded,...se.figures,...X?{alsoRefused:[{code:Lr.storageExceeded,org:T,...X}]}:{}}}),d(new Error(M));return}let ae="unread"in H?await ur(k).catch(M=>({unread:I(M)})):H.dailyApiRequests;if(X){let M=V$(X,T);Q(this.deps,{...u,outcome:"stopped",source:void 0,code:Lr.storageExceeded}),je(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Lr.storageExceeded,org:T,...X}}),d(new Error(M));return}let me=Pn({run:Wv(U.map(M=>({objectApiName:M.objectApiName,rows:M.recordCount})),{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Uo(L),...x?{secondPass:x.secondPass}:{},automationRead:K.length>0?$n(L):0}),...Fo(N?.planned),...xn(B?.ofRun)},ae);me.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${me.unread})`);let ce=Ha(me,T,ba);if(ce){Q(this.deps,{...u,outcome:"stopped",source:void 0,code:Lr.apiBudgetExceeded}),je(this.deps,n,ce,!1,{context:i,authored:!0,extraPayload:{code:Lr.apiBudgetExceeded}}),d(new Error(ce));return}let be=!1;if(N||te){let M=U.filter(le=>le.recordCount>0).map(le=>({objectApiName:le.objectApiName,rows:le.recordCount})).sort((le,ke)=>ke.rows-le.rows),G=await w.confirmRun({stage:"write",module:"seed",org:T,orgTier:Pe(O),objects:M,total:M.reduce((le,ke)=>le+ke.rows,0),storage:Dn(Ir({storageBytes:M.reduce((le,ke)=>le+En(ke.objectApiName,{rows:ke.rows}),0)},H)),counted:!0,...Lo(me),...N?{checkpoint:N.planned}:{},...B?.gate.confirmation});if(G!=="confirmed"){let le=B?.gate.stop;G!=="declined"&&!N&&le?re(le.code,le.message):re(G==="declined"?ts:vt.unanswered,G==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${T} \u2014 and there was no one to ask. Nothing was written.`);return}be=te}if(u.details=ln(B?{read:B,accepted:be}:void 0).details,Je(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),br(u,U.reduce((M,G)=>M+En(G.objectApiName,{rows:G.recordCount}),0)/1048576),N)try{f=await li(this.beforeRunCheckpoints,N,n,a.signal,(M,G,le,ke)=>{Fe(this.deps,n,M,G,le,ke),this.liveTracker?.updateProgress(n,M,G,le,ke)})}catch(M){if(!(M instanceof Jt))throw M;this.stoppedForCheckpoint(e,u,M,i,Date.now()-o),d(M.code===rt?void 0:M);return}l=!0;let Ye=lt(this.deps),De=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=De;let _e=new Map,z={objects:0,records:0,of:1};g=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),f&&g?.checkpoint?.(f),Er(g,()=>k.identity(),`seed:clone:execute ${n}`),g&&this.runningRuns.add(n);let oe=new Nn({...g?{calls:Yd(g,M=>{p+=M})}:{},keyPrefixOf:M=>_e.get(M)?.keyPrefix,connection:k,bulkExecutor:new On(Ye.bulk.threshold),bulkManager:Rr(this.deps),retryConfig:Ye.retry,signal:a.signal,onProgress:(M,G,le)=>{Fe(this.deps,n,G>0?Math.round(M/G*100):0,M,G,le),this.liveTracker?.updateProgress(n,Math.round((z.objects+M/Math.max(G,1))/z.of*100),z.records+M,0,le)},log:M=>this.deps.log(M)}),ee=new gi({log:this.deps.log}),fe=new fi,D=t.objects.map(M=>M.objectApiName),W=new Set(D),Y=new Map,F=new Map,Z=new Map;for(let M of D){let[G,le]=await Promise.all([Qd("target",M,()=>k.describe(M)),Qd("source",M,()=>ee.describe(C,M))]);xe(k.limitInfo,`seed:clone:execute describe ${M}`),xe(C.limitInfo,`seed:clone:execute describe ${M} in the source`),Y.set(M,G),F.set(M,le),Z.set(M,Pr(G).fields??[]),_e.set(M,{keyPrefix:G.keyPrefix??null,recordTypes:Gh(G.recordTypeInfos)})}let _=fe.buildEdgesFromDescribe(D,kO(Y,F)),de=fe.resolveInsertOrder(D,_),Se=fe.lookupsFilledAfter(de,_);z.of=Math.max(de.length,1);let Ue=new Map(t.objects.map(M=>[M.objectApiName,M])),He=new Map,ie=new Map,Ee=new Map,Ne=[],st=new Sh,Be=0,Ve=!1,fs=new Map,Wn=[],zn=W.has(ra),jt=M=>Lt(k,M),Ci=new Map,hr=new Map,$i=Zn(vr(M=>Lt(C,M)),async M=>F.get(M)??await ee.describe(C,M)),mo=new Map,yo=async(M,G)=>{if(G.length===0)return;let le=await $i(M);for(let ke of le){let we=!1;for(let Le of G)ke in Le&&(we||=Le[ke]!==null&&Le[ke]!==void 0,delete Le[ke]);we&&mo.set(M,(mo.get(M)??new Set).add(ke))}},Gn=async(M,G)=>{let le=(Y.get(M)?.fields??[]).filter(Le=>Le.type==="reference"),ke=await jR({lookups:le,rows:G,known:Ci,query:jt});if(ke.size===0)return;let we=hr.get(M)??new Map;for(let Le of G)for(let{name:he}of le){let Xe=Le[he];typeof Xe!="string"||!ke.has(Xe)||(delete Le[he],we.set(he,(we.get(he)??0)+1))}we.size!==0&&(hr.set(M,we),this.deps.log(`[INFO] seed:clone ${M}: written without a user or a queue the target does not hold, which the platform fills (the owner with the user the clone writes as): `+[...we].map(([Le,he])=>`${Le} on ${he}`).join(", ")))},hs=async(M,G)=>{await yo(M,G),await Gn(M,G),R&&Cv(R,M,Z.get(M)??[],G,y?t.externalIdField:void 0),G.length>0&&(h=!0);try{return{outcomes:t.upsert&&t.externalIdField?await oe.upsert(M,t.externalIdField,G,De):await oe.insert(M,G,De),stopped:!1}}catch(le){if(!(le instanceof Jo))throw le;return{outcomes:le.written,stopped:!0}}},mr=(M,G,le,ke)=>{M.forEach((we,Le)=>{let he=typeof G[Le]?.Id=="string"?G[Le].Id:"";if(we.success){le.insertedCount++,he&&we.id&&(He.set(he,we.id),le.idMappings.push({sourceId:he,targetId:we.id}));let Xe=we.id;if(Xe)for(let{fieldName:Ce,sourceRefId:qt}of ke[Le]??[])Ne.push({objectApiName:le.objectApiName,newId:Xe,sourceId:he||void 0,fieldName:Ce,sourceRefId:qt})}else we.existingId?(le.linkedCount=(le.linkedCount??0)+1,he&&(He.set(he,we.existingId),le.idMappings.push({sourceId:he,targetId:we.existingId}))):(le.failedCount++,le.errors.push({sourceId:he,message:we.errors[0]??"Unknown insert error"}))})},xi=async M=>{let G=new Map((m.find(he=>he.objectApiName===nr)?.idMappings??[]).map(he=>[he.sourceId,he.targetId])),le=new Map;for(let[he,Xe]of fs){let Ce=G.get(he);Ce&&le.set(Xe,Ce)}let ke=M.map(he=>String(he.Id)).filter(he=>le.has(he));if(ke.length===0)return new Map;let we;try{we=await Ih(jt,[...new Set(ke.map(he=>le.get(he)??""))])}catch(he){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${I(he)}`),new Map}let Le=new Map;for(let he of ke){let Xe=we.get(le.get(he)??"");Xe&&Le.set(he,Xe)}return Le},Ur=async(M,G,le)=>{if(Eh[M]===void 0)return new Map;let ke;try{ke=await Ph(jt,M,le)}catch(Le){return this.deps.log(`[seed:clone] ${M}: the relations the target holds not looked up, written as read: ${I(Le)}`),new Map}let we=new Map;for(let[Le,he]of ke){let Xe=G[Le]?.Id;typeof Xe=="string"&&we.set(Xe,he)}return we},Di=async(M,G)=>{if(ie.size===0)return new Map;let le=Y.get(wr),ke=[...new Set(G.flatMap(Ce=>Object.keys(Ce)))].filter(Ce=>IO(le,Ce)),we;try{we=await Th(jt,G.map((Ce,qt)=>({OpportunityId:Ce.OpportunityId,[As]:Ce[As],IsPrimary:M[qt]?.IsPrimary})),Ce=>ie.get(Ce),ke)}catch(Ce){return this.deps.log(`[seed:clone] ${wr}: the roles the platform wrote with the clone's opportunities not looked up, written as read \u2014 an opportunity may hold the role of its contact twice: ${I(Ce)}`),new Map}let{found:Le,alike:he}=we;if(he.length>0){this.deps.log(`[seed:clone] ${wr}: ${Ah(he.length)}`);for(let Ce of he)ie.delete(String(G[Ce]?.OpportunityId))}let Xe=new Map;for(let[Ce,qt]of Le){let kt=M[Ce]?.Id;typeof kt=="string"&&(Xe.set(kt,String(qt.Id)),Ee.set(kt,qt),ie.delete(String(G[Ce]?.OpportunityId)))}return Xe},Et=async(M,G)=>{let le=Y.get(wr),ke=[];if(M.forEach(([he,Xe],Ce)=>{let qt=Ee.get(String(he.Id))??{},kt=Object.entries(G[Ce]??{}).filter(([ue,Me])=>IO(le,ue)&&Me!==null&&Me!==void 0&&String(qt[ue]??"")!==String(Me));kt.length>0&&ke.push({Id:Xe,...Object.fromEntries(kt)})}),ke.length===0||Ve||a.signal.aborted)return;let we;try{we=await oe.update(wr,ke,De)}catch(he){if(!(he instanceof Jo))throw he;Ve=!0,we=he.written}let Le=ke.flatMap((he,Xe)=>we[Xe]?.success?[]:[`${he.Id}: ${we[Xe]?.errors[0]??"not updated"}`]);Le.length>0&&this.deps.log(`[seed:clone] ${wr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${Le.slice(0,3).join(" | ")}`)},hn=async()=>{zn=!1;let M=Wn.splice(0,Wn.length),G=m.find(he=>he.objectApiName===nr);if(M.length===0||!G||Ve)return;if(a.signal.aborted){Ve=!0;return}let le=M.map(he=>AO(nr,he,Y.get(nr),W,He)),ke=OO(nr,M,le,Se,He),{outcomes:we,stopped:Le}=await hs(nr,le);mr(we,M,G,ke),z.records+=M.length,Le&&(Ve=!0)};for(let M=0;M<de.length;M++){if(a.signal.aborted){Ve=!0;break}let G=de[M],le=Ue.get(G);Fe(this.deps,n,Math.round(M/de.length*100),M,de.length,`Cloning ${G}`),z.objects=M,this.liveTracker?.updateProgress(n,Math.round(M/de.length*100),z.records,0,`Cloning ${G}`);let ke;try{ke=await ee.fetchRecords(C,G,le.whereClause)}catch(Ae){Be++,m.push({objectApiName:G,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:I(Ae)}]});continue}let we=st.keep(G,ke,SO(G,Y.get(G),F.get(G)).map(({name:Ae})=>Ae)),Le=ke.length-we.length;if(G===nr)for(let Ae of we){let qe=Ae.ActivityId;typeof Ae.Id=="string"&&typeof qe=="string"&&qe!==""&&fs.set(Ae.Id,qe)}let he=we.map(Ae=>AO(G,Ae,Y.get(G),W,He)),Xe=cx(we,Y.get(G));Xe.length>0&&this.deps.log(`[INFO] seed:clone ${G}: ${Xe.length} field(s) the target does not have left out \u2014 ${Xe.join(", ")}`);let Ce=OO(G,we,he,Se,He),qt=Jh(G,he,_e.get(G)?.recordTypes??[]);if(qt.length>0){Be++,m.push({objectApiName:G,sourceCount:ke.length,insertedCount:0,failedCount:we.length,...Le>0?{leftToThePlatform:Le}:{},idMappings:[],errors:qt.map(Ae=>{let qe=we.find((Ze,Ct)=>Vh(he[Ct],[Ae]));return{sourceId:typeof qe?.Id=="string"?qe.Id:Ae.recordTypeId,message:Kh(Ae)}})});continue}if(G===nr&&zn){let Ae=we.map(qe=>Oh(qe));Wn.push(...we.filter((qe,Ze)=>Ae[Ze])),we=we.filter((qe,Ze)=>!Ae[Ze]),he=he.filter((qe,Ze)=>!Ae[Ze]),Ce=Ce.filter((qe,Ze)=>!Ae[Ze])}let kt=G===ra?await xi(we):G===wr?await Di(we,he):await Ur(G,we,he),ue=[],Me=[];if(kt.size>0){let Ae=we.map(qe=>!kt.has(String(qe.Id)));we.forEach((qe,Ze)=>{Ae[Ze]||(ue.push([qe,kt.get(String(qe.Id))??""]),Me.push(he[Ze]))}),we=we.filter((qe,Ze)=>Ae[Ze]),he=he.filter((qe,Ze)=>Ae[Ze]),Ce=Ce.filter((qe,Ze)=>Ae[Ze])}if(a.signal.aborted){Ve=!0;break}let{outcomes:ot,stopped:Br}=await hs(G,he);if(Br&&(Ve=!0,ot.length===0))break;if(G===lx&&ot.forEach((Ae,qe)=>{let Ze=he[qe]?.[As];Ae.success&&Ae.id&&Ae.created!==!1&&typeof Ze=="string"&&Ze!==""&&ie.set(Ae.id,Ze)}),G===wr&&ue.length>0&&await Et(ue,Me),ue.length>0){let Ae=Y.get(G),qe=await Ch(G,ue,Ze=>Ae?.fields.find(Ct=>Ct.name===Ze)?.updateable!==!1,async Ze=>{try{return await oe.update(G,Ze,De)}catch(Ct){if(!(Ct instanceof Jo))throw Ct;return Ve=!0,Ct.written}},()=>Ve||a.signal.aborted);qe&&this.deps.log(`[seed:clone] ${G}: ${qe}`)}let ht={objectApiName:G,sourceCount:ke.length,insertedCount:0,failedCount:0,linkedCount:kt.size,...G===wr&&kt.size>0?{writtenByThePlatform:kt.size}:{},...Le>0?{leftToThePlatform:Le}:{},...Xe.length>0?{fieldsNotInTarget:Xe}:{},idMappings:[],errors:[]};for(let[Ae,qe]of kt)He.set(Ae,qe),ht.idMappings.push({sourceId:Ae,targetId:qe});if(mr(ot,we,ht,Ce),m.push(ht),z.records+=we.length,Ve)break;G===ra&&await hn()}await hn();let Zt;if(Ne.length>0&&(a.signal.aborted&&(Ve=!0),Zt=Ve?dx(Ne):await ax({owed:Ne,idMap:He,targetConn:k,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:M=>{Fe(this.deps,n,100,z.records,z.records,M),this.liveTracker?.updateProgress(n,100,z.records,0,M)}}),a.signal.aborted&&(Ve=!0),g&&Zt.filled>0)){let M=new Map;for(let{objectApiName:G,newId:le}of Ne)M.set(G,[...M.get(G)??[],le]);for(let[G,le]of M)g.wroteAgain(G,le)}for(let M of m){let G=hr.get(M.objectApiName);G&&(M.lookupsNotCarried=[...G].map(([ke,we])=>({field:ke,records:we})));let le=mo.get(M.objectApiName);le&&(M.encryptedLeftOut=[...le].sort())}let wo=m.reduce((M,G)=>M+G.sourceCount,0),Jn=m.reduce((M,G)=>M+G.insertedCount,0),Ni=m.reduce((M,G)=>M+(G.linkedCount??0),0),ji=m.reduce((M,G)=>M+(G.leftToThePlatform??0),0),$e=m.reduce((M,G)=>M+G.failedCount,0),Ge=$e===0&&Be===0?"success":Jn+Ni>0?"partial":"failure",Qe=Zt!==void 0&&Zt.filled<Zt.owed,at=S(),St=(Ve||Qe)&&Ge==="success"?"partial":Ge,nt=await this.endKept(g,n,{status:St,cancelled:Ve});g=void 0;let ct=await Ln(this.beforeRunCheckpoints,f,h,this.deps.log,`seed:clone:execute ${n}`);f=void 0;let Mt={status:St,objectResults:m,totalSourceRecords:wo,totalInserted:Jn,totalLinked:Ni,...ji>0?{totalLeftToThePlatform:ji}:{},totalFailed:$e,...Zt?{secondPass:Zt}:{},durationMs:Date.now()-o,...Ve?{cancelled:!0}:{},contactPoints:at,...nt&&p>0?{runId:n}:{}};l=!1;let Hr=Ve?Jn+$e>0?"cancelled":"stopped":Mt.status;Q(this.deps,{...vO(u,Hr,m,y,at),...Hr==="stopped"?{code:rt}:{},...ct?.state==="taken"?{checkpointId:ct.checkpointId}:{}});let Pt=!Ve&&Mt.status==="failure"?"No record could be cloned.":void 0;Ve?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalInserted:Jn,totalFailed:$e}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:Mt.status,totalInserted:Jn,totalFailed:$e}),Pt!==void 0?this.liveTracker?.fail(n,Pt):Mt.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let er={...Mt,...ct?{checkpoint:ct}:{}},tr=A(this.deps,e,"seed:clone:execute:response",er);this.deps.broker.postToWebview(tr),this.deps.log(`[TX] ${tr.type} id=${tr.id} status=${Mt.status}`),d(Pt===void 0?void 0:new Error(Pt))}catch(w){let O=await Ln(this.beforeRunCheckpoints,f,h,this.deps.log,`seed:clone:execute ${n}`);l&&Q(this.deps,{...vO(u,"failure",m,y,S()),...O?.state==="taken"?{checkpointId:O.checkpointId}:{}}),await this.endKept(g,n,{status:"failure",cancelled:!1});let P=O?.state==="deleted"?`${I(w)} ${tn}`:I(w);this.deps.log(`[ERR] seed:clone:execute: ${P}`),je(this.deps,n,I(w),!0,{context:i,extraPayload:{code:P.startsWith(bO)?Lr.guardBlocked:Lr.failed,...O?{checkpoint:O}:{}}}),this.liveTracker?.fail(n,P),d(w)}}};function tx(s,e){let t=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(r=>`"${r}"`).join(", ")}`,...s.bypasses.map(r=>"give the user the clone writes as "+(r.permissionSet?`the permission set ${r.permissionSet}, whose ${r.permission}`:`a permission set holding ${r.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${gR(s.emails,s.limit)}, ${s.remaining} of ${s.max} left today. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To clone them, ${t.join("; or ")}. ${e?`${e} `:""}Nothing was written.`}function vO(s,e,t,r,n){return{...s,details:{...s.details,...Es(n).details},outcome:e,objects:t.map(o=>({...mt(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function SO(s,e,t){let r=new Set((t?.fields??[]).map(n=>n.name));return(e?.fields??[]).filter(n=>n.type==="reference"&&r.has(n.name)&&ws(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function Qd(s,e,t){try{return await t()}catch(r){let n=I(r);throw s==="target"&&nx(r,n)?new ec(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var rx="OBJECT_NOT_IN_TARGET",ec=class extends Error{constructor(t,r){super(`${t} is not in the target org, or the user SandForge connects as there may not see it (${r}): untick it to clone the others, or deploy it to the target first (Compare, Deploy from Diff) and give that user access to it.`);this.objectApiName=t;this.name="ObjectNotInTargetError"}objectApiName};function nx(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function kO(s,e){return new Map([...s].map(([t,r])=>{let n=new Map((e.get(t)?.fields??[]).map(i=>[i.name,i.referenceTo??[]])),o=r.fields.flatMap(i=>{if(i.type!=="reference")return[i];let a=n.get(i.name)??[],d=(i.referenceTo??[]).filter(c=>a.includes(c));return d.length>0?[{...i,referenceTo:d}]:[]});return[t,{fields:o}]}))}function ox(s,e){let t=new Map(e.map((r,n)=>[r,n]));return s.map(r=>({objectApiName:r.to,field:r.fieldApiName,referenceTo:r.from})).sort((r,n)=>(t.get(r.objectApiName)??0)-(t.get(n.objectApiName)??0))}function sx(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=tc(t.get(n));return o?(e.get(n)?.fields??[]).filter(i=>i.type==="reference"&&i.createable!==!1&&!o.has(i.name)).flatMap(i=>(i.referenceTo??[]).filter(a=>r.has(a)).map(a=>({objectApiName:n,field:i.name,referenceTo:a}))):[]})}function ix(s,e,t){return s.flatMap(r=>{let n=tc(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&ws(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function OO(s,e,t,r,n){let o=r.filter(c=>c.to===s),i=new Set(o.filter(c=>c.from!==s).map(c=>c.fieldApiName)),a=new Set(o.map(c=>c.fieldApiName)),d=new Set(e.map(c=>c.Id).filter(c=>typeof c=="string"));return t.map((c,u)=>{let l=[];for(let g of a){let p=e[u]?.[g];typeof p!="string"||p===""||n.has(p)||g in c&&(!i.has(g)&&!d.has(p)||(delete c[g],l.push({fieldName:g,sourceRefId:p})))}return l})}async function ax(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-D63HEQ3B.mjs"),n=await r({pendingFkUpdates:e,remapper:s.idMap,updateRecords:async(o,i,a)=>{let d=await t.sobject(i).update(a,{allowRecursive:!0,headers:Bi()});return(Array.isArray(d)?d:[d]).map((c,u)=>{let l=a[u]?.Id;return{id:c.id??(typeof l=="string"?l:""),success:c.success,errors:(c.success?[]:c.errors).map(Aw)}})},targetOrgId:s.targetOrgId,enabled:!0,stopped:s.stopped,onProgress:o=>s.report(o.message)});return{owed:e.length,filled:e.length-(n?.failedCount??0),samples:(n?.samples??[]).map(({recordSummary:o,messages:i})=>({record:o,messages:i}))}}function dx(s){let e=[...new Set(s.map(t=>t.objectApiName))];return{owed:s.length,filled:0,samples:[{record:`${e.join(", ")}: ${s.length} lookup${s.length===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}],cancelledBefore:!0}}function tc(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function cx(s,e){let t=tc(e);if(!t)return[];let r=new Set;for(let n of s)for(let o of Object.keys(n))o!=="Id"&&!t.has(o)&&r.add(o);return[...r].sort()}function ux(s,e){let t={};for(let[r,n]of Object.entries(s)){if(Object.keys(t).length>=e)break;n==null||n===""||(t[r]=n)}return t}var lx="Opportunity";function IO(s,e){if(e==="OpportunityId"||e===As)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function AO(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=tc(t),a={};for(let[d,c]of Object.entries(e))d==="Id"||o.has(d)||i&&!i.has(d)||(a[d]=c);if(t)for(let d of t.fields){if(d.type!=="reference"||!(d.referenceTo??[]).some(u=>r.has(u)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of na(s,a))delete a[d];return a}var px=new Set(["double","currency","percent","int","integer"]),rc=class{validate(e,t,r,n){let o=[],i=new Map(r.map(a=>[a.name,a]));for(let a=0;a<e.length&&o.length<100;a++){let d=e[a];for(let c of t){if(o.length>=100)break;if(!c.sfFieldApiName)continue;let u=i.get(c.sfFieldApiName);if(!u)continue;let l=d[c.csvHeader]??"";if(l===""&&!u.nillable&&u.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:l});continue}if(l!==""){if(px.has(u.type.toLowerCase())){let g=parseFloat(l);isNaN(g)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${l}"`,value:l})}u.length&&u.length>0&&l.length>u.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${u.length} for field "${c.sfFieldApiName}" (got ${l.length})`,value:l}),u.type.toLowerCase()==="picklist"&&u.picklistValues&&u.picklistValues.length>0&&(u.picklistValues.map(p=>p.value).includes(l)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${l}" for field "${c.sfFieldApiName}"`,value:l}))}}}if(n&&o.length<100){let a=t.find(d=>d.sfFieldApiName===n);if(a){let d=new Map;for(let c=0;c<e.length&&o.length<100;c++){let u=e[c][a.csvHeader]??"";if(u==="")continue;let l=d.get(u);l!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${u}" (also in row ${l})`,value:u}):d.set(u,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var gx=new Set(["seed:csv:validate","seed:csv:execute"]),fx=100,EO="IMPORT_CANCELLED",hx=6e4,eg="CSV_STORAGE_EXCEEDED";function mx(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function yx(s,e,t){let r=e>0?En(s,{rows:e})/e:0,n=Vb(t);return r>0?Math.max(0,Math.floor(n*1024*1024/r)):0}var nc=class{constructor(e){this.deps=e}deps;registry;liveTracker;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!gx.has(e.type))return!1;switch(e.type){case"seed:csv:validate":return await this.handleValidate(e),!0;case"seed:csv:execute":return await this.handleExecute(e),!0;default:return!1}}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:csv:execute ${t}: what the import created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===rt){Q(this.deps,{...t,outcome:"stopped",source:void 0,code:EO}),this.registry?.abort(o),pe(this.deps,o,{aborted:!0,insertedCount:0,failedCount:0}),this.liveTracker?.cancel(o);let d={insertedCount:0,failedCount:0,errors:[],cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:csv:execute:response",d));return}let i=r.refusal?.code,a=i!==void 0?{checkpointRefusal:i}:{};Q(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...i!==void 0?{details:a}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),je(this.deps,o,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...a}}),this.liveTracker?.fail(o,r.message)}async handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(bl,e,"seed:csv:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describe(t.objectApiName);xe(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new rc().validate(t.records,t.columnMappings,n.fields,t.externalIdField),a=A(this.deps,e,"seed:csv:validate:response",i);this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} valid=${i.valid}`)}catch(r){E(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(bl,e,"seed:csv:error",this.deps);if(!t)return;let r=e.id,n={module:"seed",operation:e.type,objectName:t.objectApiName},o=new AbortController,i=()=>{},a=new Promise((f,h)=>{i=m=>m===void 0?f():h(m)});a.catch(()=>{}),this.registry?.register(r,"csv","CSV import",a,o);let d={action:"seed_csv_import",module:"seed",operationId:r,orgId:t.orgId,outcome:"failure",source:{origin:"csv"}},c=!1,u,l=0,g,p=!1;try{let f=this.deps.infraServices?.productionGuard;if(!f){Q(this.deps,{...d,outcome:"stopped",source:void 0,code:Re.code}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Re.message),{code:Re.code,retryable:!1}),je(this.deps,r,Re.message,!1,{context:n,extraPayload:{code:Re.code}}),i(new Error(Re.message));return}let h=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Pe(h),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:R}=await et(f,m);if(d.guard=R,(R==="refused"||R==="declined")&&Q(this.deps,{...d,outcome:"stopped",source:void 0}),R==="refused")throw Rn(y.blockedReason??y.impactSummary);if(R==="declined"){let ee="Operation cancelled by user (confirmation declined).";E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ee),{code:xt.declined}),je(this.deps,r,ee,!1,{context:n}),i(new Error(ee));return}let S=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),w=ye(h,t.orgId),O=(ee,fe,D)=>{let W=D!==void 0?{checkpointRefusal:D}:{};Q(this.deps,{...d,outcome:"stopped",source:void 0,code:ee,...D!==void 0?{details:W}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(fe),{code:ee,retryable:!1,...D!==void 0?{extraPayload:W}:{}}),je(this.deps,r,fe,!1,{context:n,authored:!0,extraPayload:{code:ee,...W}}),i(new Error(fe))},P=this.targetAutomation,v=pi([t.objectApiName],!!t.externalIdField),b=await new ge(hx).withTimeout("csv automation",()=>P.read(t.orgId,[t.objectApiName])).catch(ee=>({unread:I(ee)}));typeof b.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${b.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let C=await dr({read:b,writes:v,readDeliverability:()=>Pe(h)==="production"?Promise.resolve(zt):Gt(S),accepted:!1,target:w,run:"seed",keepsAddresses:!0}),k=C.gate.verdict==="asks",T;if(t.checkpointFirst!==void 0){try{T=await ui(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:Xd(b,v),request:t.checkpointFirst})}catch(fe){if(!(fe instanceof Jt))throw fe;O(fe.code,fe.message);return}let ee=Ba(T.planned);if(ee){O(ee.code,ee.message,ee.refusal.code);return}}let x=await Or(cr(S,t.orgId)).catch(ee=>({unread:I(ee)})),J="unread"in x?await ur(S).catch(ee=>({unread:I(ee)})):x.dailyApiRequests,U=Ir({storageBytes:En(t.objectApiName,{rows:t.records.length})},x);if(!t.externalIdField&&U.verdict==="exceeds"){let ee=t.records.length,fe=yx(t.objectApiName,ee,U),D=Ar(U),W=`The import was refused before it wrote anything: its ${ee} rows take about ${mx(U.estimateMB)} MB of data storage, and ${w} has ${U.remainingMB} MB left of ${U.maxMB} MB${Wa(D,w)}, room for about ${fe} of them: split the file and import one part at a time, freeing data storage in between as needed. Nothing was written.`;Q(this.deps,{...d,outcome:"stopped",source:void 0,code:eg});let Y={org:w,rows:ee,fitting:fe,estimateMB:U.estimateMB,remainingMB:U.remainingMB,maxMB:U.maxMB,...D};E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(W),{code:eg,retryable:!1,extraPayload:Y}),je(this.deps,r,W,!1,{context:n,authored:!0,extraPayload:{code:eg,...Y}}),i(new Error(W));return}let K=Pn({run:Bv([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Uo(b)})+qv(0,$n(b)),...Fo(T?.planned),...xn(C.ofRun)},J);K.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${K.unread})`);let re=Ha(K,ye(h,t.orgId),ba);if(re){Q(this.deps,{...d,outcome:"stopped",source:void 0,code:Mo}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(re),{code:Mo,retryable:!1}),je(this.deps,r,re,!1,{context:n,authored:!0,extraPayload:{code:Mo}}),i(new Error(re));return}let N=!1;if(T||k){let ee=t.records.length,fe=await f.confirmRun({stage:"write",module:"seed",org:w,orgTier:Pe(h),objects:[{objectApiName:t.objectApiName,rows:ee}],total:ee,storage:Dn(Ir({storageBytes:En(t.objectApiName,{rows:ee})},x)),...Lo(K),...T?{checkpoint:T.planned}:{},...C.gate.confirmation});if(fe!=="confirmed"){let D=C.gate.stop;fe!=="declined"&&!T&&D?O(D.code,D.message):O(fe==="declined"?ts:vt.unanswered,fe==="declined"?"The import was cancelled before it wrote anything. Nothing was written.":`The import needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${w} \u2014 and there was no one to ask. Nothing was written.`);return}N=k}if(d.details=ln({read:C,accepted:N}).details,Je(this.deps,r,"seed",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`),this.liveTracker?.register(r,"csv",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`,t.records.length),br(d,U.estimateMB),T)try{g=await li(this.beforeRunCheckpoints,T,r,o.signal,(ee,fe,D,W)=>{Fe(this.deps,r,ee,fe,D,W),this.liveTracker?.updateProgress(r,ee,fe,D,W)})}catch(ee){if(!(ee instanceof Jt))throw ee;this.stoppedForCheckpoint(e,d,ee,n),i(ee.code===rt?void 0:ee);return}c=!0;let L=lt(this.deps),B=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=B,u=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),g&&u?.checkpoint?.(g),Er(u,()=>S.identity(),`seed:csv:execute ${r}`),u&&this.runningRuns.add(r);let te=new Nn({connection:S,bulkExecutor:new On(L.bulk.threshold),bulkManager:Rr(this.deps),retryConfig:L.retry,signal:o.signal,onProgress:(ee,fe,D)=>{let W=fe>0?Math.round(ee/fe*100):0;Fe(this.deps,r,W,ee,fe,D),this.liveTracker?.updateProgress(r,W,ee,fe,D)},log:ee=>this.deps.log(ee),...u?{calls:Yd(u,ee=>{l+=ee})}:{}}),se=t.records.map(ee=>wx(ee,t.columnMappings)),H=o.signal.aborted,X=[];if(!H){se.length>0&&(p=!0);try{X=t.externalIdField?await te.upsert(t.objectApiName,t.externalIdField,se,B):await te.insert(t.objectApiName,se,B)}catch(ee){if(!(ee instanceof Jo))throw ee;H=!0,X=ee.written}}let ae=[],me=0;for(let ee of X)ee.success?me++:ae.length<fx&&ae.push(ee.errors[0]??"Unknown insert error");let ce=X.length-me,be=ce===0?"success":me>0?"partial":"failure",Ye=!H&&be==="failure"?ae[0]??"No row could be imported.":void 0;c=!1;let De=await Ln(this.beforeRunCheckpoints,g,p,this.deps.log,`seed:csv:execute ${r}`);g=void 0,H&&X.length===0?Q(this.deps,{...d,outcome:"stopped",source:void 0,code:EO}):Q(this.deps,{...d,outcome:H?"cancelled":be,objects:[{...mt(t.objectApiName),...t.externalIdField?{upserted:me}:{created:me},failed:ce}],...De?.state==="taken"?{checkpointId:De.checkpointId}:{}});let _e=await this.endKept(u,r,{status:H&&be==="success"?"partial":be,cancelled:H});u=void 0;let z={insertedCount:me,failedCount:ce,errors:ae,...H?{cancelled:!0}:{},..._e&&l>0?{runId:r}:{},...De?{checkpoint:De}:{}};H?(this.registry?.abort(r),pe(this.deps,r,{aborted:!0,insertedCount:me,failedCount:ce}),this.liveTracker?.cancel(r)):(pe(this.deps,r,{status:be,insertedCount:me,failedCount:ce}),Ye!==void 0?this.liveTracker?.fail(r,Ye):be==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let oe=A(this.deps,e,"seed:csv:execute:response",z);this.deps.broker.postToWebview(oe),this.deps.log(`[TX] ${oe.type} id=${oe.id} inserted=${me} failed=${ce}`),i(Ye===void 0?void 0:new Error(Ye))}catch(f){let h=await Ln(this.beforeRunCheckpoints,g,p,this.deps.log,`seed:csv:execute ${r}`);c&&Q(this.deps,{...d,...h?.state==="taken"?{checkpointId:h.checkpointId}:{}}),await this.endKept(u,r,{status:"failure",cancelled:!1});let m=h?.state==="deleted"?`${I(f)} ${tn}`:I(f);E(this.deps,"seed:csv:execute","seed:csv:error",e,f,{code:Eo(f),retryable:!0,...h?{extraPayload:{checkpoint:h}}:{}}),je(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(f)}}};function wx(s,e){let t={};for(let r of e){if(!r.sfFieldApiName)continue;let n=s[r.csvHeader];n===void 0||n===""||(t[r.sfFieldApiName]=bx(n))}return t}function bx(s){if(s==="true")return!0;if(s==="false")return!1;if(s==="null")return null;let e=Number(s);return!Number.isNaN(e)&&s.trim()!==""?e:s}var Rx={string:new Set(["string","textarea","richtext","phone","email","url","picklist","multipicklist","encryptedstring"]),int:new Set(["int","double","currency","percent","string"]),double:new Set(["double","currency","percent","string"]),currency:new Set(["currency","double","string"]),percent:new Set(["percent","double","string"]),boolean:new Set(["boolean","string"]),date:new Set(["date","datetime","string"]),datetime:new Set(["datetime","date","string"]),id:new Set(["id","reference","string"]),reference:new Set(["reference","id","string"]),picklist:new Set(["picklist","string","multipicklist"]),multipicklist:new Set(["multipicklist","string"]),phone:new Set(["phone","string"]),email:new Set(["email","string"]),url:new Set(["url","string"]),textarea:new Set(["textarea","richtext","string"]),richtext:new Set(["richtext","textarea","string"]),time:new Set(["time","string"]),base64:new Set(["base64","string"]),address:new Set(["address"]),location:new Set(["location"])},vx=[{source:"double",target:"int",reason:"Decimal portion will be truncated"},{source:"datetime",target:"date",reason:"Time portion will be lost"},{source:"richtext",target:"textarea",reason:"HTML formatting will be lost"},{source:"multipicklist",target:"picklist",reason:"Multiple selections may be lost"}];function tg(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=Rx[t];return n?n.has(r):r==="string"}var oc=class{validateMapping(e,t,r){let n=[],o=[],i=new Map(e.map(d=>[d.apiName,d])),a=new Map(t.map(d=>[d.apiName,d]));for(let[d,c]of Object.entries(r)){let u=i.get(d),l=a.get(c);if(!u||!l)continue;let g=this.checkTypeCompatibility(d,u.type,c,l.type);g.compatible?g.reason&&o.push(g):n.push(g)}return{valid:n.length===0,errors:n,warnings:o}}validateRecords(e,t){let r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let i of t){let a=o[i.apiName];if(i.required&&PO(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(PO(a))continue;let d=this.validateValueType(a,i);if(d){r.push({recordIndex:n,field:i.apiName,message:d});continue}if(i.maxLength!==void 0&&typeof a=="string"&&a.length>i.maxLength&&r.push({recordIndex:n,field:i.apiName,message:`Value exceeds max length of ${i.maxLength} (got ${a.length})`}),i.picklistValues&&i.picklistValues.length>0){let c=String(a);i.picklistValues.includes(c)||r.push({recordIndex:n,field:i.apiName,message:`Value '${c}' is not a valid picklist value. Allowed: ${i.picklistValues.join(", ")}`})}}}return{valid:r.length===0,errors:r}}checkTypeCompatibility(e,t,r,n){let o=t.toLowerCase(),i=n.toLowerCase();if(o===i)return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:!0};let a=tg(o,i),d=vx.find(c=>c.source===o&&c.target===i);return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:a,reason:a?d?.reason:`Type '${t}' is not compatible with '${n}'`}}validateValueType(e,t){let r=t.type.toLowerCase();switch(r){case"boolean":if(typeof e!="boolean")return`Expected boolean but got ${typeof e}`;break;case"int":if(typeof e!="number"||!Number.isInteger(e))return`Expected integer but got ${typeof e=="number"?"float":typeof e}`;break;case"double":case"currency":case"percent":if(typeof e!="number")return`Expected number but got ${typeof e}`;break;case"date":case"datetime":if(typeof e!="string"||!Sx(e))return`Expected valid ${r} string`;break}}};function PO(s){return s==null||s===""}function Sx(s){let e=Date.parse(s);return!isNaN(e)}var sc=class{paused=!1;waiting=new Set;get isPaused(){return this.paused}pause(){this.paused=!0}resume(){this.paused=!1;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}async whilePaused(e){!this.paused||e?.aborted||await new Promise(t=>{let r=()=>{this.waiting.delete(r),e?.removeEventListener("abort",r),t()};this.waiting.add(r),e?.addEventListener("abort",r,{once:!0})})}};var rg=3e4,CO=6e4,ng="Nothing was read or written.",$O="Nothing was read.",xO="the checkpoints of this window are not open to the Sync page",Ox=new Set(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"]),DO={insert:0,update:1,upsert:2,delete:3};function sg(s,e){let t=s.objects??[],r="insert";for(let o of t)DO[o.operation]>DO[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Pe(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function Ix(s){return s.map(e=>{let t={...mt(e.objectApiName),failed:e.failed+(e.delta?.deleteFailed??0),deleted:e.delta?.deleted??0};switch(e.operation){case"insert":return{...t,created:e.success};case"update":return{...t,updated:e.success};case"delete":return{...t,deleted:e.success};case"upsert":{let r=e.upsertSplit??{created:0,updated:0},n=e.success-r.created-r.updated;return{...t,created:r.created,updated:r.updated,...n>0?{upserted:n}:{}}}}})}var Ax=new Set(["direct","rename"]),og=20,Tx=V({fields:ve(V({name:j(),type:j(),createable:Ke(),updateable:Ke()}).loose())});function NO(s,e,t){let r=Tx.safeParse(s);if(r.success)return r.data.fields;let n=r.error.issues[0];throw new Error(`The ${t} org described ${e} in a shape field types cannot be compared on (${n.path.join(".")}: ${n.message}), so the sync was not started and nothing was written.`)}function jO(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=ib();return e?{emailsAccepted:e.approved,emailsLiftedBy:"Approve an Approval step put before this Sync step to sync all the same"}:{emailsLiftedBy:"Run it from the Sync page, which asks before it writes, to sync all the same"}}var ic=class{constructor(e){this.deps=e;this.syncConfigStore=new It(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new aa;syncConfigStore;registry;historyLogger;liveTracker;pauseGates=new Map;runCreations;backupRecords;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",rn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):rn}readCap(){return dd(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0))}writeGateFor(e,t,r,n,o,i){let{targetConn:a}=t,d=this.deps.orgManager.getOrg(e.targetOrgId),c=this.targetAutomation,u=this.deps.infraServices?.productionGuard,l=jO(r),g=this.readCap(),p=Vv(e,async f=>{let{totalSize:h}=await a.query(f);return Math.min(h,g)});return Kv({readStorage:()=>new ge(rg).withTimeout("sync:limits",()=>Or(a)),readApiBudget:()=>new ge(rg).withTimeout("sync:limits",()=>ur(a)),readAutomation:n??(f=>new ge(CO).withTimeout("sync:automation",()=>c.read(e.targetOrgId,f))),readLimits:()=>new ge(rg).withTimeout("sync:limits",()=>Tr(a)),readDeliverability:()=>Pe(d)==="production"?Promise.resolve(zt):Gt(a),emails:{target:ye(d,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:lt(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...p?{countTarget:p}:{},targetFields:async f=>((await t.describeTargetFields(f)).fields??[]).map(h=>h.name)},{policy:r,org:ye(d,e.targetOrgId),orgTier:Pe(d),...u?{confirm:f=>u.confirmRun(f)}:{},emailsLiftedBy:l.emailsLiftedBy})}setRegistry(e){this.registry=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setHistoryLogger(e){this.historyLogger=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;runCheckpointOf(e,t,r,n){let o=this.beforeRunCheckpoints,i={runId:t},a,d,c,u;return{gate:{scope:async(l,g)=>{if(!o)throw new Error(xO);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...l],running:g,request:r},d=await o.scope(a,i),u=d.refusal,d},take:async l=>{if(!o||!a)throw new Error(xO);let g=await o.take(a,i,{planned:l,...n?{signal:n.signal,onProgress:p=>{let f=jo(p.percentage),h=Math.round(p.percentage),{processedObjects:m,totalObjects:y}=p;Fe(this.deps,t,h,m,y,f),this.liveTracker?.updateProgress(t,h,m,y,f)}}:{}});return g.taken?(c=g.checkpoint,n?.recorder?.checkpoint?.(g.checkpoint)):"refusal"in g&&(u=g.refusal),g}},planned:()=>d,taken:()=>c,refusal:()=>u}}async settleRunCheckpoint(e,t,r){let n=e?.taken();if(!(!n||!this.beforeRunCheckpoints))try{return await this.beforeRunCheckpoints.settle(n,t)}catch(o){return this.deps.log(`[WARN] sync ${r}: the checkpoint '${n.name}' taken before the run is kept: ${I(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!Ox.has(e.type))return!1;switch(e.type){case"sync:describe-global":return await this.handleDescribeGlobal(e),!0;case"sync:describe-fields":return await this.handleDescribeFields(e),!0;case"sync:execute":return await this.handleExecute(e),!0;case"sync:simulate":return await this.handleSimulate(e),!0;case"sync:write-order":return await this.handleWriteOrder(e),!0;case"sync:pause":return await this.handleRunControl(e,"pause"),!0;case"sync:resume":return await this.handleRunControl(e,"resume"),!0;case"sync:config:save":return await this.handleConfigSave(e),!0;case"sync:config:load":return await this.handleConfigLoad(e),!0;case"sync:config:list":return await this.handleConfigList(e),!0;case"sync:config:delete":return await this.handleConfigDelete(e),!0;case"sync:config:reset-delta":return await this.handleConfigResetDelta(e),!0;default:return!1}}refusedFieldless(e,t,r,n,o){let i=So(t.objects);return i.length===0?!1:(E(this.deps,r,n,e,new Error(`${ko(i)} ${o}`),{code:zi,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(dm,e,"sync:error",this.deps);if(t&&!this.refusedFieldless(e,t.config,"sync:config:save","sync:error","Nothing was saved."))try{let r=t.config;if(ah(this.syncConfigStore.list(),r.id,r.name)){let o=A(this.deps,e,"sync:config:save:response",{success:!1,id:r.id,code:"DUPLICATE_NAME"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} DUPLICATE_NAME`);return}this.syncConfigStore.save(r);let n=A(this.deps,e,"sync:config:save:response",{success:!0,id:r.id});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.load(t.id),n=A(this.deps,e,"sync:config:load:response",{config:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:load","sync:error",e,r)}}async handleConfigList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.syncConfigStore.list().map(o=>{let i=this.syncConfigStore.loadDelta(o.id);return{id:o.id,name:o.name,description:o.description,updatedAt:o.updatedAt,mode:o.mode,propagateDeletes:o.propagateDeletes===!0,watermarks:i.kind==="stored"?i.state.entries.length:0}}),n=A(this.deps,e,"sync:config:list:response",{configs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){E(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.delete(t.id);await this.runCreations?.idMap().delete(t.id).catch(o=>this.deps.log(`[WARN] sync:config:delete ${t.id}: ${I(o)}`));let n=A(this.deps,e,"sync:config:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"sync:error",this.deps);if(t)try{if(!this.syncConfigStore.load(t.id))throw new Error("This configuration is no longer saved: there is nothing to reset.");let r=this.syncConfigStore.clearDelta(t.id),n=A(this.deps,e,"sync:config:reset-delta:response",{success:!0,id:t.id,cleared:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} cleared=${r}`)}catch(r){E(this.deps,"sync:config:reset-delta","sync:error",e,r)}}deltaStoreFor(){return this.syncConfigStore.deltaStore()}fileStoreFor(){return this.syncConfigStore.fileStore()}idMapFor(){let e=this.runCreations;if(e)return Jw(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=Ix(r.objectResults??[]),d=a.some(u=>u.created+u.updated+u.deleted+u.failed+(u.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;Q(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:rt}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...to(i)},...r.mutedAutomation?{muted:ut(r.mutedAutomation)}:{},...r.checkpoint?.state==="taken"?{checkpointId:r.checkpoint.checkpointId}:{}})}recordRefused(e,t,r){Q(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",code:r})}recordStopped(e,t,r){Q(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",guard:r})}buildGuardRequest(e){return sg(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new oc,i=[],a=u=>({apiName:u.name,type:u.type});for(let u of e.objects){if(u.operation==="delete")continue;let l=u.objectApiName,g=new ge(n),[p,f]=await Promise.all([g.withTimeout(`describe-source-${l}`,()=>Qt(e.sourceOrgId,l,()=>t.describe(l))),g.withTimeout(`describe-target-${l}`,()=>Qt(e.targetOrgId,l,()=>r.describe(l)))]),h=NO(p,l,"source").map(a),m=NO(f,l,"target").filter(w=>w.createable||w.updateable).map(a),y=Ev(u,{creatable:new Set(m.map(w=>w.apiName))}),R=Zh(y.fieldMappings,y.excludedFields),S=[Object.fromEntries(h.filter(w=>!R.has(w.apiName.toLowerCase())).map(w=>[w.apiName,w.apiName])),...u.fieldMappings.filter(w=>Ax.has(w.type)).map(w=>({[w.sourceField]:w.targetField}))];for(let w of S)for(let O of o.validateMapping(h,m,w).errors)i.push(`${l}.${O.sourceField} (${O.sourceType}) -> ${l}.${O.targetField} (${O.targetType})`)}if(i.length===0)return;let d=i.slice(0,og).join("; "),c=i.length>og?` and ${i.length-og} more`:"";throw new Error(`Field types do not match between the orgs, so the sync was not started and nothing was written: ${d}${c}. Map each field onto a field of a compatible type, convert the value with a transform, or leave the field out: Exclude as its mapping on the Field Mapping step, or in the object's excludedFields in a saved configuration.`)}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(cm,e,"sync:error",this.deps);if(!t)return;let r=lt(this.deps);try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new ge(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());xe(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(l=>l.queryable&&!da(l.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(l=>l.createable).map(l=>l.name);else{let l=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=await o.withTimeout("describe-global",()=>l.describeGlobal());xe(l.limitInfo,"sync:describe-global target");let p=new Map(g.sobjects.map(f=>[f.name,{createable:f.createable,updateable:f.updateable}]));d=[];for(let f of a){let h=p.get(f.name);if(h&&(h.createable||h.updateable)){d.push(f.name);continue}f.createable&&c.push({objectApiName:f.name,why:h?"notCreateable":"notInTarget"})}}let u=A(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){E(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(um,e,"sync:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=new ge(n.timeouts.describe),[d,c]=await Promise.all([a.withTimeout("describe-source",()=>o.describe(r.objectApiName)),a.withTimeout("describe-target",()=>i.describe(r.objectApiName))]);xe(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),xe(i.limitInfo,`sync:describe-fields target ${r.objectApiName}`);let u=g=>g.filter(p=>p.createable).map(p=>({apiName:p.name,label:p.label,type:p.type})),l=A(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:u(d.fields),targetFields:u(c.fields)});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){E(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hl,e,"sync:error",this.deps);if(!t)return;let r=t.config;try{let n=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=lt(this.deps).timeouts.describe,i=new Map;for(let u of r.objects){if(u.operation==="delete")continue;let l=u.objectApiName;try{let g=await new ge(o).withTimeout(`describe-target-${l}`,()=>Qt(r.targetOrgId,l,()=>n.describe(l)));i.set(l,Nv(u,Pr(g)))}catch{}}let{order:a}=jv(r.objects,i),d=await this.encryptedMaskedOf(r,o).catch(()=>[]),c=A(this.deps,e,"sync:write-order:response",{order:a,...d.length>0?{encrypted:d}:{},readCap:this.readCap()});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){E(this.deps,"sync:write-order","sync:error",e,n)}}async encryptedMaskedOf(e,t){let r=e.objects.filter(a=>a.operation!=="delete");if(r.length===0)return[];let n=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=Zn(vr(async a=>(await n.query(a)).records),a=>new ge(t).withTimeout(`describe-source-${a}`,()=>Qt(e.sourceOrgId,a,()=>n.describe(a)))),i=[];for(let a of r){let d=await o(a.objectApiName);d.length>0&&i.push({objectApiName:a.objectApiName,fields:d})}return i}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Sn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",ng)||await this.startExecution(e,t.config,"manual",t.muteAutomation===!0,t.checkpointFirst))}async handleSimulate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hl,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",$O))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;Je(this.deps,r,"sync",o),this.liveTracker?.register(r,"sync",o);let a=this.simulateSync(e,n,r,i,t.checkpointFirst);if(this.registry){let d=a.then(c=>({status:c===null||c.error?"failure":"success"}));this.registry.register(r,"sync",o,d,i)}else await a}async simulateSync(e,t,r,n,o,i){let a=lt(this.deps),d={module:"sync",operation:e.type,...Xr(t.objects)};try{let c=await this.readersFor(t,n.signal),{DataSync:u}=await import("./chunk-YNMU5I7P.mjs"),{ConflictResolver:l}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:g}=await import("./chunk-6HAKOS6W.mjs"),{TransformPipeline:p}=await import("./chunk-WZX6VCIT.mjs"),{toolingQueriesOver:f,toolingValidationRules:h}=await import("./chunk-HV63UGL5.mjs"),{toolingRetrievesOver:m}=await import("./chunk-FH5UR35W.mjs"),y=c.targetConn.tooling,R=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},S=new u({insert:R,update:R,upsert:R,delete:R,describeTargetFields:c.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let w=o?this.runCheckpointOf(t,r,o):void 0,O=this.deps.services.syncOrchestrator({dataSync:S,conflictResolver:new l,fieldMapping:new g,transformPipeline:new p,querySource:c.querySource,maskedSourceFields:c.maskedSourceFields,queryTarget:c.queryTarget,services:this.deps.services,signal:n.signal,findInTarget:c.findInTarget,bulkThreshold:a.bulk.threshold,describeTargetFields:c.describeTargetFields,readSourceIds:c.readSourceIds,countSource:c.countSource,countPersonAccounts:c.countPersonAccounts,writeGate:this.writeGateFor(t,c,"ask",void 0,w?.gate),queryTargetRows:c.queryTargetRows,recordTypes:c.recordTypes,currencies:c.currencies,standardPricebooks:c.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:c.deltaReads,idMap:this.idMapFor(),files:c.files,readValidationRules:h(async T=>(await or({query:async x=>y.query(x),queryMore:async x=>y.queryMore(x)},T)).records,f(c.targetConn),m(c.targetConn)),onSimulationProgress:(T,x,J)=>{let U=Math.round(T/x*100),K=`Simulating ${J}`;Fe(this.deps,r,U,T,x,K),this.liveTracker?.updateProgress(r,U,T,x,K)}});await this.assertFieldTypesMatch(t,c.sourceConn,c.targetConn,a.timeouts.describe);let P=await O.simulate(t),v=w?.planned(),b=[...c.cutAtReadCap],C={...P,...v?{checkpoint:v}:{},readCap:c.readCap,...b.length>0?{cutAtReadCap:b}:{},operationId:r};C.cancelled?this.endCancelled(r):C.error?(this.liveTracker?.fail(r,C.error),je(this.deps,r,C.error,!0,{context:d})):(Fe(this.deps,r,100,1,1,"Simulation complete"),pe(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${C.cancelled?"stopped":"finished"}: `+C.objects.map(T=>`${T.objectApiName} insert=${T.insert} update=${T.update} delete=${T.delete} skipped=${T.skipped} refused=${T.refused} conflicts=${T.conflicts}`).join("; "));let k=A(this.deps,e,"sync:simulate:response",C);return this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`),C}catch(c){return this.liveTracker?.fail(r,I(c)),E(this.deps,"sync:simulate","sync:error",e,c),je(this.deps,r,I(c),!0,{context:d}),i?.(c),null}}async simulateForPipeline(e,t){let r=Sn.safeParse({config:e});if(!r.success)throw new Error(`Pipeline sync config failed validation: ${r.error.issues.map(p=>p.message).join("; ")}`);let n=So(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${ko(n)} ${$O}`),{code:zi});let o=vn("sync:pipeline",crypto.randomUUID(),"sync:simulate"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(p=>({...p,batchSize:p.batchSize??a}))},c=`Pipeline simulation of a sync of ${d.objects.length} object(s), writing nothing`,u=new AbortController,l=()=>u.abort();t?.aborted&&u.abort(),t?.addEventListener("abort",l,{once:!0}),Je(this.deps,i,"sync",c),this.liveTracker?.register(i,"sync",c);let g;try{let p=this.simulateSync(o,d,i,u,void 0,h=>{g=h});this.registry?.register(i,"sync",c,p.then(h=>({status:h===null||h.error?"failure":"success"})),u);let f=await p;if(f===null)throw g instanceof Error?g:new Error(I(g));return f}finally{t?.removeEventListener("abort",l)}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=$(am,e,"sync:error",this.deps);if(!r)return;let{operationId:n}=r,o=t==="pause"?"sync:pause:response":"sync:resume:response",i=this.pauseGates.get(n),a;i?(t==="pause"?(i.pause(),this.liveTracker?.pause(n)):(i.resume(),this.liveTracker?.resume(n)),a={success:!0,operationId:n,paused:i.isPaused}):a={success:!1,operationId:n,paused:!1,error:"No sync with this id is running: it has finished, or it was not started here."};let d=A(this.deps,e,o,a);this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id} paused=${a.paused}`)}async readersFor(e,t){let r=lt(this.deps),n=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=this.readCap(),a=new Set,d=new Qa({retryConfig:r.retry}),c=(k,T)=>async(x,J,U)=>{let K=wt(J.objectApiName),re="",N=$s(J.where,U?.changedSince);N&&(re+=` WHERE ${N}`),J.orderBy&&(re+=` ORDER BY ${ll(J.orderBy)}`);let L=!1,B=await d.execute(async()=>{L=!1;let se=(await k.describe(K)).fields.map(ae=>ae.name),H=se.length>0?se:["Id"],X={query:async ae=>k.query(ae),queryMore:async ae=>k.queryMore(ae)};return Ps(`SELECT ${H.join(", ")} FROM ${K}${re}`,async ae=>{let me=await or(X,ae,i);return L||=me.truncated,me.records})});if(!B.success)throw B.error??new Error("Query failed after retries");xe(k.limitInfo,`sync:execute query ${K}`);let te=B.result??[];if(L){U?.onBoundReached?.();let se=te.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,H=T===e.sourceOrgId?"source":"target";H==="source"&&a.add(J.objectApiName);let X=H==="source"?"this sync copies a subset, not the whole object":"conflict detection ran against a subset of the destination";this.deps.log(`[WARN] sync:execute ${K} (${H}): read stopped at ${te.length} record(s) \u2014 bound: ${se}. ${X}.`),Ie(this.deps,"warning","Sync",`${K}: only ${te.length} record(s) were read from the ${H} (bound: ${se}) \u2014 ${X}. `+Lv(H,i,Mv))}return te},u=async(k,T,x)=>{let U=`SELECT COUNT() FROM ${wt(T.objectApiName)}`,K=$s(T.where,x?.changedSince);K&&(U+=` WHERE ${K}`);let{totalSize:re}=await n.query(U);return Math.min(re,i)},l=async(k,T)=>{let x=wt(k.objectApiName),J=$s(k.where,T?.changedSince),U=`SELECT COUNT() FROM ${x} WHERE IsPersonAccount = true`+(J?` AND (${J})`:"");try{return(await n.query(U)).totalSize}catch{return 0}},g=new Map,p=async k=>{let T=g.get(k);if(T)return T;let x=await o.describe(k),J=Pr(x);return g.set(k,J),J},f=async k=>Pr(await o.describe(k)),h=async k=>(await or({query:async T=>o.query(T),queryMore:async T=>o.queryMore(T)},k)).records,m=Xh({query:async k=>o.query(k),queryMore:async k=>o.queryMore(k)},t),y=async(k,T,x,J)=>{let U=await m(k,T,x,J);return xe(o.limitInfo,`sync:simulate lookup ${T.objectApiName}`),U},R=em({query:async(k,T)=>n.query(k,T),queryMore:async k=>n.queryMore(k)},{query:async k=>o.query(k),queryMore:async k=>o.queryMore(k)},t),S=k=>({pages:{query:async T=>k.query(T),queryMore:async T=>k.queryMore(T)},transport:k,create:async(T,x)=>k.sobject(T).create(x,{headers:Bi()})}),w=async(k,T)=>{let J=`SELECT Id FROM ${wt(k.objectApiName)}`,U=$s(k.where,T);U&&(J+=` WHERE ${U}`),k.orderBy&&(J+=` ORDER BY ${ll(k.orderBy)}`);let{records:K}=await or(S(n).pages,J,i);return K.flatMap(re=>typeof re.Id=="string"?[re.Id]:[])},O={copy:Sv({[e.sourceOrgId]:S(n),[e.targetOrgId]:S(o)}),sourceIds:w,store:this.fileStoreFor(),...e.files!==void 0&&vv(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(k,T)=>Tw(await o.sobject(k).destroy(T),k).map(x=>({id:x.id,success:x.success,errors:x.errors}))}:{}},P=async()=>{let{readSyncRecordTypes:k}=await import("./chunk-BK5SRDAD.mjs");return k(S(n).pages,S(o).pages)},v=async()=>{let{readRunCurrencies:k}=await import("./chunk-OETEC3P7.mjs");return k(async T=>(await n.query(T)).records,async T=>(await o.query(T)).records,{source:async T=>(await n.tooling.query(T)).records,target:async T=>(await o.tooling.query(T)).records})},b=async()=>{let{readStandardPricebooks:k}=await import("./chunk-OTKXTBTX.mjs");return k(async T=>(await n.query(T)).records,async T=>(await o.query(T)).records)},C=Zn(vr(async k=>(await n.query(k)).records),k=>Qt(e.sourceOrgId,k,()=>n.describe(k)));return{sourceConn:n,targetConn:o,querySource:c(n,e.sourceOrgId),queryTarget:c(o,e.targetOrgId),maskedSourceFields:C,countSource:u,describeTargetFields:p,describeTargetFieldsAgain:f,queryTargetRows:h,recordTypes:P,currencies:v,standardPricebooks:b,findInTarget:y,readSourceIds:k=>w(k),countPersonAccounts:l,deltaReads:R,files:O,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=$(Sn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",ng)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=Sn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=So(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${ko(n)} ${ng}`),{code:zi});let o=t==="pipeline"?vn("sync:pipeline",crypto.randomUUID(),"sync:execute"):vn("sync:schedule",crypto.randomUUID(),"sync:execute"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(m=>({...m,batchSize:m.batchSize??a}))},c=this.deps.infraServices?.productionGuard;if(!c)throw this.recordRefused(i,d.targetOrgId,Re.code),sa();let{check:u,decision:l}=await et(c,this.buildGuardRequest(d)),g=l;if((l==="refused"||l==="declined")&&this.recordStopped(i,d.targetOrgId,l),l==="refused")throw new Error(`Operation blocked by Production Guard: ${u.blockedReason??u.impactSummary}`);if(l==="declined")throw new Error(`${t==="pipeline"?"Pipeline":"Scheduled"} sync cancelled (confirmation declined).`);this.dmlTracker.register(i,"sync","upsert",d.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let p=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;Je(this.deps,i,"sync",p),this.liveTracker?.register(i,"sync",p,0,{pausable:!0});let f=new AbortController,h=this.executeSync(o,d,i,f,t,g);return this.registry?.register(i,"sync",p,h,f),h}async startExecution(e,t,r,n=!1,o){let i=e.id,a={module:"sync",operation:e.type},d=this.registry?.holdUntilStart(i);try{let c=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,u=t,l={...u,objects:u.objects.map(S=>({...S,batchSize:S.batchSize??c}))};Object.assign(a,Xr(l.objects));let g=this.deps.infraServices?.productionGuard;if(!g){this.recordRefused(i,l.targetOrgId,Re.code),E(this.deps,"sync:execute","sync:error",e,new Error(Re.message),{code:Re.code}),je(this.deps,i,Re.message,!1,{context:a});return}let{check:p,decision:f}=await et(g,this.buildGuardRequest(l)),h=f;if((f==="refused"||f==="declined")&&this.recordStopped(i,l.targetOrgId,f),f==="refused")throw Rn(p.blockedReason??p.impactSummary);if(f==="declined"){let S="Operation cancelled by user (confirmation declined).";E(this.deps,"sync:execute","sync:error",e,new Error(S),{code:xt.declined}),je(this.deps,i,S,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,l,f);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),E(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),je(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",l.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${l.objects?.length??0} object(s)`;Je(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,R=this.executeSync(e,l,i,y,r,h,n,o);this.registry?this.registry.register(i,"sync",m,R,y):await R}catch(c){this.dmlTracker.markFailed(i),E(this.deps,"sync:execute","sync:error",e,c,{code:Eo(c)}),je(this.deps,i,I(c),!0,{context:a})}finally{d?.release()}}answerCancelledBeforeStart(e,t,r){Q(this.deps,{action:"sync_execute",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:r,code:bt});let n={configId:t.id,operationId:e.id,status:"partial",objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0,timestamp:new Date().toISOString(),cancelled:!0,error:"Cancelled before it started: nothing was written."},o=A(this.deps,e,"sync:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} (cancelled before it started)`)}endCancelled(e){this.registry?.abort(e),pe(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=t.id?t:{...t,id:r},u=lt(this.deps),l,g,p=!1,f,h=v=>({measure:b=>v.measure(b),hold:async b=>{let C=await v.hold(b);return f=C.answer.emails,C}}),m=new sc;this.pauseGates.set(r,m);let y=o==="pipeline"?this.deps.orgManager.getOrg(c.targetOrgId)?.orgId:void 0,R=this.runCreations?.recorder({runId:r,configId:c.id,configName:c.name??"",sourceOrgId:c.sourceOrgId,targetOrgId:c.targetOrgId,...y?{targetOrganizationId:y}:{}}),S=this.backupRecords,w=R&&S?id({runId:r,orgId:c.targetOrgId,files:S,meta:this.deps.configStore}):void 0,O=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...R?{recorder:R}:{}}):void 0,P=()=>{try{w?.close()}catch(v){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+I(v))}};try{let v=await this.readersFor(c,n.signal),{sourceConn:b,targetConn:C}=v;Er(R,()=>C.identity(),`sync ${r}`);let k=v.queryTargetRows,T=R&&w?ad({query:k,backup:w,recorder:R,describe:v.describeTargetFields,viewsEncrypted:vr(k)}):void 0,x=new On(u.bulk.threshold),J=Rr(this.deps),U=new Nn({connection:C,bulkExecutor:x,bulkManager:J,retryConfig:u.retry,signal:n.signal,pauseGate:m,onProgress:(z,oe,ee)=>{let fe=Math.round(z/oe*100);Fe(this.deps,r,fe,z,oe,ee),this.liveTracker?.updateProgress(r,fe,z,oe,ee)},log:z=>this.deps.log(z),...R?{calls:ld(R,T)}:{}}),{DataSync:K}=await import("./chunk-YNMU5I7P.mjs"),{ConflictResolver:re}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:N}=await import("./chunk-6HAKOS6W.mjs"),{TransformPipeline:L}=await import("./chunk-WZX6VCIT.mjs"),B=z=>{z.length>0&&(p=!0)},te=new K({upsert:(z,oe,ee,fe)=>(B(ee),U.upsert(z,oe,ee,fe)),insert:(z,oe,ee)=>(B(oe),U.insert(z,oe,ee)),update:(z,oe,ee)=>(B(oe),U.update(z,oe,ee)),delete:(z,oe,ee)=>(B(oe),U.delete(z,oe,ee)),describeTargetFields:v.describeTargetFields}),se=new re,H=new N,X=new L,ae={dataSync:te,conflictResolver:se,fieldMapping:H,transformPipeline:X,querySource:v.querySource,maskedSourceFields:v.maskedSourceFields,queryTarget:v.queryTarget,services:this.deps.services,grappeConfig:Ts(this.deps.services),onGrappeEvent:z=>ia(this.deps,z),countSource:v.countSource,countPersonAccounts:v.countPersonAccounts,describeTargetFields:v.describeTargetFields,describeTargetFieldsAgain:v.describeTargetFieldsAgain,leaseOfTheGate:()=>g?.lease(),queryTargetRows:k,readSourceIds:v.readSourceIds,findInTarget:v.findInTarget,writeGate:(()=>{let z=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return h(this.writeGateFor(c,v,z,void 0,O?.gate));let oe=this.targetAutomation;return g=Yv((fe,D)=>this.writeGateFor(c,v,z,fe,O?.gate,D),fe=>new ge(CO).withTimeout("sync:automation",()=>oe.read(c.targetOrgId,fe)),fe=>Ot(async()=>_t(C),fe,{...this.muteLeases,writes:Xv}),r,{target:ye(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:jO(z).emailsLiftedBy}),h(g.gate)})(),recordTypes:v.recordTypes,currencies:v.currencies,standardPricebooks:v.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:v.deltaReads,files:{...v.files,onProgress:(z,oe)=>{Fe(this.deps,r,z,0,0,oe),this.liveTracker?.updateProgress(r,z,0,0,oe)}},...R?{creations:R}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let me=this.deps.services.syncOrchestrator(ae);await this.assertFieldTypesMatch(c,b,C,u.timeouts.describe),Fe(this.deps,r,10,0,1,"Initializing sync");let ce=await me.execute(c).finally(async()=>{l=await g?.release()}),be=await this.settleRunCheckpoint(O,p,r),Ye=[...v.cutAtReadCap],De={...ce,...Ye.length>0?{status:ce.status==="success"?"partial":ce.status,readCap:v.readCap,cutAtReadCap:Ye}:{},...l?{mutedAutomation:l}:{},...be?{checkpoint:be}:{}};if(await R?.end({status:De.status,cancelled:De.cancelled===!0}),P(),De.cancelled?this.endCancelled(r):(Fe(this.deps,r,100,1,1,"Sync complete"),pe(this.deps,r,{status:De.status??"completed"}),De.status==="failure"?this.liveTracker?.fail(r,De.error??"No record could be synced."):De.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let z=De.objectResults.flatMap(oe=>oe.files?[oe.files]:[]);this.deps.log(`[sync] ${r} files: ${kv(z)}`)}xe(b.limitInfo,"sync:execute completion (source)"),xe(C.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,De,o)}catch(z){this.deps.log(`[WARN] sync history logging failed: ${I(z)}`)}this.recordRun(c,r,De,i,o,f);let _e=A(this.deps,e,"sync:execute:response",De);return this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id}`),De}catch(v){await R?.end({status:"failure"}),P(),this.dmlTracker.markFailed(r);let b=await this.settleRunCheckpoint(O,p,r),C=b?.state==="deleted";if(this.liveTracker?.fail(r,I(v)),v instanceof Dv){let J=O?.refusal(),U=C?`${v.message} ${tn}`:v.message,K={...J?{checkpointRefusal:J.code}:{},...b?{checkpoint:b}:{}};return Q(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:v.code,details:{triggeredBy:o,...J?{checkpointRefusal:J.code}:{},...to(f)}}),E(this.deps,"sync:execute","sync:error",e,v,{code:v.code,extraPayload:K}),je(this.deps,r,U,!1,{context:{module:"sync",operation:e.type,...Xr(c.objects)}}),{...v.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:U,...b?{checkpoint:b}:{}}}Os(v)&&o!=="rerun"&&d===void 0&&this.deps.infraServices?.offlineManager?this.deps.infraServices.offlineManager.enqueue({id:r,type:"sync",orgId:c.targetOrgId,payload:{config:c}})&&this.deps.log(`[OFFLINE] sync queued for replay on reconnect: ${r}`):Os(v)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let k=C?new Error(`${I(v)} ${tn}`):v;E(this.deps,"sync:execute","sync:error",e,v,{...b?{extraPayload:{checkpoint:b}}:{}}),je(this.deps,r,I(k),!0,{context:{module:"sync",operation:e.type,...Xr(c.objects)}});let x={...(v instanceof xv?v.result:void 0)??{objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0},configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:I(k),...b?{checkpoint:b}:{}};try{this.historyLogger?.logExecution(c,x,o)}catch(J){this.deps.log(`[WARN] sync history logging failed: ${I(J)}`)}return this.recordRun(c,r,x,i,o,f),x}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var Ex=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),ac=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!Ex.has(e.type))return!1;switch(e.type){case"sync:history:list":return this.handleList(e),!0;case"sync:history:detail":return this.handleDetail(e),!0;case"sync:history:export":return this.handleExport(e),!0;case"sync:history:rerun":return await this.handleRerun(e),!0;default:return!1}}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.historyStore.list(),r=A(this.deps,e,"sync:history:list:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${t.length}`)}catch(t){E(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ml,e,"sync:history:error",this.deps);if(t)try{let r=this.historyStore.load(t.entryId)??null,n=A(this.deps,e,"sync:history:detail:response",{entry:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Om,e,"sync:history:error",this.deps);if(t)try{let r=t.format==="csv"?this.historyStore.exportAsCsv(t.entryIds):this.historyStore.exportAsJson(t.entryIds),n=A(this.deps,e,"sync:history:export:response",{data:r,format:t.format});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} format=${t.format}`)}catch(r){E(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ml,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){E(this.deps,"sync:history:rerun","sync:history:error",e,new Error(`History entry not found: ${t.entryId}`),{code:"NOT_FOUND"});return}await this.syncOps.rerunFromSnapshot(e,r.configSnapshot)}};var Px=1e4;async function MO(s,e){if(s.configId!==void 0&&e.isSaved(s.configId))return{leftAsIs:!0,objects:[]};let t=new Set(s.objects);if(t.size===0)return{leftAsIs:!1,objects:[]};let r=c=>Ft(c).filter(u=>t.has(u.objectApiName)),n=(await e.runs()).find(c=>c.sourceOrgId===s.sourceOrgId&&c.targetOrgId===s.targetOrgId&&r(c).length>0);if(!n)return{leftAsIs:!1,objects:[]};let o=n.created.map(c=>c.objectApiName),i=r(n).sort((c,u)=>o.indexOf(c.objectApiName)-o.indexOf(u.objectApiName)),a,d=[];for(let{objectApiName:c,ids:u}of i){let l=u.slice(0,Px),g;try{g=await e.countInTarget(c,l)+(u.length-l.length)}catch(p){a??=p instanceof Error?p.message:String(p),g=u.length}g>0&&d.push({objectApiName:c,count:g})}return{leftAsIs:!1,run:{runId:n.runId,configName:n.configName,startedAt:n.startedAt,...n.realtime?{realtime:!0}:{}},objects:d,...a!==void 0?{unread:a}:{}}}var Cx=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),$x=6e4,xx=12e4,LO=6e4,Dx=6e4,FO="The run is still writing in another window: remove it once it has ended there.",dc=class{constructor(e,t,r,n=xo){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new It(e.configStore)}deps;history;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);backups;registry;liveTracker;removing=new Set;configs;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;elsewhere(e){return!this.isRunning(e.runId)&&Qn(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||Qn(e,this.self)}setRunCreations(e){this.creations=e}setBackupRecordStore(e){this.backups=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!Cx.has(e.type))return!1;switch(e.type){case"sync:removal:info":return await this.handleInfo(e),!0;case"sync:removal:list":return await this.handleList(e),!0;case"sync:remove":return await this.handleRemove(e),!0;case"sync:remove:sweep":return await this.handleSweepList(e),!0;case"sync:remove:automation":return await this.handleRemovalAutomation(e),!0;case"sync:earlier-copies":return await this.handleEarlierCopies(e),!0;default:return!1}}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Pe(t)}infoOf(e,t=[]){let r=Ft(e),n=Xw(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=Do(e),a=this.keptBack(i),d=El(e),c=Pl(e),u=_s(e),l={runId:e.runId,configId:e.configId,configName:e.configName,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,...e.end?{endedAt:e.end.at}:{},...!e.end&&e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{},...this.elsewhere(e)?{runningElsewhere:!0}:{},...e.realtime?{realtime:!0}:{},created:Fs(e),left:o,...d>0?{overwritten:d}:{},...a.kept.length>0?{putBack:a.kept.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),...a.keptUntil!==void 0?{putBackKeptUntil:a.keptUntil}:{}}:{},...a.notKept>0?{putBackNotKept:a.notKept}:{},...c>0?{deleted:c}:{},...e.unkept?{notKeptEncrypted:e.unkept.flatMap(({objectApiName:m,fields:y})=>y.map(R=>`${m}.${R}`))}:{},...u.length>0?{bringBack:u.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},g=e.removal?.undo?Ft(e,!0):[],p=g.length>0?{...l,createdByObject:g.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:l,f=r.length>0||i.length>0||u.length>0?r:g;if(f.length===0&&i.length===0&&u.length===0)return p;let h=this.refusalOf(e,f,[...i,...u]);return h?{...p,refusal:h}:p}keptBack(e){return gb(e,t=>this.deps.configStore.get(`backup:${t}`),pb(this.deps.services))}removalStepsOf(e,t,r){let n=i=>[...new Set(i.map(({objectApiName:a})=>a))],o=n(Ft(e,t));return{bringBack:n(_s(e)),giveBack:n(this.keptBack(Do(e)).kept),setToDraft:ir(o),delete:td(o,r,{userKept:e.runUserId!==void 0})}}async setsOfConfirmation(e){if(e.runUserId!==void 0||e.created.every(({ids:t})=>t.length===0))return{objects:[]};try{let t=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager);return await Js(Kt(t,"sync:remove:automation"),e.created)}catch{return{objects:[]}}}guardRequestOf(e,t,r){let n=o=>o.reduce((i,a)=>i+a.ids.length,0);return{orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:t.length>0?"delete":"update",objectName:[...new Set([...t,...r].map(o=>o.objectApiName))].join(", "),recordCount:n(t)+n(r),module:"sync"}}refusalOf(e,t,r){if(this.isRunning(e.runId))return{code:"RUNNING",message:"The run is still writing: remove it once it has ended."};if(this.elsewhere(e))return{code:"RUNNING",message:FO};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let n=this.deps.infraServices?.productionGuard;if(!n)return{code:"NO_GUARD",message:Re.message};let o=n.check(this.guardRequestOf(e,t,r));return o.allowed?void 0:{code:"GUARD_BLOCKED",message:o.blockedReason??o.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.stillWriting(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`sync:removal of ${e.runId}`;try{let n=await new ge(Dx).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Kt(o,r);return Za(t,e,Yn(o),()=>i.serverTime())});for(let o of ed(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hm,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Ft(r).length>0||Do(r).length>0)?await this.creations?.list()??[]:[],i=A(this.deps,e,"sync:removal:info:response",{info:r?this.infoOf(r,o):null});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){E(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(mm,e,"sync:remove:error",this.deps);if(t===null)return;let r=t?.realtime===!0;try{let n=new Set(this.history.list().flatMap(d=>d.result.created?.runId?[d.result.created.runId]:[])),o=[];for(let d of await this.creations?.list()??[]){let c=n.has(d.runId)||d.realtime===!0!==r;o.push(c?d:await this.withJobAnswered(d))}let i=o.filter(d=>d.realtime===!0===r&&!n.has(d.runId)&&!this.isRunning(d.runId)&&(Fs(d)>0||El(d)>0||Pl(d)>0||!d.end&&d.inFlight!==void 0)),a=A(this.deps,e,"sync:removal:list:response",{runs:i.map(d=>this.infoOf(d,o))});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} count=${i.length}`)}catch(n){E(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ym,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await MO(t,{runs:async()=>await r?.list()??[],isSaved:i=>this.configs.isSaved(i),countInTarget:async(i,a)=>{let d=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=wt(i),u=0;for(let l of Ns(a.filter(Qr)))u+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${l})`)).totalSize;return u}}),o=A(this.deps,e,"sync:earlier-copies:response",{copies:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){E(this.deps,"sync:earlier-copies","sync:remove:error",e,r)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i=[...new Set([...t.created,...t.overwritten??[]].map(u=>u.objectApiName).filter(u=>!Vw.includes(u)))],a;try{a=await new ge($x).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(u){a={error:I(u)}}let d=Kt(e,r),c=await rd(d,t.created,a,n,t.firstWrittenAt!==void 0?{at:t.firstWrittenAt,...t.lastWriteAt!==void 0?{lastAt:t.lastWriteAt}:{},serverTime:()=>d.serverTime()}:void 0,t.overwritten??[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Wo({...c,ties:{...c.ties,...await od(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return nd(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(bm,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(xx).withTimeout("sync:remove:sweep",async()=>{let i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"sync:remove:sweep");return Ho(nn(i,"sync:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){E(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Rm,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"sync:remove:automation","sync:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=Rs(this.removalStepsOf(n,t.again===!0,await this.setsOfConfirmation(n)),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new ge(LO).withTimeout("sync:remove:automation",()=>a.read(n.targetOrgId,i,{undeletes:!0})),c=A(this.deps,e,"sync:remove:automation:response",{runId:n.runId,automation:d,steps:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){let o=n instanceof Sr;E(this.deps,"sync:remove:automation","sync:remove:automation:error",e,n,{code:o?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r,input:n}=e;return zo({input:async()=>{if(n instanceof Error)throw n;return n},org:nn(t,"sync:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"sync"},onGuardDecision:(o,i)=>{let a=qo(o,"");delete a.forgeId,Q(this.deps,{action:"cleanup_delete",module:"sync",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Go(i)}:{},objects:Bo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>sd(d,o,i,a)).catch(d=>{this.deps.log(`[WARN] sync:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(d)}`)})}})}refuse(e,t,r,n=!1){E(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Q(this.deps,{action:"cleanup_delete",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wm,e,"sync:remove:error",this.deps);if(!t)return;let r=this.creations;if(!r){this.refuse(e,"What Sync runs created is not kept in this window yet.","NOT_INITIALIZED",!0);return}let n;try{n=await this.runOf(t.runId)}catch(a){E(this.deps,"sync:remove","sync:remove:error",e,a,{code:"REMOVE_ERROR",retryable:!0});return}if(!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or ran before runs kept what they created, or the record of it was dropped to make room.","NOT_KEPT");return}if(this.isRunning(n.runId)){this.refuse(e,"The run is still writing: remove it once it has ended.","RUNNING");return}if(this.elsewhere(n)){this.refuse(e,FO,"RUNNING");return}let o=t.again===!0;if(Ft(n,o).length===0&&Do(n).length===0&&_s(n).length===0){let a=n.removal?.undo?.removedAt??n.removal?.restoredAt??n.removal?.undeletedAt;a!==void 0?this.refuse(e,`What this run created was removed already, on ${a}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Ft(r,a),c=[...Do(r),..._s(r)],u=d.reduce((v,b)=>v+b.ids.length,0),l=c.reduce((v,b)=>v+b.ids.length,0),g=r.targetOrgId,p=this.deps.infraServices?.productionGuard;if(!p){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:f,decision:h}=await et(p,this.guardRequestOf(r,d,c));if(h==="refused"||h==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:h}),h==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${f.blockedReason??f.impactSummary}`,xt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",xt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:h,code:bt});let v={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:response",{result:v,operationId:e.id}));return}let m=e.id,y=l>0?`Removing ${u} record(s) and file(s) a Sync run created, and giving ${l} record(s) it wrote over or deleted their values back`:`Removing ${u} record(s) and file(s) a Sync run created`,R=new AbortController,S=()=>{},w=new Promise((v,b)=>{S=C=>C===void 0?v():b(C)});w.catch(()=>{}),Je(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,w,R),this.liveTracker?.register(m,"sync",y,u+l);let O,P;try{let v=await q(g,this.deps.orgRegistry,this.deps.orgManager),b=n.sweep?await this.sweepInputOf(v,r,"sync:remove sweep",R.signal).catch(X=>new Error(I(X))):void 0;P=b?await this.sweepOfRemoval({conn:v,run:r,input:b,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:R.signal,guard:p,operationId:m}):void 0;let C=P;await C?.ask();let k=Kt(v,"sync:remove"),T=await Js(k,r.created),x;if(n.muteAutomation===!0){let X=Rs(this.removalStepsOf(r,a,T),C?.takes??[]),ae=[...new Set(Object.values(X).flat())],me=this.targetAutomation,ce=await new ge(LO).withTimeout("sync:remove:automation",()=>me.read(r.targetOrgId,ae,{undeletes:!0})).catch(be=>({unread:I(be)}));x=await Ot(async()=>_t(v),ce,{...this.muteLeases,writes:Jr(X)})}let J,U=x?.muted,K=async()=>{let X=x?.prepared;!X||R.signal.aborted||(J=await X.acquire(m),U=J.outcome)},{result:re,notes:N,earlierStamped:L,emptied:B}=await Aa({run:r,org:k,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:Kw(r,await t.list().catch(()=>[])),undelete:X=>v.soap.undelete(X),...C?{sweep:X=>C.first(X),afterRemoval:X=>C.afterRemoval(X),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Kr(this.deps,g,"sync:remove"),beforeFirstWrite:K,signal:R.signal,onProgress:(X,ae,me)=>{let ce=Math.min(100,Math.round(X/Math.max(ae,1)*100));Fe(this.deps,m,ce,X,ae,me),R.signal.aborted||this.registry?.updateProgress(m,ce),this.liveTracker?.updateProgress(m,ce,X,ae,me)}}).then(async X=>({...X,emptied:X.result.status==="cancelled"?{}:await T.take(X.duplicateSets)})).finally(async()=>{J&&(U=await J.release())}),te=await P?.settle();for(let X of[...N,...B.note?[B.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${X}`);for(let{runId:X,records:ae}of L??[])this.deps.log(`[INFO] sync:remove ${m}: ${ae} record(s) given back hold the values of the earlier run ${X} again, stamped on it`);let se={...re,objects:B.object?[...re.objects,B.object]:re.objects,status:Co(re.status,te),...te?{sweep:te}:{},...U?{mutedAutomation:U}:{}};Q(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:g,outcome:$o(re),guard:h,objects:Ia(In(se.objects),se.restored??[],se.undeleted??[]),...se.leftBy?{leftBy:se.leftBy}:{},...U?{muted:ut(U)}:{},details:{runId:r.runId}});let H=A(this.deps,e,"sync:remove:response",{result:se,operationId:m});this.deps.broker.postToWebview(H),this.deps.log(`[TX] ${H.type} id=${H.id} status=${se.status}`),se.status==="cancelled"||se.sweep?.status==="cancelled"?(pe(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(pe(this.deps,m,{status:se.status}),se.status==="failure"?(O=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):se.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(v){O=v,await P?.settle().catch(()=>{});let b=Dt(v)?v:void 0;this.recordNotRemoved(e,r,b?"stopped":"failure",{guard:h,...b?{code:b.code}:{}}),E(this.deps,"sync:remove","sync:remove:error",e,v,{code:b?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,I(v))}finally{S(O)}}};var Nx=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,jx=/^[A-Za-z][A-Za-z0-9_]*$/;function cc(s,e,t){if(!Nx.test(t)||!jx.test(e))return{ok:!1,reason:"not-a-record"};let r=Mn(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var Mx=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),_O=6e4,Lx=12e4,Fx=6e4,UO="The seed is still writing: remove it once it has ended.",HO="The seed is still writing in another window: remove it once it has ended there.",uc=class{constructor(e,t,r=()=>!1,n=xo){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new Mr}deps;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;removing=new Set;externalBrowser;elsewhere(e){return!this.isRunning(e.runId)&&Qn(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async handle(e){return Mx.has(e.type)?(e.type==="seed:removal:info"?await this.handleInfo(e):e.type==="seed:removal:list"?await this.handleList(e):e.type==="seed:remove:sweep"?await this.handleSweepList(e):e.type==="seed:open-record"?await this.handleOpenRecord(e):await this.handleRemove(e),!0):!1}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Pe(t)}infoOf(e){let t=Ft(e),r={runId:e.runId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,endedAt:e.end?.at??e.lastWrittenAt??e.startedAt,...e.origin?{origin:e.origin}:{},...e.origin==="clone"?{sourceOrgId:e.sourceOrgId}:{},...e.pipeline?{pipeline:e.pipeline}:{},...e.end?{}:this.isRunning(e.runId)?{running:!0}:this.elsewhere(e)?{runningElsewhere:!0}:{unfinished:!0,...e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{}},created:Fs(e),objects:[...new Set([...e.created.map(({objectApiName:d})=>d),...(e.overwritten??[]).map(({objectApiName:d})=>d)])],left:t.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length})),...e.removal?.undo?{removed:e.removal.undo}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{}},n=e.removal?.undo?Ft(e,!0):[],o=n.length>0?{...r,createdByObject:n.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length}))}:r,i=t.length>0?t:n;if(i.length===0)return o;let a=this.refusalOf(e,i);return a?{...o,refusal:a}:o}async withScenario(e){let t=this.creations;if(!t||e.origin)return e;try{let{nodeScenarioSidecarFiles:r,readScenarioRunSidecar:n}=await import("./chunk-EFHM2U4D.mjs"),o=await n(r(),t.storagePath,e.runId);if(o.kind!=="read")return e;let{packId:i,agent:a}=o.sidecar;return{...e,scenario:{packId:i,...a?{agent:a.agent}:{}}}}catch{return e}}refusalOf(e,t){if(this.isRunning(e.runId))return{code:"RUNNING",message:UO};if(this.elsewhere(e))return{code:"RUNNING",message:HO};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let r=this.deps.infraServices?.productionGuard;if(!r)return{code:"NO_GUARD",message:Re.message};let n=r.check({orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:"delete",objectName:t.map(o=>o.objectApiName).join(", "),recordCount:t.reduce((o,i)=>o+i.ids.length,0),module:"seed"});return n.allowed?void 0:{code:"GUARD_BLOCKED",message:n.blockedReason??n.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.isRunning(e.runId)||this.elsewhere(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`seed:removal of ${e.runId}`;try{let n=await new ge(Fx).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Kt(o,r);return Za(t,e,Yn(o),()=>i.serverTime())});for(let o of ed(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}cleanupLineOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId);return cv(e,"npx sandforge cleanup",t?.alias??"<alias>")}notKeptWords(e){let t="rewind the org to a checkpoint taken before it, or empty its objects (DataOps, Cleanup, Empty objects), which deletes all their records.";return e?`${dv(e,this.cleanupLineOf(e))} Or ${t}`:`Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds. To take its records back, ${t}`}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(vm,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=r?void 0:await this.creations?.dropped(t.runId),o=A(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null,...n?{dropped:n,cleanupLine:this.cleanupLineOf(n)}:{}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){E(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(zm,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{E(this.deps,"seed:open-record","seed:open-record:error",e,new Error(n),{code:o})};try{let n=await this.creations?.get(t.runId);if(!n){r("Nothing of this run is kept any more.","NOT_KEPT");return}let o=t.recordId.slice(0,15),i;for(let{objectApiName:l,ids:g}of n.created){let p=g.find(f=>f.slice(0,15)===o);if(p){i={objectApiName:l,id:p};break}}if(!i){r("This record is not one this run created.","NOT_CREATED");return}let a=this.deps.orgManager.getOrg(n.targetOrgId);if(!a){r("The org this run wrote to is no longer connected.","ORG_NOT_FOUND");return}let d=cc(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let l=d.reason==="not-https"?`its instance URL must use HTTPS, got "${d.protocol}"`:d.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${ye(a)}": ${l}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),u=A(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${c.status}`)}catch(n){E(this.deps,"seed:open-record","seed:open-record:error",e,n)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=[];for(let o of await this.creations?.list()??[])t.push(await this.withJobAnswered(o));let r=[];for(let o of t)r.push(await this.withScenario(this.infoOf(o)));let n=A(this.deps,e,"seed:removal:list:response",{runs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} runs=${t.length}`)}catch(t){E(this.deps,"seed:removal:list","seed:remove:error",e,t)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i;try{i=await new ge(_O).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:I(c)}}let a=Kt(e,r),d=await rd(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Wo({...d,ties:{...d.ties,...await od(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return nd(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(km,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(Lx).withTimeout("seed:remove:sweep",async()=>{let i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"seed:remove:sweep");return Ho(nn(i,"seed:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return zo({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:nn(t,"seed:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"seed"},onGuardDecision:(n,o)=>{let i=qo(n,"");delete i.forgeId,Q(this.deps,{action:"cleanup_delete",module:"seed",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:n.status==="refused"?"stopped":n.status,...o?{guard:o}:{},...n.status==="refused"?{code:Go(o)}:{},objects:Bo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>sd(a,n,o,i)).catch(a=>{this.deps.log(`[WARN] seed:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(a)}`)})}})}refuse(e,t,r,n=!1){E(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Q(this.deps,{action:"cleanup_delete",module:"seed",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Sm,e,"seed:remove:error",this.deps);if(!t)return;let r=this.creations,n=await this.runOf(t.runId);if(!r||!n){this.refuse(e,this.notKeptWords(await r?.dropped(t.runId)),"NOT_KEPT");return}let o=t.again===!0;if(Ft(n,o).length===0){n.removal?.undo?this.refuse(e,`What this run created was removed already, on ${n.removal.undo.removedAt}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(this.isRunning(n.runId)){this.refuse(e,UO,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,HO,"RUNNING");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Ft(r,a),c=d.reduce((O,P)=>O+P.ids.length,0),u=r.targetOrgId,l=this.deps.infraServices?.productionGuard;if(!l){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:g,decision:p}=await et(l,{orgId:u,orgTier:this.tierOf(u),operation:"delete",objectName:d.map(O=>O.objectApiName).join(", "),recordCount:c,module:"seed"});if(p==="refused"||p==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:p}),p==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,xt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",xt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:p,code:bt});let O={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:response",{result:O,operationId:e.id}));return}let f=e.id,h=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},R=new Promise((O,P)=>{y=v=>v===void 0?O():P(v)});R.catch(()=>{}),Je(this.deps,f,"seed",h),this.registry?.register(f,"seed",h,R,m),this.liveTracker?.register(f,"seed",h,c);let S,w;try{let O=await q(u,this.deps.orgRegistry,this.deps.orgManager);w=n.sweep?await this.sweepOfRemoval({conn:O,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:l,operationId:f}):void 0;let P=w;await P?.ask();let v=Kt(O,"seed:remove"),b=await Js(v,r.created),C;if(n.muteAutomation===!0){let B=[...new Set(d.map(ae=>ae.objectApiName))],te=Rs({setToDraft:ir(B),delete:td(B,b,{userKept:r.runUserId!==void 0})},P?.takes??[]),se=te.delete??[],H=this.targetAutomation,X=await new ge(_O).withTimeout("seed:remove automation",()=>H.read(r.targetOrgId,se)).catch(ae=>({unread:I(ae)}));C=await Ot(async()=>_t(O),X,{...this.muteLeases,writes:Jr(te)})}let k,T=C?.muted,x=async()=>{let B=C?.prepared;!B||m.signal.aborted||(k=await B.acquire(f),T=k.outcome)},{result:J,notes:U,emptied:K}=await Aa({run:r,org:v,includeChanged:i,...a?{again:a}:{},store:t,...P?{sweep:B=>P.first(B),afterRemoval:B=>P.afterRemoval(B),automationMade:P.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Kr(this.deps,u,"seed:remove"),beforeFirstWrite:x,signal:m.signal,onProgress:(B,te,se)=>{let H=Math.min(100,Math.round(B/Math.max(te,1)*100));Fe(this.deps,f,H,B,te,se),m.signal.aborted||this.registry?.updateProgress(f,H),this.liveTracker?.updateProgress(f,H,B,te,se)}}).then(async B=>({...B,emptied:B.result.status==="cancelled"?{}:await b.take(B.duplicateSets)})).finally(async()=>{k&&(T=await k.release())}),re=await w?.settle();for(let B of[...U,...K.note?[K.note]:[]])this.deps.log(`[WARN] seed:remove ${f}: ${B}`);let N={runId:J.runId,status:Co(J.status,re),includeChanged:J.includeChanged,objects:K.object?[...J.objects,K.object]:J.objects,finishedAt:J.finishedAt,...J.leftBy?{leftBy:J.leftBy}:{},...re?{sweep:re}:{},...T?{mutedAutomation:T}:{}};Q(this.deps,{action:"cleanup_delete",module:"seed",operationId:f,orgId:u,outcome:$o(J),guard:p,objects:In(N.objects),...N.leftBy?{leftBy:N.leftBy}:{},...T?{muted:ut(T)}:{},details:{runId:r.runId}});let L=A(this.deps,e,"seed:remove:response",{result:N,operationId:f});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} status=${N.status}`),N.status==="cancelled"||N.sweep?.status==="cancelled"?(pe(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f)):(pe(this.deps,f,{status:N.status}),N.status==="failure"?(S=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(f,"Nothing this run created could be removed.")):N.status==="partial"?this.liveTracker?.partial(f):this.liveTracker?.complete(f))}catch(O){S=O,await w?.settle().catch(()=>{});let P=Dt(O)?O:void 0;this.recordNotRemoved(e,r,P?"stopped":"failure",{guard:p,...P?{code:P.code}:{}}),E(this.deps,"seed:remove","seed:remove:error",e,O,{code:P?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,f,{status:"failure"}),this.liveTracker?.fail(f,I(O))}finally{y(S)}}};var lc="sync:history:all",BO="syncHistory";var pc=class{constructor(e){this.configStore=e}configStore;save(e){let t=this.loadAll(),r=t.findIndex(o=>o.id===e.id);r>=0?t[r]=e:t.push(e);let n=t.length>500?t.sort((o,i)=>o.startTime.localeCompare(i.startTime)).slice(t.length-500):t;this.configStore.set(lc,n,BO)}load(e){return this.loadAll().find(t=>t.id===e)}list(){return this.loadAll().sort((e,t)=>t.startTime.localeCompare(e.startTime))}delete(e){let t=this.loadAll(),r=t.filter(n=>n.id!==e);return r.length===t.length?!1:(this.configStore.set(lc,r,BO),!0)}exportAsJson(e){let t=this.getFilteredEntries(e);return JSON.stringify(t,null,2)}exportAsCsv(e){let t=this.getFilteredEntries(e),r="id,configName,status,totalProcessed,totalSuccess,totalFailed,totalSkipped,startTime,endTime,duration,triggeredBy",n=t.map(o=>{let i=this.csvEscape(o.configSnapshot.name);return[o.id,i,o.result.status,o.result.totalProcessed,o.result.totalSuccess,o.result.totalFailed,o.result.totalSkipped,o.startTime,o.endTime,o.result.duration,o.triggeredBy].join(",")});return[r,...n].join(`
|
|
17
|
-
`)}clear(){this.configStore.delete(lc)}loadAll(){let e=this.configStore.get(lc);return Array.isArray(e)?e:[]}getFilteredEntries(e){let t=this.list();if(!e||e.length===0)return t;let r=new Set(e);return t.filter(n=>r.has(n.id))}csvEscape(e){return e.includes(",")?`"${e}"`:e}};var _x=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function Ux(s){if(s.errors.length<=50)return s;let e=s.errors.slice(0,50),t=0;for(let r of s.errors.slice(50))_x.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var gc=class{constructor(e,t=()=>crypto.randomUUID()){this.historyStore=e;this.generateId=t}historyStore;generateId;logExecution(e,t,r,n){let i=new Date(t.timestamp).getTime()-t.duration,a={id:this.generateId(),configSnapshot:structuredClone(e),result:{...t,objectResults:t.objectResults.map(Ux)},startTime:new Date(i).toISOString(),endTime:t.timestamp,triggeredBy:r,...n?{scheduleId:n}:{}};return this.historyStore.save(a),a}getHistory(){return this.historyStore.list()}getEntry(e){return this.historyStore.load(e)}exportHistory(e,t){return e==="csv"?this.historyStore.exportAsCsv(t):this.historyStore.exportAsJson(t)}};var Hx={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},Bx=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),qx=5;function Wx(s){let e=new Map;for(let t of s.components){let r=e.get(t.componentType)??{objectApiName:t.componentType,created:0,updated:0,deleted:0,failed:0};if(t.outcome==="created")r.created+=1;else if(t.outcome==="changed")r.updated+=1;else if(t.outcome==="failed")r.failed+=1;else continue;e.set(t.componentType,r)}return[...e.values()]}var fc=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!Bx.has(e.type))return!1;switch(e.type){case"compare:execute":return await this.handleCompareStart(e),!0;case"compare:permissions":return await this.handlePermissions(e),!0;case"compare:snapshots":return await this.handleSnapshots(e),!0;case"compare:drift":return await this.handleDrift(e),!0;case"compare:validate-deployment":return await this.handleValidateDeployment(e),!0;case"compare:deploy":return await this.handleDeploy(e),!0;default:return!1}}async handleValidateDeployment(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ty,e,"compare:error",this.deps);if(!t)return;let r=t.testLevel==="RunSpecifiedTests"?t.runTests??[]:[];try{if(!await this.passGuard(e,t.targetOrgId,t.components,!0))return;let n=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-HOEE3PE5.mjs"),a=this.options.waiting??i.DEFAULT_WAITING,d=this.progressTo(e),c=await i.retrieveComponents(i.metadataApiOf(n),n.version,t.components,{waiting:a,onProgress:d});if(c.managed.length>0){E(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(g=>`${g.componentType} ${g.fullName}`).join(", ")+" in the source, and it owns them: untick them and validate again. Nothing was sent to the target."),{code:"MANAGED",extraPayload:{managed:c.managed.map(g=>({componentType:g.componentType,fullName:g.fullName}))}});return}let u=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,l=i.deploymentReport(u,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});l.success&&l.deployId&&this.keepValidation(l.deployId,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,zipFile:c.zipFile,components:c.retrieved,testLevel:t.testLevel,runTests:r}),this.post(A(this.deps,e,"compare:validate-deployment:response",{report:l}),l)}catch(n){E(this.deps,"compare:validate-deployment","compare:error",e,n,{code:await this.deployErrorCode(n)})}}async handleDeploy(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ry,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){E(this.deps,"compare:deploy","compare:error",e,new Error(`No successful validation ${t.validationId} is waiting in this window: validate the deployment, then deploy it. Nothing was deployed.`),{code:"NOT_VALIDATED"});return}if(r.targetOrgId!==t.targetOrgId){E(this.deps,"compare:deploy","compare:error",e,new Error(`Validation ${t.validationId} was run in another org than the one named. Nothing was deployed.`),{code:"TARGET_MISMATCH"});return}let n;try{if(n=await this.passGuard(e,r.targetOrgId,r.components,!1),!n)return;this.validations.delete(t.validationId);let o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-HOEE3PE5.mjs"),a=await i.deployPackage(i.metadataApiOf(o),r.zipFile,i.deployOptions(!1,r.testLevel,r.runTests),{waiting:this.options.waiting??i.DEFAULT_WAITING,onProgress:this.progressTo(e)}),d=i.deploymentReport(a,{missing:[],problems:[]},{sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,checkOnly:!1,testLevel:r.testLevel,runTests:r.runTests});Q(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:d.success?"success":"failure",guard:n,objects:Wx(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(A(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){n&&Q(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:"failure",guard:n}),E(this.deps,"compare:deploy","compare:error",e,o,{code:await this.deployErrorCode(o)})}}async passGuard(e,t,r,n){let o=this.deps.infraServices?.productionGuard??new ab,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Pe(i),operation:"deploy",objectName:[...new Set(r.map(u=>u.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let u=o.check(a);if(u.allowed)return"allowed";this.refuse(e,u.blockedReason??u.impactSummary);return}let{check:d,decision:c}=await et(o,a);if((c==="refused"||c==="declined")&&Q(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:t,outcome:"stopped",guard:c}),c==="refused"){this.refuse(e,d.blockedReason??d.impactSummary);return}if(c==="declined"){E(this.deps,e.type,"compare:error",e,new Error("Operation cancelled by user (deployment confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}return c}refuse(e,t){E(this.deps,e.type,"compare:error",e,new Error(`Operation blocked by Production Guard: ${t}`),{code:"GUARD_BLOCKED"})}keepValidation(e,t){for(this.validations.set(e,t);this.validations.size>qx;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>Fe(this.deps,e.id,t.total>0?Math.round(t.done/t.total*100):0,t.done,t.total,t.step,t.deployId!==void 0?{deployId:t.deployId}:void 0)}post(e,t){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id} deploy=${t.deployId??"-"} status=${t.status}`)}async deployErrorCode(e){let{DeploymentStillRunning:t}=await import("./chunk-HOEE3PE5.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ds,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await this.compareOrgs(r),o=A(this.deps,e,"compare:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){E(this.deps,"compare:execute","compare:error",e,n)}}async compareOrgs(e,t){t?.throwIfAborted();let r=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);t?.throwIfAborted();let n=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{DiffEngine:o}=await import("./chunk-7F54PZUS.mjs"),{MetadataCompare:i}=await import("./chunk-F2424IKX.mjs"),{createContentReader:a}=await import("./chunk-HXS7ORUF.mjs"),d=new o,c=async(f,h)=>{let m=f===e.sourceOrgId?r:n,y=new Map,R=async O=>{t?.throwIfAborted();let P=await m.metadata.list(O);return xe(m.limitInfo,`compare:metadata list ${String(h)}`),Array.isArray(P)?P:[]},S=Hx[h],w=S?(await R([{type:S}])).map(O=>({type:h,folder:O.fullName})):[{type:h}];for(let O=0;O<w.length;O+=3)for(let P of await R(w.slice(O,O+3)))y.set(P.fullName,JSON.stringify(P));return y},u=a(f=>f===e.sourceOrgId?r:n,t),l=new i(c,d,u);if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let g=this.deps.services.compareOrchestrator({metadataCompare:l,diffEngine:d,services:this.deps.services}),p={id:crypto.randomUUID(),name:"compare-from-ui",sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:"metadata",componentTypes:e.types,includeManaged:e.includeManaged??!0,createdAt:new Date().toISOString()};return g.execute(p,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ua,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(h,m)=>{let y=await Lt(h,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");xe(h.limitInfo,`compare:permissions ${m}`);let R=await Lt(h,"SELECT Id, Name FROM Profile");return xe(h.limitInfo,`compare:permissions profiles ${m}`),{permSets:y,profiles:R}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.permSets.map(h=>h.Name)),u=new Set(d.permSets.map(h=>h.Name)),l=new Set(a.profiles.map(h=>h.Name)),g=new Set(d.profiles.map(h=>h.Name)),p={permissionSets:{sourceOnly:a.permSets.filter(h=>!u.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),targetOnly:d.permSets.filter(h=>!c.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),shared:a.permSets.filter(h=>u.has(h.Name)).map(h=>({name:h.Name,label:h.Label}))},profiles:{sourceOnly:a.profiles.filter(h=>!g.has(h.Name)).map(h=>({name:h.Name})),targetOnly:d.profiles.filter(h=>!l.has(h.Name)).map(h=>({name:h.Name})),shared:a.profiles.filter(h=>g.has(h.Name)).map(h=>({name:h.Name}))}},f=A(this.deps,e,"compare:permissions:response",{permissions:p});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id}`)}catch(n){E(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ua,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(p,f)=>{let h=await p.describeGlobal();xe(p.limitInfo,`compare:snapshots describeGlobal ${f}`);let m=h.sobjects.map(y=>({name:y.name,custom:y.custom,label:y.label,queryable:y.queryable}));return{totalObjects:m.length,customObjects:m.filter(y=>y.custom).length,standardObjects:m.filter(y=>!y.custom).length,queryableObjects:m.filter(y=>y.queryable).length,objects:m}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.objects.map(p=>p.name)),u=new Set(d.objects.map(p=>p.name)),l={source:{orgId:r.sourceOrgId,totalObjects:a.totalObjects,customObjects:a.customObjects,standardObjects:a.standardObjects,queryableObjects:a.queryableObjects},target:{orgId:r.targetOrgId,totalObjects:d.totalObjects,customObjects:d.customObjects,standardObjects:d.standardObjects,queryableObjects:d.queryableObjects},diff:{sourceOnly:a.objects.filter(p=>!u.has(p.name)).map(p=>p.name),targetOnly:d.objects.filter(p=>!c.has(p.name)).map(p=>p.name),sharedCount:a.objects.filter(p=>u.has(p.name)).length},capturedAt:new Date().toISOString()},g=A(this.deps,e,"compare:snapshots:response",{snapshot:l});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){E(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ua,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(p,f)=>{let h={},m=await Lt(p,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if(xe(p.limitInfo,`compare:drift companyInfo ${f}`),m[0])for(let[y,R]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(h[`Organization.${y}`]=String(R));return h},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set([...Object.keys(a),...Object.keys(d)]),u=[];for(let p of c){let f=a[p],h=d[p];f===void 0?u.push({setting:p,sourceValue:"",targetValue:h??"",status:"missing_source"}):h===void 0?u.push({setting:p,sourceValue:f,targetValue:"",status:"missing_target"}):f!==h?u.push({setting:p,sourceValue:f,targetValue:h,status:"drift"}):u.push({setting:p,sourceValue:f,targetValue:h,status:"match"})}let l={items:u,totalChecked:u.length,driftCount:u.filter(p=>p.status==="drift").length,matchCount:u.filter(p=>p.status==="match").length,missingCount:u.filter(p=>p.status==="missing_source"||p.status==="missing_target").length,detectedAt:new Date().toISOString()},g=A(this.deps,e,"compare:drift:response",{drift:l});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){E(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as iD}from"node:crypto";function qO(s,e,t){return s==="delete"?{...mt(e),deleted:t.done,failed:t.failed}:{...mt(e),updated:t.done,failed:t.failed}}async function hc(s,e,t){let r=crypto.randomUUID(),n=s.infraServices?.productionGuard;if(!n)return Q(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",code:Re.code}),{ran:!1,operationId:r,code:Re.code,message:Re.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await et(n,{orgId:e.orgId,orgTier:Pe(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return Q(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",guard:a}),{ran:!1,operationId:r,guard:a,message:a==="refused"?`Operation blocked by Production Guard: ${i.blockedReason??i.impactSummary}`:"Operation cancelled by user (confirmation declined)."};Je(s,r,"dataops",e.description);let c=new AbortController,u=()=>{},l=new Promise((h,m)=>{u=y=>y===void 0?h():m(y)});l.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,l,c);let g=ar(t,r,"dataops",e.description,e.recordCount),p=[],f=0;try{let h=await e.run((R,S)=>{p.push({objectApiName:R,counts:S}),f+=S.done+S.failed;let w=Math.min(100,Math.round(f/Math.max(e.recordCount,1)*100)),O=`${R}: ${S.done} done, ${S.failed} refused`;Fe(s,r,w,f,e.recordCount,O),g.progress(w,f,e.recordCount,O)},c.signal);await e.beforeEnd?.();let m=Sl(h),y=c.signal.aborted;if(Q(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,...y?m.done+m.failed>0?{outcome:"cancelled"}:{outcome:"stopped",code:rt}:{outcome:m.status},...d?{guard:d}:{},objects:h.map(R=>qO(e.operation,R.objectApiName,R.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),pe(s,r,{aborted:!0,done:m.done,failed:m.failed}),g.cancel(),u(),{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{},cancelled:!0,error:`Cancelled: ${m.done} record(s) ${e.operation==="delete"?"deleted":"overwritten"} before the cancel; the rest were left as they are.`};if(pe(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let R=`The org refused the ${m.failed} record(s)`;g.fail(R),u(new Error(R))}else m.status==="partial"?g.partial():g.complete(),u();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(h){await e.beforeEnd?.();let m=I(h);return Q(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:p.map(y=>qO(e.operation,y.objectApiName,y.counts))}),je(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),g.fail(m),u(h),{ran:!0,operationId:r,outcome:{...Sl(p),status:"failure"},...d?{guard:d}:{},error:m}}}var WO=100;async function Gx(s,e,t){let r=new Map,n=[],o=t.map(a=>ze(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=WO)i.push(o.slice(a,a+WO));i.length===0&&i.push([]);for(let a of i){let d=await s.query(`SELECT ${["Id",...a].join(", ")} FROM ${e} ORDER BY Id DESC LIMIT ${200}`);for(let c of d.records){if(typeof c!="object"||c===null)continue;let u={...c};delete u.attributes;let l=typeof u.Id=="string"?u.Id:void 0;if(!l)continue;let g=r.get(l);g?Object.assign(g,u):(r.set(l,u),n.push(l))}}return n.map(a=>r.get(a))}async function Jx(s,e,t){let r,n;try{if(r=sr.parse(await s.describe(ze(t))),n=ze(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(f){return{status:"failed",objectApiName:t,message:I(f)}}let o=Us(e,n,r.fields),i=new Set(o.map(f=>f.field.name)),a=r.fields.filter(f=>Zw(f)&&eb(f)||i.has(f.name)),d=[],c;try{d=await Gx(s,n,a)}catch(f){c=I(f)}let u=c?o:Us(e,n,r.fields,d),l=e.getPatterns(),g=u.map(f=>{let h=tb(f.field),m=d.map(R=>R[f.field.name]),y=f.detectedBy==="content"?l[f.pattern]:void 0;return{fieldApiName:f.field.name,label:f.field.label,classification:f.classification,detectedBy:f.detectedBy,pattern:f.pattern,filled:m.filter(Ea).length,...y?{matched:m.filter(R=>typeof R=="string"&&y.test(R)).length}:{},...h?{searchedFor:h}:{}}}).sort((f,h)=>h.filled-f.filled||f.label.localeCompare(h.label)),p=rb(r);return{status:"scanned",objectApiName:t,label:r.label,sampled:d.length,fields:g,nameField:p?{fieldApiName:p.name,label:p.label}:null,...c!==void 0?{sampleError:c}:{}}}async function zO(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await Jx(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function Vx(s,e,t,r){let n=t.fields.filter(Qw).map(d=>d.name),o=await kn(s,t.name,n,r),i=Us(e,t.name,t.fields,o),a=ob(t,i);return{objectApiName:t.name,records:o,erased:a.fields,plan:{objectApiName:t.name,label:t.label,records:o.length,fields:a.fields.map(d=>({fieldApiName:d.field.name,label:d.field.label,method:d.method})),kept:a.kept.map(d=>({fieldApiName:d.name,label:d.label}))}}}async function GO(s,e,t,r){let n=[],o;for(let i of r){let a=sr.parse(await s.describe(ze(i.objectApiName))),d=u=>({objectApiName:a.name,plan:{objectApiName:a.name,label:a.label,records:0,refused:u}});if(t==="anonymize"){if(a.updateable!==!0){n.push(d(`The connected user may not edit ${a.label} records: erase them with Delete instead, or have an admin grant Edit on ${a.label} in a permission set.`));continue}n.push(await Vx(s,e,a,i.ids));continue}if(a.deletable!==!0){n.push(d(`The connected user may not delete ${a.label} records: erase them with Anonymize in place instead, or have an admin grant Delete on ${a.label} in a permission set.`));continue}o??=await fa(s);let c=await ha(s,a,i.ids,o);n.push({objectApiName:a.name,ids:[...i.ids],plan:{objectApiName:a.name,label:a.label,records:i.ids.length,related:c.related,uncounted:c.uncounted}})}return n}function mc(s){let e=new Map;for(let t of s)t.refused||t.records===0||e.set(t.objectApiName,(e.get(t.objectApiName)??0)+t.records);return[...e].map(([t,r])=>({objectApiName:t,records:r}))}function Kx(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function JO(s,e,t,r,n){let o=[];for(let i of t){if(n?.aborted)break;if(i.plan.refused)continue;let a;if(i.ids)a=await ma(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let u=e.anonymize(c,Kx(i.objectApiName,d)),l=[],g=0;c.forEach((p,f)=>{let h={Id:p.Id};for(let m of d)Ea(p[m.field.name])&&(h[m.field.name]=u[f][m.field.name]??null);Object.keys(h).length>1?l.push(h):g++}),a=await ww(s,i.objectApiName,l,n),a.done+=g}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var VO="dataops:subject-requests",Xx="audit",Yx=V({objectApiName:j(),done:Te().int().nonnegative(),failed:Te().int().nonnegative()}),Qx=Mi("kind",[V({kind:yt("searched"),at:j(),searchedBy:ve(We(["email","phone","name"])),objects:ve(V({objectApiName:j(),found:Te().int().nonnegative(),truncated:Ke()}))}),V({kind:yt("exported"),at:j(),records:Te().int().nonnegative()}),V({kind:yt("erased"),at:j(),mode:We(["anonymize","delete"]),outcome:We(["success","partial","failure","stopped"]),operationId:j(),objects:ve(Yx)})]),Zx=V({requestId:j().min(1),orgId:j().min(1),openedAt:j(),events:ve(Qx)}),yc=class{constructor(e,t=500){this.configStore=e;this.limit=t}configStore;limit;has(e,t){return this.read().some(r=>r.requestId===e&&r.orgId===t)}record(e,t,r){let n=this.read(),o=n.find(i=>i.requestId===e&&i.orgId===t);o||(o={requestId:e,orgId:t,openedAt:r.at,events:[]},n.push(o)),o.events.push(r),this.write(n)}list(){return this.read().reverse()}read(){let e=this.configStore.get(VO);return Array.isArray(e)?e.flatMap(t=>{let r=Zx.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(VO,e.slice(-this.limit),Xx)}};function tD(s){return Yu(s).slice(-8)}function rD(s){return`%${s.split("").join("%")}%`}function KO(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function nD(s,e,t){let r=ze(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${rr(n)}'`,matches:o=>KO(o,n)}}if(e==="phone"&&t.phone){let n=tD(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${rD(n)}'`,matches:o=>typeof o=="string"&&Yu(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${rr(n)}'`,matches:o=>KO(o,n)}}}async function oD(s,e,t){try{let r=sr.parse(await s.describe(ze(e))),n=ze(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=nb(r).flatMap(({field:p,kind:f})=>{let h=nD(p,f,t.identifiers);return h?[h]:[]});if(o.length===0)return{status:"skipped",objectApiName:e,label:r.label};let i=o.map(p=>({fieldApiName:p.field.name,label:p.field.label,kind:p.kind})),a=o.map(p=>p.soql).join(" OR "),d=(await s.query(`SELECT COUNT() FROM ${n} WHERE ${a}`)).totalSize;if(d===0)return{status:"searched",objectApiName:e,label:r.label,counted:d,records:[],truncated:!1,searched:i};let c=r.fields.find(p=>p.nameField===!0),u=[...new Set(["Id",...c?[c.name]:[],...o.map(p=>p.field.name)])].map(ze),l=await s.query(`SELECT ${u.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),g=[];for(let p of l.records){if(typeof p!="object"||p===null)continue;let f=p;if(!Qr(f.Id))continue;let h=[...new Set(o.filter(y=>y.matches(f[y.field.name])).map(y=>y.field.name))];if(h.length===0)continue;let m=c?f[c.name]:null;g.push({id:f.Id,name:typeof m=="string"?m:null,matchedBy:h})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:g,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:sD(I(r),t.identifiers)}}}function sD(s,e){let t=s;for(let r of[e.email,e.name,e.phone]){let n=r?.trim();n&&(t=t.replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),"\u2026"))}return t}async function XO(s,e){let t=[];for(let r of e.objects)t.push(await oD(s,r,e));return t}var aD=6e4,dD=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),cD=20;function uD(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function lD(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function pD(s,e){return{...s,update:async(t,r)=>{e.beforeWrite(t);try{let n=await s.update(t,r),o=Array.isArray(n)?n:[n];return e.wrote(t,o.flatMap((i,a)=>lD(i)?[r[a]?.Id]:[])),n}catch(n){throw cb(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function gD(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var wc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;found=new Map;maskingKey=iD(32).toString("hex");saveDialog;writing=new ub;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}duplicatesSettleMs=fb;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}isWritingTo(e){return this.writing.has(e)}get requestLog(){return new yc(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new Pa}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return ga(r,t)}async handle(e){if(!dD.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:pii-inventory":return await this.handleInventory(e),!0;case"dataops:dsr:search":return await this.handleSearch(e),!0;case"dataops:dsr:export":return await this.handleExport(e),!0;case"dataops:dsr:erase":return await this.writing.during(uD(e)?void 0:lb(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=$(Bm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await zO(r,this.detector,t),o=A(this.deps,e,"dataops:pii-inventory:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){E(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=$(qm,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,objects:n}=t,o={...t.email!==void 0?{email:t.email}:{},...t.name!==void 0?{name:t.name}:{},...t.phone!==void 0?{phone:t.phone}:{}};try{let i=await this.session(r,"dataops:dsr:search"),a=await XO(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),u=new Date().toISOString(),l={orgId:r,objects:new Map};for(let h of a)h.status==="searched"&&l.objects.set(h.objectApiName,new Set(h.records.map(m=>m.id)));this.hold(c,l),d.record(c,r,{kind:"searched",at:u,searchedBy:gD(o),objects:a.flatMap(h=>h.status==="searched"?[{objectApiName:h.objectApiName,found:h.records.length,truncated:h.truncated}]:[])});let g={requestId:c,orgId:r,searchedAt:u,limit:200,objects:a},p=A(this.deps,e,"dataops:dsr:search:response",{...g});this.deps.broker.postToWebview(p);let f=[...l.objects.values()].reduce((h,m)=>h+m.size,0);this.deps.log(`[TX] ${p.type} id=${p.id} records=${f}`)}catch(i){E(this.deps,"dataops:dsr:search","dataops:error",e,i)}}hold(e,t){for(this.found.delete(e),this.found.set(e,t);this.found.size>cD;){let r=this.found.keys().next().value;if(r===void 0)break;this.found.delete(r)}}heldFor(e,t){let r=this.found.get(e);if(!r||r.orgId!==t)throw new Error("This request has found nothing in this window. Search again: an export or an erasure only acts on the records a search found.");return r}async handleExport(e){let t=$(Wm,e,"dataops:error",this.deps);if(t)try{let r=this.heldFor(t.requestId,t.orgId),n=await this.session(t.orgId,"dataops:dsr:export"),o={},i=0;for(let[l,g]of r.objects){if(g.size===0)continue;let p=sr.parse(await n.describe(l)),f=await kn(n,p.name,p.fields.map(h=>h.name),[...g]);o[l]=f,i+=f.length}let a=new Date().toISOString(),d={sandforgeSubjectRequestVersion:1,requestId:t.requestId,orgId:t.orgId,exportedAt:a,objects:o},c=await this.saveDialog.save(`sandforge-subject-request-${t.requestId.slice(0,8)}.json`,JSON.stringify(d,null,2),["json"]);c.status==="saved"&&this.requestLog.record(t.requestId,t.orgId,{kind:"exported",at:a,records:i});let u=A(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} ${c.status} records=${i}`)}catch(r){E(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=$(Gm,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,requestId:n,mode:o,dryRun:i}=t;try{let a=this.heldFor(n,r),d=t.records.reduce((L,B)=>{let te=a.objects.get(B.objectApiName);return L+B.ids.filter(se=>!te?.has(se)).length},0);if(d>0)throw new Error(`${d} of the records to erase were not found by this request. Search again, and erase from what the search lists.`);let c=await this.session(r,"dataops:dsr:erase"),u=await GO(c,this.detector,o,t.records),l=u.map(L=>L.plan),g=mc(l);if(i){let L=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:l,written:g});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} plan objects=${l.length}`);return}let p=l.filter(L=>!L.refused&&L.records>0),f=p.reduce((L,B)=>L+B.records,0);if(f===0){let L=l.flatMap(B=>B.refused?[B.refused]:[]);throw new Error(L.length>0?`Nothing can be erased. ${L.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let h=ye(this.deps.orgManager.getOrg(r),r),m=await q(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,R=await en({act:o==="delete"?"cleanup":"masking",target:h,objects:g,org:No(m,L=>new ge(aD).withTimeout("dataops automation",()=>y.read(r,L)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),S=Tn(R.answer),w=S?{refused:S}:await ro(R,e.id,t.acceptEmails===!0,"erasure");if("refused"in w){let L=crypto.randomUUID();Q(this.deps,{action:"subject_erase",module:"dataops",operationId:L,orgId:r,outcome:"stopped",code:w.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:L,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(w.refused.message),{code:w.refused.code,...S?xa(S):{}});return}let O=w.held,P={},v=async()=>{if(!(!O||P.back)){P.back=await O.release();for(let L of Xt(P.back,h))this.deps.log(`[INFO] ${L}`)}},b=o==="anonymize"?mb({query:async L=>m.query(L),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},hb(R.answer.automation,g.map(L=>L.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,C={},k=async()=>{await v(),!C.read&&(C.read=!0,C.duplicates=await b?.read())},T=()=>wb(C.duplicates,h,"erasure"),x=()=>O?{mutedAutomation:P.back??O.outcome}:{},J=new Ub(void 0,this.maskingKey),U=await hc(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:p.map(L=>L.objectApiName),recordCount:f,action:"subject_erase",description:`Erase ${f} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(L,B)=>JO(b?pD(c,b):c,J,u,L,B),beforeEnd:k},this.liveTracker).finally(v),K=new Date().toISOString();if(!U.ran){this.requestLog.record(n,r,{kind:"erased",at:K,mode:o,outcome:"stopped",operationId:U.operationId,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(U.message),{...U.code?{code:U.code}:{},extraPayload:x()});return}this.requestLog.record(n,r,{kind:"erased",at:K,mode:o,outcome:U.outcome.status,operationId:U.operationId,objects:U.outcome.objects});let{duplicates:re}=C;if(U.error!==void 0){let L=T();E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(L?`${U.error} ${L}`:U.error),{...U.cancelled?{code:rt}:{},extraPayload:{...x(),...re?{duplicates:re}:{}}});return}let N=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:l,outcome:U.outcome,...x(),...re?{duplicates:re}:{}});this.deps.broker.postToWebview(N),this.deps.log(`[TX] ${N.type} id=${N.id} ${U.outcome.status} done=${U.outcome.done} failed=${U.outcome.failed}`),yb(re)&&Ie(this.deps,"warning","Erase",T())}catch(a){E(this.deps,"dataops:dsr:erase","dataops:error",e,a)}}handleLog(e){try{let t=this.requestLog.list(),r=A(this.deps,e,"dataops:dsr:log:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} entries=${t.length}`)}catch(t){E(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var fD=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function tI(s){return s.type==="reference"&&kl(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!fD.has(s.referenceTo[0])}function rI(s,e){return e>0&&s/e>=.9}async function hD(s,e,t){let r,n,o;try{if(r=sr.parse(await s.describe(ze(e.objectApiName))),n=ze(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`);o=(await s.query(`SELECT COUNT() FROM ${n}`)).totalSize}catch(p){return{status:"failed",objectApiName:e.objectApiName,message:I(p)}}let i=r.fields.filter(Ol).sort((p,f)=>p.label.localeCompare(f.label)),a=r.fields.filter(tI),d=[...a,...r.fields.filter(p=>kl(p)&&!a.includes(p))],[c,u,l]=await Promise.all([Sw(s,n,d,o),kw(s,n,i,e.duplicateKey,o),Iw(s,n,r.fields,t,o)]),g=c.fields.filter(p=>a.some(f=>f.name===p.fieldApiName)&&rI(p.filled,o)&&p.filled<o).map(p=>{let f=a.find(h=>h.name===p.fieldApiName);return{fieldApiName:p.fieldApiName,label:p.label,referenceTo:f?.referenceTo?.[0]??"",filled:p.filled,empty:o-p.filled}}).sort((p,f)=>f.empty-p.empty||p.label.localeCompare(f.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,fields:c.fields,unmeasured:c.unmeasured,stale:l.stale,orphans:g,duplicates:u.duplicates,keyFields:i.map(p=>({fieldApiName:p.name,label:p.label})),errors:[...c.errors,...u.errors,...l.errors],deletable:r.deletable===!0}}async function nI(s,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let r=t().toISOString(),n=[];for(let o of e.objects)n.push(await hD(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:bw,duplicateSample:Rw,singleFieldQueries:vw},objects:n}}function mD(s){let e=Date.parse(s.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isNaN(e)?void 0:new Date(e).toISOString().replace(/\.\d{3}Z$/,"Z")}function ig(s,e,t,r){let n=(s?.skip??0)+e;return e>0&&n<t?{skip:n,...r}:void 0}function QO(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return Qr(t)?[t]:[]})}function yD(s,e){switch(s){case"int":case"long":case"double":case"currency":case"percent":return typeof e=="number"&&Number.isFinite(e)?String(e):void 0;case"boolean":return typeof e=="boolean"?String(e):void 0;case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:void 0;case"datetime":case"time":return;default:return typeof e=="string"?`'${rr(e)}'`:void 0}}function wD(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var ZO=100,bD=2e3;async function RD(s,e,t,r){let n=ze(e.name),o=ze(t.name),i=await Ow(s,n,t.name),a=i.rows.reduce((l,g)=>l+g.count-1,0),d=i.rows.map(l=>yD(t.type,l.value));if(d.some(l=>l===void 0))throw new Error(`Copies of ${e.label} records cannot be picked out by ${t.label}: its values are dates and times, which this cleanup does not compare.`);let c=e.fields.some(l=>l.name==="LastModifiedDate"),u=[];for(let l=0;l<d.length&&u.length<r;l+=ZO){let g=d.slice(l,l+ZO).join(", "),p=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${g}) ORDER BY Id LIMIT ${bD}`),f=new Map;for(let h of p.records){if(typeof h!="object"||h===null)continue;let m=h;if(!Qr(m.Id))continue;let y=wD(t.type,m[t.name]),R=f.get(y)??[];R.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),f.set(y,R)}for(let h of f.values()){h.sort((m,y)=>y.modified.localeCompare(m.modified)||y.id.localeCompare(m.id));for(let m of h.slice(1)){if(u.length>=r)break;u.push(m.id)}}}return{total:a,ids:u}}async function ag(s,e,t,r,n){let o=sr.parse(await s.describe(ze(e))),i=ze(o.name),a=p=>o.fields.find(f=>f.name.toLowerCase()===p.toLowerCase());if(t.kind==="stale"){if(!Number.isInteger(t.days)||t.days<1)throw new Error(`A staleness threshold is a whole number of days, not ${t.days}.`);if(!a("LastModifiedDate"))throw new Error(`${o.label} records carry no date of last modification.`);let p=`LastModifiedDate < LAST_N_DAYS:${t.days}`,f=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${p}`)).totalSize,h=n?.modified!==void 0?mD(n.modified):void 0,m=h!==void 0&&n?.id!==void 0&&Qr(n.id)?` AND (LastModifiedDate > ${h} OR (LastModifiedDate = ${h} AND Id > '${n.id}'))`:"",y=await s.query(`SELECT Id, LastModifiedDate FROM ${i} WHERE ${p}${m} ORDER BY LastModifiedDate, Id LIMIT ${r}`),R=QO(y.records),S=y.records.at(-1),w=ig(n,R.length,f,{id:R.at(-1),...typeof S?.LastModifiedDate=="string"?{modified:S.LastModifiedDate}:{}});return{object:o,total:f,ids:R,truncated:(n?.skip??0)+R.length<f,...w?{next:w}:{}}}if(t.kind==="orphans"){let p=a(t.fieldApiName);if(!p||!tI(p))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let f=ze(p.name),h=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${f} = null`)).totalSize;if(!rI(h-m,h))throw new Error(`${p.label} is filled on fewer than ${Math.round(.9*100)}% of ${o.label} records: the business does not rely on it, and a record without it is no orphan.`);let y=n?.id!==void 0&&Qr(n.id)?` AND Id > '${n.id}'`:"",R=await s.query(`SELECT Id FROM ${i} WHERE ${f} = null${y} ORDER BY Id LIMIT ${r}`),S=QO(R.records),w=ig(n,S.length,m,{id:S.at(-1)});return{object:o,total:m,ids:S,truncated:(n?.skip??0)+S.length<m,...w?{next:w}:{}}}let d=a(t.keyField);if(!d||!Ol(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,u=await RD(s,o,d,c+r),l=u.ids.slice(c),g=ig(n,l.length,u.total,{});return{object:o,total:u.total,ids:l,truncated:c+l.length<u.total,...g?{next:g}:{}}}var vD=6e4,SD=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function sI(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var bc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return ga(r,t)}async handle(e){if(!SD.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:cleanup:scan":return await this.handleScan(e),!0;case"dataops:cleanup:export":return await this.handleExport(e),!0;default:return await this.handleDelete(e),!0}}async handleScan(e){let t=$(Hm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await nI(r,t),o=A(this.deps,e,"dataops:cleanup:scan:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){E(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=$(Jm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await ag(r,t.objectApiName,t.recommendation,1e3,t.after),o=await kn(r,n.object.name,n.object.fields.map(u=>u.name),n.ids),i=new Date().toISOString(),a={sandforgeCleanupVersion:1,orgId:t.orgId,objectApiName:n.object.name,recommendation:t.recommendation,exportedAt:i,recommended:n.total,records:o},d=await this.saveDialog.save(`sandforge-cleanup-${n.object.name}-${sI(t.recommendation)}.json`,JSON.stringify(a,null,2),["json"]),c=A(this.deps,e,"dataops:cleanup:export:response",{objectApiName:t.objectApiName,records:o.length,truncated:n.truncated,saved:d,exported:(t.after?.skip??0)+o.length,recommended:n.total,...n.next?{next:n.next}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} ${d.status} records=${o.length}`)}catch(r){E(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=$(Vm,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,recommendation:n,dryRun:o}=t;try{let i=await this.session(r,"dataops:cleanup:delete"),a=await ag(i,t.objectApiName,n,1e3),{object:d,ids:c}=a;if(d.deletable!==!0)throw new Error(`The connected user may not delete ${d.label} records: Export keeps a copy of them, and an admin grants Delete on ${d.label} in a permission set. Nothing was deleted.`);if(o){let v=await ha(i,d,c,await fa(i)),b={objectApiName:d.name,label:d.label,records:c.length,related:v.related,uncounted:v.uncounted},C=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:b,truncated:a.truncated,written:mc([b])});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id} plan records=${c.length}`);return}if(c.length===0)throw new Error(`No ${d.label} record is left to delete for this recommendation.`);let u=await q(r,this.deps.orgRegistry,this.deps.orgManager),l=ye(this.deps.orgManager.getOrg(r),r),g=this.targetAutomation,p=$a(t),f=await en({act:"cleanup",target:l,objects:[{objectApiName:d.name,records:c.length}],org:No(u,v=>new ge(vD).withTimeout("dataops automation",()=>g.read(r,v)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...p?{voice:p}:{}}),h=Tn(f.answer);if(h){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(h.message),{code:h.code,...xa(h)});return}let m=await ro(f,e.id,t.acceptEmails===!0,p);if("refused"in m){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,R={},S=async()=>{if(!(!y||R.back)){R.back=await y.release();for(let v of Xt(R.back,l))this.deps.log(`[INFO] ${v}`)}},w={objectApiName:d.name,label:d.label,records:c.length},O=await hc(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${sI(n)}`,origin:"dataops:cleanup:delete",run:async(v,b)=>{let C=await ma(i,d.name,c,b);return v(d.name,C),[{objectApiName:d.name,counts:C}]},beforeEnd:S},this.liveTracker).finally(S);if(!O.ran){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(O.message),O.code?{code:O.code}:void 0);return}if(O.error!==void 0){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(O.error),O.cancelled?{code:rt}:void 0);return}let P=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,truncated:a.truncated,outcome:O.outcome,...y?{mutedAutomation:R.back??y.outcome}:{}});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id} ${O.outcome.status} deleted=${O.outcome.done} failed=${O.outcome.failed}`)}catch(i){E(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as IN}from"node:path";async function iI(s){let{permissions:e,objects:t}=s;if(e.viewAllData&&e.modifyAllData)return{kind:"org"};let r={kind:"perObject",viewAllData:e.viewAllData,modifyAllData:e.modifyAllData},n=await s.grants();if("unread"in n)return{...r,unseen:t.map(l=>({objectApiName:l,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=Wb(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=zb(t,{...i,describes:d}),u=[];for(let[l,g]of c)"access"in g||u.push({objectApiName:l,reason:g.reason,...g.detail!==void 0?{detail:g.detail}:{}});return{...r,unseen:u}}function aI(s,e){if(e.kind==="org")return[];let t=new Set(s.kind==="org"?[]:s.unseen.map(r=>r.objectApiName));return e.unseen.map(r=>r.objectApiName).filter(r=>!t.has(r))}var kD=1e4,cI={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function dg(s){return Ls(cI,s,1,"hard")}var uI=9,OD=25;function lI(s,e,t){let r=e>0&&Ls(cI,s,e,t);if(!r&&t==="hard"&&e>0)return{objectApiName:s,records:e,restCalls:0,jobs:[],toTheBin:!1,notSent:!0};if(!r)return{objectApiName:s,records:e,restCalls:Math.ceil(e/Wt),jobs:[],toTheBin:!0};let n=Math.ceil(e/Ms),o=Math.ceil(e/n),i=[];for(let a=e;a>0;a-=o)i.push(Math.min(a,o));return{objectApiName:s,records:e,restCalls:0,jobs:i,toTheBin:t==="recycle"}}function Fr(s,e){return{apiRequests:s,seconds:s*e}}function hi(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function pI(s){return Math.max(1,Math.ceil(s/$l))}function gI(s){return s.notSent?{apiRequests:0,seconds:0}:hi([Fr(pI(s.records),no),Fr(1,Bs),Fr(s.restCalls,Fa),...s.jobs.map(e=>({apiRequests:Pw({stateReads:$w(e)}),seconds:Cw(e)}))])}function ID(s){return s<=0?{apiRequests:0,seconds:0}:hi([Fr(1,Bs),Fr(Math.ceil(s/$l),no),Fr(Math.ceil(s/Wt),Fa),Fr(Math.ceil(s/Wt),no)])}function AD(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Wt);return hi([Fr(e,Fa),Fr(e,no)])}var TD=.05,dI={check:2,connect:3};function Rc(s,e,t,r=0){let n=t*dI.check+dI.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*TD);return{apiRequests:o+i,seconds:e*Bs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function fI(s){let e=s.passes.map(({objectApiName:d,records:c})=>lI(d,Math.max(0,c),s.mode)),t=hi([ID(s.toDraft),Fr(s.draftReads??0,no),...e.map(gI),...(s.refused??[]).map(AD)]),r=Rc(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((u,l)=>u+Math.ceil(l/kD),0),0),o=s.mode==="recycle"?Math.max(0,s.deleted):e.filter(d=>d.toTheBin).reduce((d,c)=>d+c.records,0),i=s.dataStorageMB===void 0?void 0:s.dataStorageMB*OD,a=e.some(d=>d.jobs.length>0);return{...r,bulkBatches:n,passes:e,binRecords:o,...i===void 0?{}:{bin:{documentedCapacity:i,past:o>i}},api:Pn(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?Pn(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function hI(s,e,t,r=0){let n=hi(e.map(o=>{let i=lI(o.objectApiName,Math.max(0,o.records),s),a=gI(i);if(!o.idsRead||i.notSent)return a;let d=pI(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*no}}));return Rc(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var cg=3;function mI(s,e,t=0){return Rc({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function yI(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*Bs},o=Rc(n,Math.max(0,e),t,Math.max(0,r)),i=s.api.verdict==="unread"?{unread:s.api.unread}:{max:s.api.max,remaining:s.api.remaining};return{...s,...o,api:Pn(o.apiRequests,i)}}var ED=qb.extend({relationshipName:j().nullish(),polymorphicForeignKey:Ke().optional()}),wI=Ua.extend({deletable:Ke().optional(),fields:ve(ED)});function ug(s){return Mb.has(s)}var bI={pricebook2:{field:"IsStandard",value:!0}};function RI(s){let e=bI[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function ao(s){let e=bI[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var PD=new Set(["pricebook2","product2"]);function vI(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&Bb(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function lg(s,e=t=>t){let t=[];for(let[r,n]of s)for(let o of n.childRelationships??[]){let i=e(o.childSObject),a=s.get(i)?vc(s,i,o.field):void 0;SI(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:vI(o,r)})}return t}var mi=5,CD=8;function SI(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function $D(s,e,t){let r=vc(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function pg(s,e,t){let r=new Map;for(let f of[...e,...s,...t.keys()])r.set(f.toLowerCase(),f);let n=f=>r.get(f.toLowerCase())??f,o=f=>t.get(f)??t.get(n(f)),i=new Set(s.map(f=>f.toLowerCase())),a=new Set([...e,...s].map(f=>f.toLowerCase())),d=new Map,c=new Map,u=new Set,l=(f,h)=>{let m=c.get(f)??new Set;m.add(h),c.set(f,m)},g=s.map(f=>({top:f,from:f,above:[]}));for(;g.length>0;){let f=[];for(let{top:h,from:m,above:y}of g){let R=o(m);if(!R){u.add(m);continue}for(let S of R.childRelationships??[]){if(vI(S,m)!=="cascade")continue;let w=n(S.childSObject),P=o(w)?.fields.find(k=>k.name.toLowerCase()===S.field.toLowerCase());if(SI(P,m))continue;let v=w.toLowerCase();if(!a.has(v)||v===m.toLowerCase()||y.some(k=>k.object.toLowerCase()===v))continue;let b=[{object:w,field:S.field,parent:m},...y],C=d.get(w)??[];if(b.length>1&&C.length>=CD){l(w,m);continue}d.set(w,[...C,{object:w,steps:b,emptied:h}]),!(i.has(v)||b.length>=mi)&&f.push({top:h,from:w,above:b})}}g=f}for(let f=!0;f;){f=!1;for(let[h,m]of d)for(let y of m)for(let[R,S]of y.steps.entries())R===0||!c.has(S.object)||y.steps.slice(0,R).some(O=>$D(t,O.object,O.field))||c.get(h)?.has(S.object)||(l(h,S.object),f=!0)}let p=[...d.keys()].filter(f=>!i.has(f.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:p,routesCut:new Map([...c].map(([f,h])=>[f,[...h].sort()])),undescribed:[...u].filter(f=>!i.has(f.toLowerCase())).sort()}}function rs(s,e){let t=new Set,r=new Set,n=o=>{if(!r.has(o)){r.add(o),e.emptied.has(o)&&t.add(o);for(let i of e.routes.get(o)??[])n(i.emptied)}};return n(s),t}function xD(s,e,t){if(t===void 0)return s;if(t==="unnamed")return{...s,exact:!1};if(t.length===0)return s;let r=t.map(n=>`'${n}'`).join(", ");return{soql:`${s.soql} AND ${e} NOT IN (${r})`,exact:s.exact}}function vc(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function Sc(s,e,t=ao,r=()=>{}){let n=[],o=(i,a,d,c)=>xD({soql:i,exact:a},d,r(c));for(let[i,a]of s.entries()){if(!e.has(a.object)){let f=[...n,a.field].join(".");return o(`${f} != null`,!1,f,a.parent)}let d=vc(e,a.object,a.field);if(!d){if(i===0)return;let f=s[i-1],h=[...n.slice(0,-1),f.field].join(".");return o(`${h} != null`,!1,h,f.parent)}let c=(d.referenceTo?.length??0)>1||d.polymorphicForeignKey===!0,u=d.relationshipName??void 0,l=i===s.length-1,g=u?[...n,u].join("."):void 0,p=[...n,d.name].join(".");if(c)return g?o(`${g}.Type = '${a.parent}'`,l,p,a.parent):o(`${p} != null`,!1,p,a.parent);if(l){let f=t(a.parent);if(f===void 0&&!PD.has(a.parent.toLowerCase()))return o(`${p} != null`,!0,p,a.parent);if(!g)return o(`${p} != null`,!1,p,a.parent);let h=f!==void 0?` AND ${g}.${f}`:"";return o(`${g}.Id != null${h}`,!0,p,a.parent)}if(!u||i+1>=mi)return o(`${p} != null`,!1,p,a.parent);n.push(u)}}function kI(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?vc(e,o.object,o.field):void 0;if(!i)return;let a=[...r,i.name].join(".");if(n===s.length-1)return`${a} IN (${t.map(c=>`'${c}'`).join(", ")})`;if((i.referenceTo?.length??0)>1||i.polymorphicForeignKey===!0||!i.relationshipName||n+1>=mi)return;r.push(i.relationshipName)}}function yi(s,e,t=ao,r){let n=s.map(a=>Sc(a.steps,e,t,r)).filter(a=>a!==void 0);if(n.length===0)return;if(n.length===1)return n[0];let o=n.every(a=>a.exact)&&n.length===s.length,i=[...new Set(n.map(a=>a.soql))];return i.length===1?{soql:i[0],exact:o}:{soql:i.map(a=>`(${a})`).join(" OR "),exact:o}}function OI(s,e,t,r,n,o=ao,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return Sc([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return yi(d,n,o,i)}var TI=4,II=100,DD=/^[A-Za-z0-9]+$/;function AI(s,e){let t=ao(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===yr.toLowerCase())return`${qs} = false`}var po="stopped before the org was asked";function EI(s,e,t="COUNT()"){let r=ug(s),n=[...e,...r?["IsDeleted = false"]:[]],o=n.length===0?"":` WHERE ${n.map(i=>n.length>1?`(${i})`:i).join(" AND ")}`;return{soql:`SELECT ${t} FROM ${ze(s)}${o}`,all:r}}var lo=class{statements=new Map;answers=new Map;ask(e,t){let r=EI(e,t.map(i=>typeof i=="string"?i:i.soql)),n=t.some(i=>typeof i!="string"&&!i.exact),o=this.statements.get(r.soql);return this.statements.set(r.soql,{...r,atMost:n||o?.atMost===!0}),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await js([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:po});return}try{let d=await(i?e.countAll(o):e.count(o));this.answers.set(n,{records:d,...a?{atMost:!0}:{}})}catch(d){this.answers.set(n,{unread:I(d)})}}),TI),r}answer(e){return this.answers.get(e)??{unread:po}}},Ic=class{statements=new Map;answers=new Map;ask(e,t){let r=EI(e,t,"Id");return this.statements.set(r.soql,r.all),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await js([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:po}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>DD.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:I(i)}})}}),TI),r}answer(e){return this.answers.get(e)??{counted:{unread:po}}}};function hg(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??po}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function gg(s,e){return s.records===void 0?s:e.records===void 0?{...s,atMost:!0}:{...s,records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{},...e.atLeast?{atMost:!0}:{}}}function Fn(s){return s.records===0&&s.atLeast!==!0}function co(s){return s===void 0||s.records===void 0||s.records>0}function Oc(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function mg(s){return s.records===void 0?s:{...s,atLeast:!0}}function wi(s){return s.records===void 0?s:{...s,atMost:!0}}function fg(s,e){let t=e.key?s.answer(e.key):Oc(e.objectApiName),r=e.going?hg(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=mg(r)),e.over&&n&&(r=wi(r)),r}function yg(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function ND(s){let e=r=>typeof r=="string"?r:r.soql,t=[...new Set(s.map(r=>r.length===1?e(r[0]):r.map(n=>`(${e(n)})`).join(" AND ")))];return{soql:t.length===1?t[0]:t.map(r=>`(${r})`).join(" OR "),exact:s.every(r=>r.every(n=>typeof n=="string"||n.exact))}}function uo(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??po};let t=s.some(n=>n.records===void 0||n.atLeast),r=s.some(n=>n.atMost);return{records:e.reduce((n,o)=>n+(o.records??0),0),...r?{atMost:!0}:{},...t?{atLeast:!0}:{}}}var kc="Pricebook2";function jD(s){let e=new Map,t=r=>r.records.records??Number.POSITIVE_INFINITY;for(let r of s){let n=[r.objectApiName,r.field??"",r.parent??""].join("\0"),o=e.get(n);(!o||t(r)>t(o))&&e.set(n,r)}return[...e.values()]}async function PI(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(D=>D.objectApiName),c=a.get(yr)?.fields.some(D=>D.name===qs)===!0,u=D=>{let W=AI(D,c);if(!(D.toLowerCase()===yr.toLowerCase()&&n.emptied.has(Ao)))return W},l=D=>{let W=u(D);return W===void 0?[]:[W]},g=new Map,p=D=>g.get(D),f=D=>p(D),h=D=>Sc(D,a,u,f),m=D=>yi(D,a,u,f),y=(D,W,Y)=>OI(D,W,Y,n,a,u,f),R=new lo,S=new Map;for(let D of d)S.set(D,R.ask(D,l(D)));let w=await R.run(e,t),O=new Map(d.map(D=>[D,R.answer(S.get(D)??"")])),P=D=>[...rs(D,n)].some(W=>co(O.get(W))),v=D=>D.filter(W=>co(O.get(W.emptied))),b=D=>!n.emptied.has(D)&&n.routesCut.has(D),C=new lo,k=[];for(let{parent:D,child:W,field:Y,kind:F}of i){if(F!=="restricted"||W===D||n.emptied.has(W)||!P(D))continue;let Z=y(W,Y,D),_=n.routes.has(W)?m(v(n.routes.get(W)??[])):void 0;k.push({objectApiName:W,field:Y,parent:D,...Z?{key:C.ask(W,[Z])}:{},...Z&&_?{going:C.ask(W,[_,Z])}:{},..._&&b(W)?{over:!0}:{},...n.emptied.has(D)&&!n.routes.has(W)?{naming:""}:{}})}for(let{child:D,field:W,parent:Y,rows:F}of Dl){if(F===void 0||!P(Y)||n.emptied.has(D)||!n.routes.has(D))continue;let _=a.get(D)?.fields.some(Se=>Se.name===F.field)===!0?y(D,W,Y):void 0;if(!_)continue;let de=`${F.field} = ${String(F.value)}`;k.push({objectApiName:D,field:W,parent:Y,key:C.ask(D,[de,_]),along:!0,...n.emptied.has(Y)?{naming:de}:{}})}w=await C.run(e,t)||w;let T=new Ic,x=new Map,J=new Map;k.forEach((D,W)=>{if(D.naming===void 0||D.key===void 0||(fg(C,D).records??0)===0)return;let Y=`Id IN (SELECT ${ze(D.field)} FROM ${ze(D.objectApiName)}${D.naming!==""?` WHERE ${D.naming}`:""})`;x.set(W,T.ask(D.parent,[...l(D.parent),Y])),J.set(D.parent,[...J.get(D.parent)??[],Y])}),w=await T.run(e,t)||w;for(let D of J.keys()){let W=[...x].filter(([F])=>k[F].parent===D).map(([,F])=>T.answer(F));if(W.every(F=>F.counted.records===0))continue;let Y=new Set(W.flatMap(F=>F.ids??[]));g.set(D,W.every(F=>F.ids!==void 0)&&Y.size<=II?[...Y]:"unnamed")}let U=D=>{let W={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let _ of o.passes){let de=_.objectApiName;if(!co(O.get(de)))continue;let Se=l(de);ug(de)&&W.archived.set(de,D.ask(de,[...Se,"IsArchived = true"]));let Ue=RI(de);Ue!==void 0&&W.kept.set(de,D.ask(de,[Ue]));let He=v(_.goneBefore);if(He.length>0){let Ee=m(He);W.goneBefore.set(de,Ee?{key:D.ask(de,[...Se,Ee]),unreadable:!1}:{unreadable:!0})}let ie=r.undo?v(_.sentBeforeTheirParent):[];for(let Ee of ie){let Ne=h(Ee.steps),st=Ee.steps[0],Be=Ne?[...Se,Ne]:void 0;W.undoLost.push({objectApiName:de,field:st.field,parent:st.parent,reason:"unordered",...Be?{key:D.ask(de,Be),conditions:Be}:{}})}}for(let _ of n.along){let de=v(n.routes.get(_)??[]);if(de.length===0)continue;let Se=de.map(He=>{let ie=h(He.steps);return{route:He,...ie?{key:D.ask(_,[ie])}:{}}}),Ue=de.length>1?m(de):void 0;W.along.set(_,{...Ue?{total:D.ask(_,[Ue])}:Se[0].key?{total:Se[0].key}:{},via:Se})}let Y=_=>o.passes.findIndex(de=>de.objectApiName===_);for(let _ of r.undo?o.beforeParent:[]){if(_.reason==="customPrices"){if(!P(kc)||!P(_.parent)||Y(kc)>Y(_.parent))continue;let He=y(_.objectApiName,"Pricebook2Id",kc),ie=y(_.objectApiName,_.field,_.parent),Ee=He&&ie?[He,ie]:void 0;W.undoLost.push({objectApiName:_.objectApiName,field:_.field,parent:_.parent,reason:"restricted",...Ee?{key:D.ask(_.objectApiName,Ee),conditions:Ee}:{},...b(kc)||b(_.parent)?{under:!0}:{}});continue}if(!P(_.objectApiName)||!P(_.parent))continue;let de=y(_.objectApiName,_.field,_.parent),Se=[];if(!n.emptied.has(_.objectApiName)){let He=m(v(n.routes.get(_.objectApiName)??[]));He&&Se.push(He)}let Ue=b(_.objectApiName)||b(_.parent);W.undoLost.push({objectApiName:_.objectApiName,field:_.field,parent:_.parent,reason:"restricted",...de?{key:D.ask(_.objectApiName,[...Se,de]),conditions:[...Se,de]}:{},...Ue?{under:!0}:{}})}for(let{child:_,field:de,parent:Se,rows:Ue}of Dl){if(Ue===void 0||!P(Se)||!n.emptied.has(_))continue;let ie=a.get(_)?.fields.some(Ne=>Ne.name===Ue.field)===!0?y(_,de,Se):void 0;if(!ie||!r.undo||!co(O.get(_)))continue;let Ee=`${Ue.field} = ${String(Ue.value)}`;W.undoLost.push({objectApiName:_,field:de,parent:Se,reason:"restricted",key:D.ask(_,[Ee,ie]),conditions:[Ee,ie],more:!0})}let F=(_,de,Se,Ue=!1)=>{W.refusals.push({code:_,objectApiName:de,key:D.ask(de,Se),...Ue?{under:!0}:{}})};for(let _ of o.toDraft){if(!P(_))continue;let de="StatusCode != 'Draft'";if(n.emptied.has(_)){F("activatedOrder",_,[de]);continue}let Se=v(n.routes.get(_)??[]),Ue=m(Se);F(yg(Se,g)?"activatedOrder":"activatedOrderLeft",_,Ue?[Ue,de]:[{soql:de,exact:!1}],Ue!==void 0&&b(_))}for(let[_,de]of W.kept)W.refusals.push({code:"standardPriceBook",objectApiName:_,key:de});n.emptied.has(ta)&&co(O.get(ta))&&(n.emptied.has(yr)||F("directContactRelation",ta,[{soql:"IsDirect = true",exact:!n.routes.has(yr)}]));let Z=a.get(yr);return n.emptied.has(yr)&&!n.emptied.has(Ao)&&co(O.get(yr))&&Z?.fields.some(_=>_.name===qs)===!0&&F("personAccountContact",yr,[`${qs} = true`]),W},K=new Ic,re=new Map;if(g.size>0){let D=new Set;p=W=>(n.emptied.has(W)||D.add(W),g.get(W)),U(new lo),p=W=>g.get(W);for(let W of[...D].sort()){let Y=v(n.routes.get(W)??[]),F=Y.filter(de=>g.has(de.emptied));if(F.length===0)continue;let Z=g.get(F[0].emptied),_=Y.length===1&&Array.isArray(Z)?kI(Y[0].steps,a,Z):void 0;_===void 0?g.set(W,"unnamed"):re.set(W,K.ask(W,[_]))}w=await K.run(e,t)||w;for(let[W,Y]of re){let F=K.answer(Y);g.set(W,F.ids!==void 0&&F.ids.length<=II?F.ids:"unnamed")}}let N=new lo,L=U(N);w=await N.run(e,t)||w;let B=D=>fg(N,D),te=new lo,se=new Map;for(let[D,W]of J)W.length===2&&g.get(D)==="unnamed"&&se.set(D,te.ask(D,[...l(D),...W]));let H=new Map,X=new Map;for(let D of L.undoLost)X.set(D.objectApiName,[...X.get(D.objectApiName)??[],D]);for(let[D,W]of X){let Y=W.filter(Z=>!Fn(B(Z)));if(Y.length<2)continue;let F=Y.map(Z=>Z.conditions);F.some(Z=>Z===void 0)||H.set(D,te.ask(D,[ND(F)]))}w=await te.run(e,t)||w;let ae=k.map((D,W)=>{let Y=x.get(W);return{objectApiName:D.objectApiName,field:D.field,parent:D.parent,records:fg(C,D),...Y!==void 0?{keeps:T.answer(Y).counted}:{}}}).filter(D=>!Fn(D.records)),me=D=>{let W=ae.flatMap(_=>_.parent===D&&_.keeps!==void 0?[_.keeps]:[]);if(W.length===0)return;let Y=g.get(D);if(Array.isArray(Y))return{records:Y.length};let F=uo(W),Z=se.get(D);return Z!==void 0?gg(F,te.answer(Z)):W.length>1&&(F.records??0)>0?wi(F):F},ce=ae.filter(D=>!Array.isArray(g.get(D.parent))&&k.some(W=>W.along===!0&&W.objectApiName===D.objectApiName&&W.field===D.field&&W.parent===D.parent)),be=ae.filter(D=>k.some(W=>W.along===!0&&W.objectApiName===D.objectApiName&&W.field===D.field&&W.parent===D.parent)),Ye=o.passes.map(D=>{let W=D.objectApiName,Y=AI(W,c),F=O.get(W)??{unread:po};if(!co(F))return{objectApiName:W,...Y!==void 0?{rows:Y}:{},records:F,sent:F};let Z=L.goneBefore.get(W),_=Z===void 0?F:Z.unreadable||Z.key===void 0?Oc(W):n.routesCut.has(W)?wi(hg(F,N.answer(Z.key))):hg(F,N.answer(Z.key)),de=L.archived.get(W),Se=L.kept.get(W),Ue=me(W);return{objectApiName:W,...Y!==void 0?{rows:Y}:{},records:F,sent:_,...de?{archived:N.answer(de)}:{},...Se?{kept:N.answer(Se)}:{},...Ue&&!Fn(Ue)?{blocked:Ue}:{}}}),De=r.undo?Ye.filter(D=>a.get(D.objectApiName)?.undeletable===!1&&!Fn(D.sent)).map(D=>({objectApiName:D.objectApiName,reason:"notRestorable",records:D.sent})):[],_e=[...L.along].map(([D,{total:W,via:Y}])=>{let F=W?N.answer(W):Oc(D),Z=n.routesCut.get(D),_=ce.filter(ie=>ie.objectApiName===D),de=be.filter(ie=>ie.objectApiName===D),Se=_.length>0?uo(_.map(ie=>ie.records)):void 0,Ue=de.length>0?uo(de.map(ie=>ie.records)):void 0,He=Se?gg(F,Se):F;return{objectApiName:D,records:Z?mg(He):He,via:Y.map(({route:ie,key:Ee})=>{let Ne=Ee?N.answer(Ee):Oc(D),st=ie.steps[0],Be=_.filter(Ve=>Ve.field===st.field&&Ve.parent===st.parent);return{field:st.field,parent:st.parent,emptied:ie.emptied,records:Be.length>0?gg(Ne,uo(Be.map(Ve=>Ve.records))):Ne}}).filter(ie=>!Fn(ie.records)),...Ue&&!Fn(Ue)?{blocking:Ue}:{},...Z?{routesNotRead:[...Z]}:{}}}).filter(D=>!Fn(D.records)),z=(D,W)=>D.map(Y=>({...W(Y),records:B(Y)})).filter(Y=>!Fn(Y.records)),oe=jD([...z(L.undoLost,D=>({objectApiName:D.objectApiName,...D.field!==void 0?{field:D.field}:{},...D.parent!==void 0?{parent:D.parent}:{},reason:D.reason})),...De]),ee=new Map;for(let D of oe)ee.set(D.objectApiName,[...ee.get(D.objectApiName)??[],D]);let fe=uo([...ee].map(([D,W])=>{let Y=H.get(D),F=W.filter(_=>_.reason==="notRestorable");if(Y===void 0){let _=uo(W.map(de=>de.records));return W.length>1&&(_.records??0)>0?wi(_):_}let Z=te.answer(Y);return W.some(_=>_.reason!=="notRestorable"&&_.records.atLeast)&&(Z.records??0)>0&&(Z=mg(Z)),F.length>0?wi(uo([Z,...F.map(_=>_.records)])):Z}));return{objects:Ye,along:_e,refusals:z(L.refusals,D=>({code:D.code,objectApiName:D.objectApiName})),blockers:ae,undoLost:oe,undoLostRecords:fe,kept:g,statements:R.size+C.size+T.size+K.size+N.size+te.size,...w?{stopped:!0}:{}}}var xI={lookup:0,cascade:1,restricted:2,customPrices:2},CI="Pricebook2",wg="Product2",$I="PricebookEntry";function MD(s,e){let t=[],r=[],n=o=>s.emptied.has(o)||s.routes.has(o);for(let o of s.emptied)for(let i of rs(o,s))i!==o&&t.push({first:i,then:o,reason:"cascade"});for(let{parent:o,child:i,field:a,kind:d}of e){if(i===o||!n(i)||!n(o))continue;if(d==="lookup"){s.emptied.has(i)&&s.emptied.has(o)&&t.push({first:i,then:o,reason:"lookup"});continue}if(d!=="restricted")continue;let c=rs(i,s),u=s.emptied.has(i)?[i]:[...c],l=!1;for(let g of rs(o,s))if(!c.has(g))for(let p of u)p!==g&&(t.push({first:p,then:g,reason:"restricted"}),l=!0);l&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(CI)&&s.emptied.has(wg)&&(t.push({first:CI,then:wg,reason:"customPrices"}),n($I)&&r.push({objectApiName:$I,field:"Product2Id",parent:wg,reason:"customPrices"})),{constraints:t,beforeParent:r}}function LD(s){return Object.hasOwn(xI,s)}function DI(s,e){let{constraints:t,beforeParent:r}=MD(s,e),n=[...s.emptied].sort(),o=new Map(n.map(l=>[l,[]]));for(let{first:l,then:g,reason:p}of t)p==="cascade"?o.get(l)?.push({childSObject:g,field:p,cascadeDelete:!0}):o.get(g)?.push({childSObject:l,field:p});let i=new Map(n.map(l=>[l,{name:l,fields:[],childRelationships:o.get(l)??[]}])),a=Mh(n,i,({field:l})=>{let g=LD(l)?l:"lookup";return{first:g==="cascade"?"parent":"child",firmness:xI[g]}}),d=new Map(a.map((l,g)=>[l,g])),c=(l,g)=>(d.get(l)??0)<(d.get(g)??0);return{passes:a.map(l=>{let g=s.routes.get(l)??[];return{objectApiName:l,goneBefore:g.filter(p=>c(p.emptied,l)),sentBeforeTheirParent:g.filter(p=>!c(p.emptied,l))}}),beforeParent:r,unordered:FD(t.filter(({first:l,then:g})=>!c(l,g))),toDraft:ir([...n,...s.along])}}function FD(s){let e=new Set;return s.filter(({first:t,then:r,reason:n})=>{let o=`${t}\0${r}\0${n}`;return e.has(o)?!1:(e.add(o),!0)})}function _D(s){switch(s){case"configuration":case"excludedByUser":case"notFound":case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"heldWithFiles":case"setup":case"platformCreated":case"metadata":return s;case"notCustomSetting":return"notFound";case"files":return"documents";case"notWritable":return"notDeletable"}}var UD=(s,e,t)=>{let r=Fb(s,e,"empty",t.customSettings?{customSettings:Nh}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:_D(o),...i===void 0?{}:{detail:i}}))}},HD=new Set([xh,Dh].map(s=>s.toLowerCase()));function NI(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function BD(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(HD.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(jh(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function Ac(s,e,t,r=UD){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(l=>[l.name.toLowerCase(),l])),i=new Set(n.candidates.map(l=>l.toLowerCase())),a=new Map(n.leftOut.map(l=>[l.objectApiName.toLowerCase(),l])),d=[],c=[],u=l=>{let g=a.get(l.name.toLowerCase());return g?{...g,objectApiName:l.name}:{objectApiName:l.name,reason:"notDeletable"}};if(t.mode==="objects"){let l=new Set;for(let g of t.objects??[]){let p=g.toLowerCase();if(l.has(p))continue;l.add(p);let f=o.get(p);f?i.has(p)?d.push(f.name):c.push(u(f)):c.push({objectApiName:g,reason:"notFound"})}}else{let l=new Set((t.excluded??[]).map(g=>g.toLowerCase()));for(let g of t.excluded??[])o.has(g.toLowerCase())||c.push({objectApiName:g,reason:"notFound"});for(let g of o.values()){let p=g.name.toLowerCase();if(l.has(p)){c.push({objectApiName:g.name,reason:"excludedByUser"});continue}if(!i.has(p)){c.push(u(g));continue}let f=BD(g,t);f===void 0?d.push(g.name):c.push({objectApiName:g.name,reason:f})}}return d.sort(),c.sort(NI),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function jI(s,e,t=new Map){let r=[],n=[...s.leftOut];for(let o of s.objects){let i=e.get(o);if(i)i.deletable===!1?n.push({objectApiName:o,reason:"notDeletable"}):i.fields.some(a=>a.name==="IsDeleted")?r.push(o):n.push({objectApiName:o,reason:"noRecycleBin"});else{let a=t.get(o);n.push({objectApiName:o,reason:"notDescribed",...a===void 0?{}:{detail:a}})}}return{...s,objects:r,leftOut:n.sort(NI)}}async function bg(s,e,t,r){await js(e.map(n=>async()=>{try{t.set(n,wI.parse(await s.describe(n)))}catch(o){r.set(n,I(o))}}),6)}function WD(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!dg(r));return t.length===0?s:{...s,objects:s.objects.filter(dg),leftOut:[...s.leftOut,...t.map(r=>({objectApiName:r,reason:"notForGood"}))].sort((r,n)=>r.objectApiName<n.objectApiName?-1:r.objectApiName>n.objectApiName?1:0)}}function go(s){return s.records}async function MI(s,e){let t=Ac(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await bg(e,t.objects,r,n);let o=WD(jI(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(b=>b.name)].map(b=>[b.toLowerCase(),b])),a=b=>i.get(b.toLowerCase())??b,d=pg(o.objects,t.worked,r);for(let b=0;b<mi;b++){let C=d.undescribed.filter(k=>!r.has(k)&&!n.has(k));if(C.length===0)break;await bg(e,C,r,n),d=pg(o.objects,t.worked,r)}let c=b=>d.emptied.has(b)||d.routes.has(b),u=[...new Set(lg(r,a).filter(({kind:b,parent:C,child:k})=>b==="restricted"&&c(C)&&!c(k)).map(({child:b})=>b))].filter(b=>!r.has(b)&&!n.has(b));await bg(e,u,r,n);let l=lg(r,a),g=DI(d,l),p=await PI({affected:d,order:g,relations:l,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),f=[...p.objects.filter(b=>go(b.records)===void 0),...p.along.filter(b=>go(b.records)===void 0)].map(b=>b.objectApiName),h=[...p.objects.map(b=>Math.max(0,(go(b.records)??0)-(b.blocked?.records??0))),...p.along.map(b=>go(b.records)??0)].filter(b=>b>0),m=h.reduce((b,C)=>b+C,0),y=p.along.some(b=>b.records.atLeast===!0)||p.objects.some(b=>b.blocked?.atMost===!0),R=p.refusals.filter(b=>b.code==="activatedOrder").reduce((b,C)=>b+(go(C.records)??0),0),S=g.toDraft.filter(b=>!d.emptied.has(b)).map(b=>{let C=d.routes.get(b)??[];if(!yg(C,p.kept))return{objectApiName:b};let k=yi(C,r,void 0,T=>p.kept.get(T));return{objectApiName:b,...k?{condition:k.soql}:{}}}),w=b=>b.records===void 0||b.records>0,O=p.objects.filter(b=>w(b.records)).length+p.along.filter(b=>w(b.records)).length,P=uI+r.size+n.size+p.statements+2*O,v=fI({mode:s.deleteMode,passes:p.objects.map(b=>({objectApiName:b.objectApiName,records:go(ir([b.objectApiName]).length>0?b.records:b.sent)??0})),toDraft:R,deleted:m,reads:P,draftReads:S.filter(b=>b.condition!==void 0).length,refused:p.blockers.map(b=>go(b.records)??0),...s.apiBudget?{apiBudget:s.apiBudget}:{},...s.bulkBatches?{bulkBatches:s.bulkBatches}:{},...s.dataStorageMB===void 0?{}:{dataStorageMB:s.dataStorageMB}});return{mode:t.mode,deleteMode:s.deleteMode,passes:p.objects,along:p.along,leftOut:o.leftOut,refusals:p.refusals,blockers:p.blockers,beforeParent:g.beforeParent,unordered:g.unordered,undoLost:p.undoLost,undoLostRecords:p.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:S,cost:v,total:{records:m,objects:h.length,uncounted:f,...y?{atLeast:!0}:{}},statements:p.statements,...p.stopped?{stopped:!0}:{}}}var zD=5,GD=Ms,Tc=class{constructor(e,t){this.objectApiName=e;this.planned=t}objectApiName;planned;deleted=0;gone=0;refused=new Map;refusedUnkept=0;lockResent=new Map;notes=[];settle(e,t){e.forEach((r,n)=>{let o=t[n],i=r.slice(0,15);if((o.lockResends!==void 0||this.lockResent.has(i))&&this.lockResent.set(i,o.kind),o.kind!=="refused"){this.refused.delete(r),o.kind==="deleted"?this.deleted++:this.gone++;return}let a={reason:o.reason,dependency:o.dependency,again:o.limit===void 0&&o.reason!==jw};this.refused.has(r)||this.refused.size<GD?this.refused.set(r,a):(this.refusedUnkept++,this.note(o.reason))})}note(e){this.notes.includes(e)||this.notes.push(e)}toSendAgain(){return[...this.refused].filter(([,e])=>e.again).map(([e])=>e)}heldByDependents(){return[...this.refused].filter(([,e])=>e.again&&e.dependency).map(([e])=>e)}result(e,t){let r=this.refused.size+this.refusedUnkept,n=this.refusedUnkept>0?[`${this.refusedUnkept} more refused record(s) were counted, not kept for a second try: the reasons given are those of the records kept.`]:[],o=[...Mw(this.objectApiName,e),...Lw(this.lockResent.values()),...this.notes,...n,...[...this.refused.values()].map(a=>a.reason)],i=this.deleted+this.gone+r;return{objectApiName:this.objectApiName,planned:this.planned,deleted:this.deleted,gone:this.gone,refused:r,...t&&this.planned>i?{notReached:this.planned-i}:{},reasons:[...new Set(o)].slice(0,zD)}}};async function LI(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??ya(),i=e.objects.reduce((h,m)=>h+m.count,0),a=[],d=0,c=[],u=h=>{let m=a.find(y=>y.objectApiName===h);if(!m){let y=e.objects.find(R=>R.objectApiName===h);m=new Tc(h,y?.count??0),a.push(m)}return m},l=async(h,m)=>{await Sa(s,c,{note:(R,S,w,O)=>u(R).note(w?va(R,S,O,c):S)});let y=a.map(R=>R.result(o,h));if(h)for(let{objectApiName:R,count:S}of e.objects)y.some(w=>w.objectApiName===R)||y.push({...new Tc(R,S).result(o,!1),...S>0?{notReached:S}:{}});return{hard:r==="hard",objects:y,cancelled:h,...m!==void 0?{hardRefused:m}:{}}},g=(h,m)=>Fw(s,h.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,R)=>{let S=h.deleted+h.gone+h.refused.size+h.refusedUnkept;h.settle(y,R),t.onSettled?.(h.objectApiName,y,R),d+=h.deleted+h.gone+h.refused.size+h.refusedUnkept-S,t.onProgress?.(d,i,h.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return l(!0,Nw);if(t.toDraft!==!1){let h=await Ra(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=h.drafted,h.cancelled)return l(!0)}for(let{objectApiName:h,count:m}of e.objects){if(n())return l(!0);let y=u(h),R=Ls(s,h,m,r),S=[],w=async()=>{let O=S;return S=[],g(y,O)};for await(let O of e.pages(h)){if(n())return l(!0);if(S.push(...O),R&&S.length<Ms)continue;let P=await w();if(P.stopped)return l(!0,P.hardRefused)}if(S.length>0){if(n())return l(!0);let O=await w();if(O.stopped)return l(!0,O.hardRefused)}}let p;if(await _w(a,{stopped:n,idsOf:(h,m)=>m===0?h.toSendAgain():h.heldByDependents(),send:async(h,m)=>{let y=await g(h,[...m]);return p=y.hardRefused,y.stopped},deleted:h=>h.deleted}))return l(!0,p);for(let h of a){if(n())return l(!0);let{gone:m,unchecked:y,failure:R}=await Uw([...h.refused.keys()],S=>kn(s,h.objectApiName,[],S),()=>!0);for(let S of m)h.refused.delete(S),h.gone++;y.length>0&&h.note(`Not checked: ${y.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(R?` \u2014 ${R}`:"."))}return l(!1)}function JD(s){let e=Math.floor(Date.parse(s)/1e3)*1e3;if(!Number.isFinite(e))throw new RangeError(`Not a date-time: ${s}`);return`CreatedDate < ${new Date(e).toISOString().replace(".000Z","Z")}`}function VD(s){return/CreatedDate/.test(I(s))}function Rg(s){let e=s.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?e[0]:e.map(t=>`(${t})`).join(" AND ")}function KD(s,e,t,r){let n=e?.count??t??s.planned,o=s.deleted+s.gone+s.refused,i=r&&n>o?n-o:0;return{objectApiName:s.objectApiName,planned:n,deleted:s.deleted,gone:s.gone,refused:s.refused,...i>0?{notReached:i}:{},reasons:s.reasons}}function XD(s,e,t,r=!1){if(e&&t===void 0)return"cancelled";let n=s.reduce((i,a)=>i+a.deleted,0),o=s.reduce((i,a)=>i+a.refused+(a.notReached??0),0);return t!==void 0?n>0?"partial":"failure":o===0?"success":n>0||r||s.some(i=>i.gone>0)?"partial":"failure"}async function FI(s){let{journal:e,org:t}=s,r=e.head,n=s.now??(()=>new Date),o=await e.state();await e.attempt(s.resumed,n());let i=[],a=new Ma,d=new Map;if(s.resumed){for await(let N of e.lines())if(N.kind==="settled"){for(let L of[...N.deleted,...N.gone])a.add(L);d.set(N.objectApiName,(d.get(N.objectApiName)??0)+N.deleted.length+N.gone.length)}}let c=new AbortController,u=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,l=()=>u.aborted,g,p=!1,f=JD(r.readAt),h=new Map(r.passes.map(N=>[N.objectApiName,N])),m=N=>h.get(N)?.rows??ao(N),y=new Map,R=new Map,S=()=>r.passes.reduce((N,L)=>N+Math.max(0,(R.get(L.objectApiName)??L.sent??L.records??0)-(d.get(L.objectApiName)??0)),0),w=async(N,L)=>{let B=async te=>{let se=await Lb(t.ids,N,[{objectApiName:L.objectApiName,...te!==void 0?{filter:te}:{}}],{signal:u});return se.stopped?void 0:se.spool};try{let te=await B(Rg([L.filter,L.own,f]));return te?{spool:te,sinceRead:!0}:void 0}catch(te){if(!VD(te))throw te;i.push(`${L.objectApiName} has no CreatedDate: its records were read whole, those made after the simulation among them.`);let se=await B(Rg([L.filter,L.own]));return se?{spool:se,sinceRead:!1}:void 0}},O=N=>{let L=y.get(N);if(L)return L;let B=(async()=>{let te=r.passes.findIndex(be=>be.objectApiName===N),se=e.idsDirOf(te,N),H=o.spooled.get(N);if(s.resumed&&H)return R.set(N,H.count),{spool:await La.open(se,_a),count:H.count,sinceRead:H.sinceRead};if(l())return;let X=m(N),ae=await w(se,{objectApiName:N,...X!==void 0?{own:X}:{}});if(!ae)return;let me=ae.spool.count,ce=h.get(N)?.records;if(ce!==void 0&&me>ce){g={code:"ORG_CHANGED",message:`${N} now holds ${me.toLocaleString("en-US")} records to delete, where the simulation counted ${ce.toLocaleString("en-US")}: the org changed beyond what was confirmed, and the emptying stopped before deleting any of them. Simulate it again, then resume or undo it.`},c.abort();return}return await e.spooled({objectApiName:N,place:te,count:me,sinceRead:ae.sinceRead}),R.set(N,me),{spool:ae.spool,count:me,sinceRead:ae.sinceRead}})();return y.set(N,B),B},P={objects:r.passes.map(N=>({objectApiName:N.objectApiName,count:N.sent??N.records??0})),pages:N=>({async*[Symbol.asyncIterator](){let L=await O(N);if(L)for await(let B of L.spool.pages(N)){let te=a.size>0?B.filter(se=>!a.has(se)):B;te.length>0&&(yield te)}}})},v=Promise.resolve(),b,C=(N,L,B)=>{let te=[],se=[];L.forEach((H,X)=>{let ae=B[X]?.kind;ae==="deleted"?te.push(H):ae==="gone"&&se.push(H)}),te.length>0&&(p=!0),te.length+se.length!==0&&(v=v.then(async()=>{if(b===void 0)try{await e.settled(N,te,se)}catch(H){b=I(H),c.abort()}}))},k=[];for(let[N,L]of r.toDraftAlong.entries()){if(L.condition===void 0||l())continue;let B=e.idsDirOf(r.passes.length+N,L.objectApiName),te=await w(B,{objectApiName:L.objectApiName,filter:L.condition});if(!te)break;let{drafted:se}=await Ra(t.deletion,[{objectApiName:L.objectApiName}],te.spool,()=>!0,l,async()=>new Set);k.push(...se)}let T=await LI(t.deletion,P,{mode:r.deleteMode,signal:u,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:C,onProgress:(N,L,B)=>{let te=Math.max(N,S());s.onProgress?.({percentage:te>0?Math.min(99,Math.round(N/te*100)):99,step:`${B}: ${N.toLocaleString("en-US")} of about ${te.toLocaleString("en-US")} settled`})}}).finally(async()=>{await v,await Sa(t.deletion,k,{note:(N,L,B,te)=>i.push(va(N,L,te,k))})});b!==void 0&&i.push(`The journal of this emptying could not be written (${b}): it stopped there, so that its Undo misses nothing it deleted.`);let x=new Map;for(let[N,L]of y)x.set(N,await L.catch(()=>{}));let J=T.objects.map(N=>KD(N,x.get(N.objectApiName),h.get(N.objectApiName)?.records,T.cancelled));if(!T.cancelled)for(let N of J){if(!x.get(N.objectApiName)?.sinceRead)continue;let B=m(N.objectApiName),te=f.replace("CreatedDate <","CreatedDate >=");try{let se=await t.deletion.query(`SELECT COUNT() FROM ${ze(N.objectApiName)} WHERE ${Rg([B,te])}`);se.totalSize>0&&(N.madeSince=se.totalSize)}catch(se){i.push(`Whether ${N.objectApiName} records were made after the simulation could not be read: `+I(se))}}let U=T.cancelled&&g===void 0&&b===void 0,K=g!==void 0||b!==void 0?p?"partial":"failure":XD(J,U,T.hardRefused,s.resumed&&o.deletedAny),re=J.reduce((N,L)=>N+L.refused,0);return s.resumed&&K==="partial"&&!p&&re>0&&i.push(`The org refused again the ${re.toLocaleString("en-US")} record(s) this emptying had left, each said with its words above: they stay, and the emptying is closed. Undo brings back what it deleted.`),{status:K,hard:T.hard,passes:J,...T.hardRefused!==void 0?{hardRefused:T.hardRefused}:{},...g!==void 0?{changed:g}:{},deletedAny:p,notes:i}}var YD=/Entity is not in the recycle bin/,QD=/INSUFFICIENT_ACCESS/,ZD=5,_I=5e4;function Ec(s){return s.slice(0,15)}function vg(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(Ec(r))}return e}function eN(s){let e=s?.errors?.[0];if(e===void 0)return"The org gave no reason.";if(typeof e=="string")return e;let t=e.statusCode??"",r=e.message??"";return t&&r?`${t}: ${r}`:t||r||"The org gave no reason."}function tN(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function bi(s,e){s.reasons.length<ZD&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*rN(s,e,t){let r=t?new Ma:void 0;for await(let o of s.settledOf(e)){if(r)for(let i of[...o.deleted,...o.gone])r.add(i);o.deleted.length>0&&(yield[...o.deleted])}if(!t||!r)return;let n=await La.open(s.idsDirOf(t.place,e),_a);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function UI(s){let e=0,t=0,r,n=new Map;for await(let o of s.lines())o.kind==="attempt"?(e++,r=void 0):o.kind==="end"?(t++,r=o.status):o.kind==="spooled"&&n.set(o.objectApiName,{place:o.place,count:o.count,attempt:e});return{spooledIn:n,...e>t?{unendedAttempt:e}:{},wentThrough:r==="success"||r==="partial"}}function HI(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function nN(s){return(s.head.undoLost??[]).filter(e=>e.records===void 0||e.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,records:{...e.records!==void 0?{records:e.records}:{unread:"not counted"},...e.atLeast===!0?{atLeast:!0}:{}}}))}async function BI(s){let e=await UI(s),t=0;for(let{objectApiName:r}of s.head.passes){let n=0;for await(let a of s.settledOf(r))a.deleted.length!==0&&(n+=a.deleted.length,t+=Math.ceil(a.deleted.length/Wt)*cg);let o=HI(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Wt)*cg);let i=(s.head.undoLost??[]).filter(a=>a.objectApiName===r).reduce((a,d)=>a+(d.records??0),0);t+=Math.ceil(Math.min(i,n)/Wt)}return t}async function qI(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await UI(e),a=[],d=new Map,c=!1,u=[...r.passes].reverse();for(let[h,{objectApiName:m}]of u.entries()){let y=tN(m);a.push(y);let R=ze(m),S=HI(i,m);for await(let w of rN(e,m,S)){y.planned+=w.length;for(let O=0;O<w.length;O+=Wt){let P=w.slice(O,O+Wt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+P.length;continue}let[v]=Ns(P,Wt),b,C;try{b=vg((await t.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${v}) AND IsDeleted = true`)).records),C=vg((await t.query(`SELECT Id FROM ${R} WHERE Id IN (${v})`)).records)}catch(x){y.refused+=P.length,bi(y,`The recycle bin could not be read: ${I(x)}`);continue}let k=P.filter(x=>b.has(Ec(x)));for(let x of P)b.has(Ec(x))||(C.has(Ec(x))?y.alreadyBack++:(y.notInBin++,bi(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(k.length===0)continue;let T;try{let x=await s.undelete(k),J=Array.isArray(x)?x:[x];T=k.map((U,K)=>J[K]??{success:!1})}catch(x){let J=I(x);T=k.map(()=>({success:!1,errors:[J]}))}T.forEach((x,J)=>{if(x.success===!0){y.undeleted++;return}let U=eN(x);if(YD.test(U)){y.notInBin++;let K=d.get(m)??[];K.length<_I&&K.push(k[J]),d.set(m,K),bi(y,"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 before a record it hangs from was deleted after it (the org answers 'Entity is not in the recycle bin')")}else QD.test(U)?(y.othersDeletion++,bi(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${U})`)):(y.refused++,bi(y,U))})}s.onProgress?.({percentage:Math.round((h+1)/Math.max(1,u.length)*100),step:`${m}: ${y.undeleted.toLocaleString("en-US")} brought back`})}}if(!c)for(let h of a){let m=d.get(h.objectApiName)??[];if(m.length===0)continue;h.notInBin>m.length&&n.push(`${h.objectApiName}: past ${_I.toLocaleString("en-US")} records answered not in the recycle bin, whether a parent brought back later took them back was not read: they are counted as not back.`);let y=ze(h.objectApiName);try{let R=0;for(let w of Ns(m,Wt)){let O=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${w})`);R+=vg(O.records).size}let S=Math.min(R,h.notInBin);h.notInBin-=S,h.alreadyBack+=S}catch(R){n.push(`Whether the ${h.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${I(R)}): they are counted as not back.`)}}let l=i.wentThrough?nN(e):[],g=a.reduce((h,m)=>h+m.undeleted+m.alreadyBack,0),p=a.reduce((h,m)=>h+m.notInBin+m.othersDeletion+m.refused+(m.notReached??0),0)+l.length;return{status:c?"cancelled":p===0?"success":g>0?"partial":"failure",objects:a.filter(h=>h.planned>0),notes:n,...l.length>0?{previewedLost:l}:{}}}var fr="Nothing was deleted.";function Cc(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var Sg=V({Max:Te(),Remaining:Te()}).loose(),oN=V({DailyApiRequests:Sg.optional(),DailyBulkApiBatches:Sg.optional(),DataStorageMB:Sg.optional()}).loose();async function sN(s){try{let e=oN.parse(await s.limits()),t=o=>o?{max:o.Max,remaining:o.Remaining}:void 0,r=t(e.DailyApiRequests),n=t(e.DailyBulkApiBatches);return{apiBudget:r??{unread:"the limits the org answered list no DailyApiRequests"},...n?{bulkBatches:n}:{},...e.DataStorageMB?{dataStorageMB:e.DataStorageMB.Max}:{}}}catch(e){return{apiBudget:{unread:I(e)}}}}async function zI(s){try{return(await s.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t.Id).filter(t=>typeof t=="string")}catch{return[]}}function Ig(s){let e=t=>t.records===void 0||t.records>0;return[...s.passes.filter(t=>e(t.records)).map(t=>t.objectApiName),...s.along.filter(t=>e(t.records)).map(t=>t.objectApiName)]}function iN(s){let e=s.passes.map(n=>({objectApiName:n.objectApiName,records:n.sent.records??0})).filter(n=>n.records>0),t=s.refusals.filter(n=>n.code==="activatedOrder"&&(n.records.records??0)>0).map(n=>({objectApiName:n.objectApiName,records:n.records.records??0})),r=[...e];for(let n of t)r.some(o=>o.objectApiName===n.objectApiName)||r.push(n);return{objects:r,steps:{delete:e.map(n=>n.objectApiName),...t.length>0?{setToDraft:t.map(n=>n.objectApiName)}:{}},written:[...e.map(n=>({...n,write:"delete"})),...t.map(n=>({...n,write:"update"}))]}}async function aN(s,e){let t=[];for(let r of e)try{let n=Ua.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function GI(s,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${s} is being taken`:e.operation==="rewind"?`A rewind is writing to ${s}`:e.operation==="undo"?`An undo is writing to ${s}`:e.operation==="empty"?`An emptying of its objects, or its undo, is writing to ${s}`:`SandForge is deleting checkpoints of ${s}`} (process ${e.pid} on ${e.host}): empty once it has ended. ${fr}`}}function ns(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function kg(s,e){let t=await s.lastOf(e);if(!t)return;let r;try{r=await s.open(e,t.runId)}catch(o){if(o instanceof Cr)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function JI(s,e){return{code:"OPEN_RUN",message:`The last emptying of ${s} (${e}) stopped part way: resume it, or undo it, before another one starts, so that its Undo still reaches the org as it was. ${fr}`}}function dN(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function VI(s){let e=s.undoLostRecords;return e?.records!==void 0?{records:e.records,atLeast:e.atLeast===!0}:{records:s.undoLost.reduce((t,r)=>t+(r.records.records??0),0),atLeast:s.undoLost.some(t=>t.records.records===void 0||t.records.atLeast===!0)}}function cN(s){if(s.deleteMode!=="recycle")return;let e=s.undoLost.filter(i=>i.records.records===void 0||i.records.records>0);if(e.length===0)return;let t=VI(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(dN))],o=e.some(i=>i.reason==="restricted"||i.reason==="unordered");return{code:"NO_UNDO",message:`${r} record(s) would stay gone after Undo (${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""})`+(o?": some go before a record they name, as Salesforce requires, and once both have gone, Undo cannot bring them back":"")+". Accept it to empty all the same, or leave those objects out. "+fr}}function uN(s,e){let t=[],{api:r,batches:n}=s.cost;return r.verdict==="exceeds"&&t.push({code:"API_BUDGET",message:`The emptying takes about ${r.estimate.toLocaleString("en-US")} API requests, and ${e} has ${r.remaining.toLocaleString("en-US")} left today. Empty fewer objects, or tomorrow. ${fr}`}),n?.verdict==="exceeds"&&t.push({code:"BULK_BATCHES",message:`The emptying's Bulk API jobs take about ${n.estimate.toLocaleString("en-US")} batches, and ${e} has ${n.remaining.toLocaleString("en-US")} left today. Empty fewer records, or tomorrow. ${fr}`}),t}function Pc(s){return s.records}function lN(s,e){let t=[],r=new Map(s.passes.map(o=>[o.objectApiName,o]));for(let o of e.passes){let i=r.get(o.objectApiName),a=Pc(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&Pc(i.records)!==void 0&&t.push(`${o.objectApiName} could not be counted again (${o.records.unread??""})`)}let n=new Map(s.along.map(o=>[o.objectApiName,o]));for(let o of e.along){let i=n.get(o.objectApiName),a=Pc(o.records),d=i?Pc(i.records):0;if(a===void 0){d!==void 0&&t.push(`what goes along of ${o.objectApiName} could not be counted again`);continue}d!==void 0&&a>d&&t.push(`${a.toLocaleString("en-US")} ${o.objectApiName} record(s) now go along, where the simulation counted ${d.toLocaleString("en-US")}`)}if(e.deleteMode==="recycle"){let o=c=>VI(c).records,i=c=>new Set(c.undoLost.map(u=>`${u.objectApiName}.${u.field??""}.${u.reason}`)),a=i(s);([...i(e)].filter(c=>!a.has(c)).length>0||o(e)>o(s))&&t.push("more records would go beyond what Undo brings back")}return t}function WI(s,e){return{code:"ORG_CHANGED",message:`${s} changed since the simulation, beyond what was confirmed: ${e.slice(0,5).join("; ")}${e.length>5?"; \u2026":""}. Simulate the emptying again. ${fr}`}}function Og(s,e,t){let r=t.automation?Vr(t.automation,t.mutePlan,Jr(t.steps)):{firing:[]};return{module:"empty",written:Ig(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function KI(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=Cc(t),i=await oo(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await QI(s,e.request,e.deleteMode),d=await en({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...YI(a.preview)}),c=await kg(s.store,i.org.id),u=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(Og(s,a.preview,d.answer),{operationId:s.operationId}):void 0,l=s.requestsSent!==void 0?s.requestsSent()-n:void 0,g=XI(a,l,2,Zr(d.mute?.plan)),p={previewId:pN(s.now?.()??new Date),readAt:g.readAt,orgName:r,tier:i.tier,preview:g.preview,request:e.request,organizationId:i.org.id,access:g.access,hardDelete:{permitted:g.permissions.hardDelete,...g.permissions.unread!==void 0?{unread:g.permissions.unread}:{}},peopleActive:gN(g.people),...u?{checkpoint:u}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},f=await eA(s,i.org.id,g,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...u?{checkpoint:u}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:p,automation:d.answer,refusals:f,...l!==void 0?{requestsSent:l}:{}}}function XI(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:yI(s.preview.cost,n,t,r)}}}function pN(s){return up(s).replace(/^em-/,"ep-")}function YI(s){let e=iN(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function QI(s,e,t){let{org:r}=s,n=Cc(r),o=await r.serverTime(),i=V({sobjects:ve(oa)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await sN(r),c=await MI({global:i,tooling:a,request:e,deleteMode:t,apiBudget:d.apiBudget,...d.bulkBatches?{bulkBatches:d.bulkBatches}:{},...d.dataStorageMB!==void 0?{dataStorageMB:d.dataStorageMB}:{},stopped:()=>s.signal?.aborted===!0},r),u=await Vs(n),l=Ig(c),g=new Set(i.filter(R=>R.customSetting===!0).map(R=>R.name)),p=await iI({permissions:u,objects:l,customSettings:l.filter(R=>g.has(R)),grants:async()=>Gb(n,()=>r.userId()),describe:R=>aN(r,R)}),f=await r.userId(),h=new Date(Date.parse(o)-np).toISOString(),m=await op(r,l,[f,...await zI(r)],h),y=s.voice==="page"?await pS(r,m):m;return{readAt:o,preview:c,permissions:u,access:p,people:y}}function gN(s){return{people:s.people.length,...s.atLeast?{atLeast:!0}:{},...s.who.length>0?{who:s.who.map(e=>({...e}))}:{},...s.unread.length>0?{unread:s.unread}:{}}}function ZI(s){return s.voice==="page"?"page":"flags"}async function eA(s,e,t,r){let n=[],o=await s.runWriting?.(e);o!==void 0&&n.push({code:"RUN_WRITING",message:o}),r.open!==void 0&&n.push(JI(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The simulation was stopped before every count was in: simulate again. ${lS}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(rp(t.permissions));let i=sp(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:ZI(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:cN(t.preview);a&&n.push(a),n.push(...uN(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=Tn(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function fN(s){let e=s.toISOString();return{runId:"",status:"success",hard:!1,passes:[],totals:{deleted:0,gone:0,refused:0,notReached:0},undo:{offered:!1,why:"nothingDeleted"},notes:["The org holds nothing the simulation would delete any more: nothing was sent."],startedAt:e,finishedAt:e}}function hN(s){return{mode:s.mode,...s.objects?{objects:[...s.objects]}:{},...s.excluded?{excluded:[...s.excluded]}:{},...s.customSettings!==void 0?{customSettings:s.customSettings}:{},...s.files!==void 0?{files:s.files}:{},...s.managedPackages!==void 0?{managedPackages:s.managedPackages}:{},...s.unrestorable!==void 0?{unrestorable:s.unrestorable}:{}}}function mN(s){return s.undoLost.filter(e=>e.records.records===void 0||e.records.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,...e.records.records!==void 0?{records:e.records.records}:{},...e.records.atLeast===!0?{atLeast:!0}:{}}))}async function yN(s){let e=new Map,t=new Map;for await(let r of s.lines())if(r.kind==="spooled")e.set(r.objectApiName,r.count);else if(r.kind==="settled"){let n=t.get(r.objectApiName)??0;t.set(r.objectApiName,n+r.deleted.length+r.gone.length)}return s.head.passes.map(r=>{let n=e.get(r.objectApiName);return n===void 0?{objectApiName:r.objectApiName,records:r.sent??r.records??0,idsRead:!1}:{objectApiName:r.objectApiName,records:Math.max(0,n-(t.get(r.objectApiName)??0)),idsRead:!0}})}function wN(s){return s.reduce((e,t)=>({deleted:e.deleted+t.deleted,gone:e.gone+t.gone,refused:e.refused+t.refused,notReached:e.notReached+(t.notReached??0)}),{deleted:0,gone:0,refused:0,notReached:0})}async function tA(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date);if(!e.confirmed&&e.resumeRunId===void 0)throw new Error("An emptying acts on the simulation it was confirmed on, or takes up a run.");let o=s.requestsSent?.()??0,i=Cc(t),a=await oo(i,{orgName:r,registered:s.registered,mode:e.confirmed?.request.mode??"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c,u=await kg(s.store,d);if(e.resumeRunId!==void 0){if(!u||u.runId!==e.resumeRunId)return{ran:!1,refusal:{code:"RUN_GONE",message:`${e.resumeRunId} is not the last emptying of ${r} stopped part way: there is nothing of it to take up. ${fr}`}};if(c=u.journal,c.head.mode==="org"&&a.tier==="staging"){let k=await oo(i,{orgName:r,registered:s.registered,mode:"org"});if(!k.allowed)return{ran:!1,refusal:k.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:WI(r,["it is another org than the one the simulation read \u2014 a refreshed sandbox is a new org"])};let l=e.confirmed,g=c?c.head.deleteMode:l?.preview.deleteMode??"recycle",p=[],f,h,m,y;if(l){f=await QI(s,l.request,g);let k=[...lN(l.preview,f.preview),...aI(l.access,f.access).map(T=>`the user is no longer proven to see every record of ${T}`)];if(k.length>0&&p.push(WI(r,k)),f.preview.total.records===0&&f.preview.total.uncounted.length===0&&k.length===0)return{ran:!0,result:fN(n())};h=await en({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...YI(f.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(Og(s,f.preview,h.answer),{operationId:s.operationId}):void 0,m||p.push({code:"CHECKPOINT_REFUSED",message:`Checkpoints cannot be taken from here: run without Checkpoint first. ${fr}`})),f=XI(f,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,Zr(h.mute?.plan)),p.push(...await eA(s,d,f,{deleteMode:g,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(l.peopleActive.who??[]).map(T=>T.userId)}:{},automation:h.answer,...m?{checkpoint:m}:{},...u?{open:u.runId}:{}}))}else{let k=c.head,T=await Vs(i);g==="hard"&&!T.hardDelete&&p.push(rp(T));let x=await s.runWriting?.(d);x!==void 0&&p.push({code:"RUN_WRITING",message:x});let J=k.passes.map(te=>te.objectApiName),U=await t.userId(),K=await t.serverTime(),re=await op(t,J,[U,...await zI(t)],new Date(Date.parse(K)-np).toISOString()),N=sp(r,re,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:ZI(s)});N&&p.push(N);let L=k.passes.map(te=>({objectApiName:te.objectApiName,records:te.sent??te.records??0})).filter(te=>te.records>0);h=await en({act:"empty",target:r,objects:L,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let B=Tn(h.answer);B&&p.push({code:B.code,message:B.message},...B.alsoRefused),y=hI(g,await yN(c),s.requestsSent!==void 0?s.requestsSent()-o:0,Zr(h.mute?.plan))}if(p.length>0)return ns(p);let R=l&&f?f.preview:void 0,S=R?R.total.records:c.head.passes.reduce((k,T)=>k+(T.records??0),0),w=R?Ig(R):c.head.passes.map(k=>k.objectApiName),O=await s.askGuard({operation:g==="hard"?"hardDelete":"delete",objectNames:w,recordCount:S});if(O.decision==="refused"||O.decision==="declined")return ns([{code:"GUARD",message:O.decision==="refused"?`Production Guard refused the emptying: ${O.reason??"no reason given"}. ${fr}`:`The emptying was declined at Production Guard's confirmation. ${fr}`}],{guard:O.decision});let P=O.decision,v;if(m&&s.checkpoints&&R){let k=await s.checkpoints.take(Og(s,R,h.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:T})=>s.onProgress?.(Math.round(T/10),`Taking the checkpoint first (${Math.round(T)}%)`)});if(!k.taken)return ns(["stopped"in k?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${fr}`}:{code:k.refusal.code,message:k.refusal.message}],{guard:P});v=k.checkpoint}let b=async k=>{if(!v||v.state!=="taken"||!s.checkpoints)return v;try{return await s.checkpoints.settle(v,k)}catch{return v}},C=s.lock(d);if("busy"in C)return await b(!1),ns([GI(r,C.busy)],{guard:P});try{let k=await kg(s.store,d);if(!c&&k)return await b(!1),ns([JI(r,k.runId)],{guard:P});let T=await ro(h,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in T)return await b(!1),ns([{code:T.refused.code,message:T.refused.message}],{guard:P});let x=T.held,J=n(),U=c??await s.store.begin(d,{runId:up(J),orgName:r,startedAt:J.toISOString(),readAt:l.readAt,previewId:l.previewId,mode:R.mode,deleteMode:g,request:hN(l.request),passes:R.passes.map(me=>({objectApiName:me.objectApiName,...me.records.records!==void 0?{records:me.records.records}:{},...me.sent.records!==void 0?{sent:me.sent.records}:{},...me.rows!==void 0?{rows:me.rows}:{}})),toDraftAlong:R.toDraftAlong,beforeParent:R.beforeParent,...g==="recycle"?{undoLost:mN(R)}:{}}),K=R&&R.cost.api.verdict!=="unread"?wa(R.cost.api).splitAllowance:void 0,re,N,L=[];try{re=await FI({org:{deletion:t,ids:t},journal:U,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:ya(K),now:n,onProgress:({percentage:me,step:ce})=>s.onProgress?.(me,ce)})}catch(me){throw await U.ended("failure",[],n()).catch(()=>{}),me}finally{let me=t.lostJobs?.()??[];if(me.length>0&&t.stillRunning){let ce=await t.stillRunning(me);ce.length>0&&L.push(`${ce.length} Bulk API job(s) the org was still running after ten minutes: the mute was given back all the same, and what they delete from now on runs the org's automation.`)}x&&(N=await x.release(),L.push(...Xt(N,r).map(ce=>ce.trim())))}let B=re.passes,te=n();await U.ended(re.status,B,te,re.hardRefused);let se=await b(re.deletedAny),H=[];if(re.status==="success"||re.status==="partial")for(let me of await s.store.runsOf(d))me.runId>=U.head.runId||(await s.store.remove(d,me.runId),H.push(me.runId));let X=await U.state();return{ran:!0,result:{runId:U.head.runId,status:re.status,hard:re.hard,passes:B,totals:wN(B),...re.hardRefused!==void 0?{hardRefused:re.hardRefused}:{},undo:re.hard?{offered:!1,why:"hard"}:X.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...re.notes,...re.changed?[re.changed.message]:[],...L],...N?{mutedAutomation:N}:{},...se?{checkpoint:se}:{},...H.length>0?{removedRuns:H}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:J.toISOString(),finishedAt:te.toISOString()},guard:P}}finally{C.lock.release()}}async function rA(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=Cc(t),a=await oo(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(w,O)=>({ran:!1,refusal:{code:w,message:`${O} Nothing was brought back.`}}),u;try{u=await s.store.open(d,e.runId)}catch(w){if(w instanceof Cr)return c("RUN_GONE",w.message);throw w}if((await s.store.lastOf(d))?.runId!==e.runId)return c("NOT_LAST_RUN",`${e.runId} is not the last emptying of ${r}: Undo reaches the last one alone, as what a later emptying deleted may hang from what this one did.`);let g=await u.state();if(u.head.deleteMode==="hard")return c("UNDO_UNAVAILABLE",`${e.runId} deleted for good: Salesforce brings back nothing a hard delete took, what went along included.`);if(g.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let p=await s.runWriting?.(d),f=[];p!==void 0&&f.push({code:"RUN_WRITING",message:p});let h=u.head.passes.map(w=>({objectApiName:w.objectApiName,records:w.records??0})),m=await en({act:"emptyUndo",target:r,objects:h,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},writes:{steps:{bringBack:h.map(w=>w.objectApiName)},written:[]}}),y=Tn(m.answer);if(y&&f.push({code:y.code,message:y.message},...y.alsoRefused),f.length>0){let[w,...O]=f;return{ran:!1,refusal:w,...O.length>0?{alsoRefused:O}:{}}}let R=mI(await BI(u),s.requestsSent!==void 0?s.requestsSent()-o:0,Zr(m.mute?.plan)),S=s.lock(d);if("busy"in S)return{ran:!1,refusal:GI(r,S.busy)};try{let w=await ro(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in w)return{ran:!1,refusal:{code:w.refused.code,message:w.refused.message}};let O,P;try{P=await qI({org:t,undelete:b=>t.undelete(b),journal:u,...s.signal?{signal:s.signal}:{},onProgress:({percentage:b,step:C})=>s.onProgress?.(b,C)})}finally{w.held&&(O=await w.held.release())}let v=n();return P.status!=="cancelled"&&await u.undone(P.status,v),{ran:!0,result:{runId:e.runId,status:P.status,objects:P.objects,notes:[...P.notes,...O?Xt(O,r).map(b=>b.trim()):[]],...O?{mutedAutomation:O}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:R,...P.previewedLost?{previewedLost:P.previewedLost}:{},finishedAt:v.toISOString()}}}finally{S.lock.release()}}function bN(s){let e=Yn(s),t={closed:!1};return{bulk:{bulk2:{createJob:r=>{let n=e.bulk2.createJob(r);return t={closed:!1},{get id(){return n.id},open:async()=>{await n.open();let o=Ew(n);t={...o!==void 0?{jobId:o}:{},closed:!1}},uploadData:o=>n.uploadData(o),close:async()=>{await n.close(),t={...t,closed:!0}},abort:()=>n.abort(),check:()=>n.check(),getAllResults:()=>n.getAllResults()}}}},last:()=>t}}function nA(s,e,t){let r=Zi(s),n=Dw(s,t),o=bN(s),i=[],a=new rv(async(u,l)=>(await Yn(s).bulk2.job("ingest",{id:l}).check()).state),d=u=>async(l,g,p)=>{try{return await xw(o.bulk,l,g,p,u)}catch(f){let h=o.last();throw h.closed&&i.push({orgId:e,objectApiName:l,...h.jobId?{jobId:h.jobId}:{}}),f}},c=u=>({totalSize:u.totalSize,done:u.done,records:u.records,...u.nextRecordsUrl?{nextRecordsUrl:u.nextRecordsUrl}:{}});return{describe:u=>s.describe(u),count:async u=>(await s.query(u)).totalSize,countAll:async u=>(await s.query(u,{scanAll:!0})).totalSize,readIds:async(u,l)=>{let g=await s.query(u,{scanAll:l});return{totalSize:g.totalSize,ids:g.records.flatMap(p=>typeof p.Id=="string"?[p.Id]:[])}},query:async(u,l)=>c(await s.query(u,{scanAll:l?.scanAll===!0})),queryMore:async u=>c(await s.queryMore(u)),queryDeleted:u=>n.queryDeleted(u),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(u=>u.name)}catch{return[]}},serverTime:async()=>(await s.soap.getServerTimestamp()).timestamp,userId:async()=>(await s.soap.getUserInfo()).userId,limits:()=>s.request({method:"GET",url:"/limits"}),update:(u,l)=>n.update(u,l),destroy:(u,l)=>n.destroy(u,l),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:u=>s.soap.undelete(u),lostJobs:()=>[...i],stillRunning:u=>a.stillRunning(u),requestsSent:r}}import{readdir as RN,readFile as vN,rm as oA,stat as sA,writeFile as SN}from"node:fs/promises";import{join as $c}from"node:path";var aA=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,kN=50;function xc(s){return aA.test(s)}var iA=V({records:Te().optional(),unread:j().optional()}).loose(),ON=V({v:yt(1),orgId:j().min(1),kept:V({previewId:j().regex(aA),readAt:j(),orgName:j(),organizationId:j().min(15).max(18),request:V({mode:We(["objects","org"])}).loose(),preview:V({mode:We(["objects","org"]),deleteMode:We(["recycle","hard"]),passes:ve(V({objectApiName:j(),records:iA}).loose()),along:ve(V({objectApiName:j(),records:iA}).loose()),undoLost:ve(V({objectApiName:j()}).loose()),total:V({records:Te()}).loose()}).loose(),access:V({kind:We(["org","perObject"])}).loose(),peopleActive:V({people:Te(),who:ve(V({userId:j()}).loose()).optional()}).loose()}).loose()}),Dc=class{constructor(e,t=Na){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!xc(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await ja(this.root),await SN($c(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:Da}),await this.sweep(r)}async read(e,t=Date.now()){if(!xc(e))return;let r=$c(this.root,`${e}.json`);try{if((await sA(r)).mtimeMs+this.keepMs<=t)return;let n=ON.safeParse(JSON.parse(await vN(r,"utf8")));return!n.success||n.data.kept.previewId!==e?void 0:{orgId:n.data.orgId,kept:n.data.kept}}catch{return}}async remove(e){xc(e)&&await oA($c(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await RN(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&xc(o.slice(0,-5))).sort(),n=Math.max(0,r.length-kN);for(let[o,i]of r.entries()){let a=$c(this.root,i);try{(o<n||(await sA(a)).mtimeMs+this.keepMs<=e)&&await oA(a,{force:!0})}catch{}}}};var AN=6e4,TN=20,os="dataops",EN=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),pn=class extends Error{constructor(t,r=[],n){super(t.message);this.refusal=t;this.alsoRefused=r;this.mutedAutomation=n;this.name="EmptyRefused"}refusal;alsoRefused;mutedAutomation};function PN(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...mt(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function CN(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...mt(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function $N(s){return{previewId:s.previewId,readAt:s.readAt,orgName:s.orgName,tier:s.tier,preview:s.preview,access:s.access,hardDelete:s.hardDelete,peopleActive:s.peopleActive,...s.checkpoint?{checkpoint:s.checkpoint}:{},...s.openRun?{openRun:s.openRun}:{}}}var Nc=class{constructor(e){this.deps=e}deps;liveTracker;previews=new Map;running=new Map;writing=new Map;targetAutomation;muteLeases={};checkpoints;runWriting;stores;orgOf=(e,t)=>nA(e,t,"dataops:empty");setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setBeforeRunCheckpoints(e){this.checkpoints=e}setRunWriting(e){this.runWriting=e}setStores(e){this.stores=e}setOrgOf(e){this.orgOf=e}isWritingTo(e,t){for(let[r,n]of this.writing)if(n===e&&r!==t)return!0;return!1}async handle(e){if(!EN.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:empty:scope":return await this.handleScope(e),!0;case"dataops:empty:preview":return await this.handlePreview(e),!0;case"dataops:empty:run":return await this.handleRun(e),!0;case"dataops:empty:cancel":return this.handleCancel(e),!0;default:return await this.handleUndo(e),!0}}async countingReader(e){let{TargetAutomationReader:t,targetAutomationQueries:r}=await import("./chunk-FH5UR35W.mjs");return new t(r(async n=>{let o=await q(n,this.deps.orgRegistry,this.deps.orgManager);return e(o),o}))}ownStores(){if(this.stores)return this.stores;let e=Eb({root:Ab()});if("refusal"in e)throw new pn({code:"RUN_WRITING",message:`The lock of the org cannot be kept in ${e.refusal.path}. Nothing was read or deleted.`});let t=e.store;return this.stores={journals:new yd(lp()),previews:new Dc(IN(lp(),"previews")),lock:r=>t.lock(r,"empty")},this.stores}async contextOf(e,t,r,n,o){let i=this.deps.orgManager.getOrg(e),a=await q(e,this.deps.orgRegistry,this.deps.orgManager),d=ye(i,e),c=this.ownStores(),u=this.orgOf(a,e),l=[],g,p=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(g??=this.countingReader(m=>l.push(Zi(m))),g),f=$a(r),h=this.runWriting?.(e,d,t);return{org:u,...u.requestsSent?{requestsSent:()=>(u.requestsSent?.()??0)+l.reduce((m,y)=>m+y(),0)}:{},orgId:e,orgName:d,username:i?.username??d,registered:i,store:c.journals,lock:c.lock,...h?{runWriting:h}:{},automation:No(a,async m=>{let y=await p();return new ge(AN).withTimeout("dataops automation",()=>y.read(e,m,{undeletes:!0}))},!1),muteLeases:this.muteLeases,...f?{voice:f}:{},...this.checkpoints?{checkpoints:this.checkpoints}:{},askGuard:async m=>{let y=this.deps.infraServices?.productionGuard;if(!y)return{decision:"refused",reason:Re.message};let{check:R,decision:S}=await et(y,{orgId:e,orgTier:Pe(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:os});return{decision:S,...S==="refused"?{reason:R.blockedReason??R.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof pn){E(this.deps,e.type,"dataops:error",e,t,{code:t.refusal.code,retryable:!1,...t.alsoRefused.length>0||t.mutedAutomation?{extraPayload:{...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...t.mutedAutomation?{mutedAutomation:t.mutedAutomation}:{}}}:{}});return}E(this.deps,e.type,"dataops:error",e,t,{code:r})}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScope(e){let t=$(Km,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:l=>o.org.query(l)},a=await oo(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new pn(a.refusal);let d=V({sobjects:ve(oa)}).loose().parse(await o.org.describeGlobal()).sobjects,c=Ac(d,await o.org.toolingObjects(),n),u=await Vs(i);this.respond(e,"dataops:empty:scope:response",{mode:c.mode,objects:c.objects,leftOut:c.leftOut,candidates:c.worked,tier:a.tier,hardDelete:{permitted:u.hardDelete,...u.unread!==void 0?{unread:u.unread}:{}}})}catch(r){this.fail(e,r,"EMPTY_SCOPE_ERROR")}}previewStore(){return this.ownStores().previews}async keep(e,t){for(this.previews.set(t.previewId,{orgId:e,kept:t,at:Date.now()});this.previews.size>TN;){let r=this.previews.keys().next().value;if(r===void 0)break;this.previews.delete(r)}try{await this.previewStore()?.keep(e,t)}catch(r){this.deps.log(`[WARN] dataops:empty:preview: ${t.previewId} kept in this window alone (${r instanceof Error?r.message:String(r)})`)}}async keptPreview(e,t){let r=this.previews.get(t),n=r&&Date.now()-r.at<=Na?r:await this.previewStore()?.read(t);return n?.orgId===e?n.kept:void 0}async letGo(e){this.previews.delete(e),await this.previewStore()?.remove(e).catch(()=>{})}async handlePreview(e){let t=$(Xm,e,"dataops:error",this.deps);if(!t)return;let r=new AbortController;this.running.set(e.id,r);try{let n=await this.contextOf(t.orgId,e.id,t,r.signal),o=await KI(n,{request:t.request,deleteMode:t.deleteMode,accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}});if(!o.previewed)throw new pn(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...$N(o.kept),automation:o.automation,refusals:o.refusals,...o.requestsSent!==void 0?{requestsSent:o.requestsSent}:{}})}catch(n){this.fail(e,n,"EMPTY_PREVIEW_ERROR")}finally{this.running.delete(e.id)}}handleCancel(e){let t=$(Qm,e,"dataops:error",this.deps);if(!t)return;let r=this.running.get(t.operationId);r&&(this.deps.infraServices?.backgroundRegistry?.abort(t.operationId),r.abort()),this.respond(e,"dataops:empty:cancel:response",{operationId:t.operationId,cancelled:r!==void 0})}async writeAct(e,t,r,n,o,i,a){let d=e.id,c=this.deps.infraServices?.backgroundRegistry,u=new AbortController;this.running.set(d,u),this.writing.set(d,t);let l=()=>{},g=new Promise((h,m)=>{l=y=>y===void 0?h():m(y)});g.catch(()=>{}),Je(this.deps,d,os,r),c?.register(d,os,r,g,u);let p=ar(this.liveTracker,d,os,r),f=(h,m)=>{Fe(this.deps,d,h,0,0,m),u.signal.aborted||c?.updateProgress(d,h),p.progress(h,0,0,m)};try{let h=await this.contextOf(t,d,a,u.signal,f),m=await n(h);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),pe(this.deps,d,{status:"refused",code:m.refusal.code}),p.fail(m.refusal.message),l(new Error(m.refusal.message)),new pn(m.refusal,m.alsoRefused??[],m.mutedAutomation);let{result:y}=m;if(o(y.status,{result:y,...m.guard?{guard:m.guard}:{}}),await i(y),y.status==="cancelled")c?.abort(d),pe(this.deps,d,{aborted:!0}),p.cancel(),l();else if(y.status==="failure"){let R="Nothing the emptying set out to do went through: its result says why.";pe(this.deps,d,{status:y.status}),p.fail(R),l(new Error(R))}else pe(this.deps,d,{status:y.status}),y.status==="success"?p.complete():p.partial(),l()}catch(h){throw h instanceof pn||(o("failure",{}),pe(this.deps,d,{status:"failure"}),p.fail(h instanceof Error?h.message:String(h)),l(h)),h}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=$(Ym,e,"dataops:error",this.deps);if(t)try{let r;if(t.previewId!==void 0&&(r=await this.keptPreview(t.orgId,t.previewId),!r))throw new pn({code:"PREVIEW_GONE",message:"The simulation this emptying was confirmed on is no longer kept on this machine \u2014 a simulation is kept a day: simulate again, then empty. Nothing was read or deleted."});let n=o=>({empty:"run",...r?{mode:r.preview.mode,deleteMode:r.preview.deleteMode}:{},...t.resumeRunId!==void 0?{resumes:t.resumeRunId}:{},...o?{runId:o.runId,hard:o.hard,gone:o.totals.gone,...o.status==="cancelled"?{cancelled:!0}:{}}:{}});await this.writeAct(e,t.orgId,t.resumeRunId!==void 0?`Taking up the emptying ${t.resumeRunId}`:`Emptying ${r?.preview.total.objects??0} object(s) of ${r?.orgName??t.orgId}`,o=>tA(o,{...r?{confirmed:r}:{},...t.resumeRunId!==void 0?{resumeRunId:t.resumeRunId}:{},accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}}),(o,i)=>Q(this.deps,{action:"cleanup_delete",module:os,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:PN(i.result)}:{},...i.result?.mutedAutomation?{muted:ut(i.result.mutedAutomation)}:{},...i.result?.checkpoint?.state==="taken"?{checkpointId:i.result.checkpoint.checkpointId}:{},details:n(i.result)}),async o=>{t.previewId!==void 0&&await this.letGo(t.previewId),this.respond(e,"dataops:empty:run:response",{operationId:e.id,result:o})},t)}catch(r){this.fail(e,r,"EMPTY_RUN_ERROR")}}async handleUndo(e){let t=$(Zm,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>rA(r,{runId:t.runId,accord:t}),(r,n)=>Q(this.deps,{action:"empty_undo",module:os,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:CN(n.result)}:{},...n.result?.mutedAutomation?{muted:ut(n.result.mutedAutomation)}:{},details:{empty:"undo",runId:t.runId}}),r=>this.respond(e,"dataops:empty:undo:response",{operationId:e.id,result:r}),t)}catch(r){this.fail(e,r,"EMPTY_UNDO_ERROR")}}};import{userInfo as FN}from"node:os";var dA=6e4,xN=2*6e4,DN=50,NN=2880*6e4,jN=60*6e4,MN=250,cA="pipeline-triggers",LN=V({cron:j().optional(),timezone:j().optional(),nextRunAt:Te().optional(),lastFiredAt:Te().optional(),lastOutcome:We(["started","missed"]).optional()});function Ri(s,e){return`pipeline-trigger:${s}:${e}`}var jc=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new hS;now;newId;timer;started=!1;firstLook=!0;looking;lookAgain=!1;lastPrune=0;soonest;busyMisses=new Map;refusedMisses=new Map;unscheduled=new Map;start(){this.started||(this.started=!0,this.firstLook=!0,this.deps.log("[pipeline-triggers] started"),this.look())}stop(){this.started&&(this.started=!1,clearTimeout(this.timer),this.timer=void 0,this.deps.log("[pipeline-triggers] stopped"))}reload(){return this.started?this.look():Promise.resolve()}async onSandboxRefresh(e){if(!this.started)return;let t=this.deps.org(e.orgId);for(let r of this.deps.pipelines())for(let n of this.triggersOf(r)){if(!this.engine.firesOnRefreshOf(n,e.orgId)||this.engine.idleReason(n,t)||!this.deps.claims.claim(`refresh:${r.id}:${n.id}:${e.key}`))continue;let o=this.now(),i=await this.problemsOf(r);if(i.length>0){this.refuseStart(r,n,"sandbox_refresh",o,i,{sandboxName:t?.name});continue}this.fire(r,n,"sandbox_refresh",o,t?.name)}}async statuses(){let e=[],t=this.now();for(let r of this.deps.pipelines()){let n=this.triggersOf(r),o;for(let i of n){let a=this.read(r.id,i.id),d=i.type,c={pipelineId:r.id,triggerId:i.id,type:d,armed:!1,...a.lastFiredAt!==void 0?{lastFiredAt:new Date(a.lastFiredAt).toISOString(),...a.lastOutcome?{lastOutcome:a.lastOutcome}:{}}:{},...d==="schedule"?{timezone:this.engine.timezoneOf(i)}:{}},u=this.engine.idleReason(i,this.orgOf(i),t);u||(o??=await this.problemsOf(r),o.length>0&&(u={idle:"cannotRun",detail:o.join(" ")})),!u&&!this.started&&(u={idle:"stopped"});let l;if(!u&&d==="schedule"){let g=this.planOf(i,a)??this.engine.nextRun(i,t);typeof g=="number"?l=g:u=g}e.push(u?{...c,idle:u.idle,...u.detail?{detail:u.detail}:{}}:{...c,armed:!0,...l!==void 0?{nextRunAt:new Date(l).toISOString()}:{}})}}return e}look(){return this.looking?(this.lookAgain=!0,this.looking):(this.looking=this.lookNow().catch(e=>{this.deps.log(`[pipeline-triggers] a look failed: ${I(e)}`)}).finally(()=>{this.looking=void 0,this.lookAgain?(this.lookAgain=!1,this.look()):this.arm()}),this.looking)}async lookNow(){if(!this.started)return;let e=this.now(),t=this.firstLook;this.firstLook=!1,e-this.lastPrune>=jN&&(this.lastPrune=e,this.deps.claims.prune(NN));let r=new Set,n=new Set,o;for(let i of this.deps.pipelines()){n.add(i.id);let a;for(let d of this.triggersOf(i)){r.add(Ri(i.id,d.id));let c=this.engine.idleReason(d,this.orgOf(d),e);if(c||(a??=await this.problemsOf(i)),d.type!=="schedule")continue;let u=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);u!==void 0&&(o===void 0||u<o)&&(o=u)}this.sayWhyUnscheduled(i,a)}for(let i of[...this.unscheduled.keys()])n.has(i)||this.unscheduled.delete(i);this.soonest=o,this.forgetAllBut(r)}sayWhyUnscheduled(e,t){if(t===void 0)return;let r=this.unscheduled.get(e.id);if(t.length===0){if(r===void 0)return;this.unscheduled.delete(e.id),this.deps.log(`[pipeline-triggers] "${e.name}" can run again: its triggers start it`);return}let n=t.join(" ");r!==n&&(this.unscheduled.set(e.id,n),this.deps.log(`[pipeline-triggers] "${e.name}" is not scheduled: its triggers start nothing while a step cannot run. ${n}`))}lookAt(e,t,r,n,o){let i=this.read(e.id,t.id),a=this.planOf(t,i);if(a===void 0)return this.plan(e,t,i,r);if(a>r)return a;let d=this.engine.dueBetween(t,a,r,DN),c=[a,...d.times],u=c[c.length-1],l=!n&&r-u<=xN?u:void 0,g=l===void 0?c:c.slice(0,-1),p=this.plan(e,t,i,r),f=g.filter(h=>this.deps.claims.claim(this.dueKey(e,t,h)));if(f.length>0){let h={reason:n?"closed":"asleep",count:f.length,...f.length>1?{lastDueAt:new Date(f[f.length-1]).toISOString()}:{},...d.more?{atLeast:!0}:{}};this.recordMissed(e,"schedule",f[0],h),this.remember(e,t,{lastFiredAt:f[f.length-1],lastOutcome:"missed"}),this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:"schedule",dueAt:new Date(f[0]).toISOString(),missed:h,...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}})}return l!==void 0&&this.deps.claims.claim(this.dueKey(e,t,l))&&(o.length>0?this.refuseStart(e,t,"schedule",l,o,{...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}}):this.fire(e,t,"schedule",l)),p}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=Ri(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,u=c&&c.detail===a?{...c,count:c.count+1}:{runId:`missed-${this.newId()}`,detail:a,firstDueAt:n,count:1};r==="schedule"&&this.refusedMisses.set(d,u);let l={reason:"cannotRun",count:u.count,...u.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,u.firstDueAt,l,u.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(u.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:l,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=Ri(e.id,t.id);this.refusedMisses.delete(i);let a=this.deps.start(e,r);if(a.started){this.busyMisses.delete(i),this.remember(e,t,{lastFiredAt:n,lastOutcome:"started"}),this.deps.log(`[pipeline-triggers] started "${e.name}" (${r})`),a.run.then(l=>{l?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:l.error??"the run failed",...o?{sandboxName:o}:{}})},l=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:I(l),...o?{sandboxName:o}:{}})});return}let d=this.busyMisses.get(i),c=d&&d.busySince===a.busy.startedAt?{...d,count:d.count+1,lastDueAt:n}:{runId:`missed-${this.newId()}`,busySince:a.busy.startedAt,firstDueAt:n,count:1,lastDueAt:n};this.busyMisses.set(i,c);let u={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,u,c.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),this.deps.log(`[pipeline-triggers] "${e.name}" not started (${r}): a run started at ${a.busy.startedAt} is going`),c.count===1&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...o?{sandboxName:o}:{}})}recordMissed(e,t,r,n,o=`missed-${this.newId()}`){this.deps.record({runId:o,pipelineId:e.id,pipelineName:e.name,status:"missed",triggeredBy:t,startTime:new Date(r).toISOString(),duration:0,stepCount:0,errorCount:0,missed:n})}planOf(e,t){return t.cron===(e.config.cron??"").trim()&&t.timezone===this.engine.timezoneOf(e)?t.nextRunAt:void 0}plan(e,t,r,n){let o=this.engine.nextRun(t,n),i=typeof o=="number"?o:void 0;return this.write(e.id,t.id,{...r,cron:(t.config.cron??"").trim(),timezone:this.engine.timezoneOf(t),nextRunAt:i}),i}unplan(e,t){let r=this.read(e.id,t.id);(r.nextRunAt!==void 0||r.cron!==void 0)&&this.write(e.id,t.id,{...r.lastFiredAt!==void 0?{lastFiredAt:r.lastFiredAt}:{},...r.lastOutcome?{lastOutcome:r.lastOutcome}:{}})}remember(e,t,r){this.write(e.id,t.id,{...this.read(e.id,t.id),...r})}forgetAllBut(e){for(let t of Object.keys(this.deps.store.getByCategory(cA)))e.has(t)||this.deps.store.delete(t)}arm(){if(clearTimeout(this.timer),this.timer=void 0,!this.started)return;let e=this.soonest===void 0?dA:this.soonest-this.now(),t=Math.min(Math.max(e,MN),dA);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=fS.safeParse(r);if(!n.success)return[];let o=n.data;return o.type==="schedule"||o.type==="sandbox_refresh"?[o]:[]})}orgOf(e){let t=e.config.orgId;return e.type==="sandbox_refresh"&&t?this.deps.org(t):void 0}async problemsOf(e){try{return await this.deps.problems(e)}catch(t){return[`The saved pipeline cannot be read: ${I(t)}.`]}}read(e,t){let r=LN.safeParse(this.deps.store.get(Ri(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(Ri(e,t),r,cA)}};function ss(){let s=new Map,e=new Map;return{claim(t){return s.has(t)?!1:(s.set(t,Date.now()),!0)},hold(t,r){let n=e.get(t);return n?{busy:n}:(e.set(t,r),{release:()=>{e.delete(t)}})},prune(t){let r=Date.now()-t;for(let[n,o]of s)o<r&&s.delete(n)}}}var Y1=65*6e4;var uA=[{id:"tpl-sandbox-refresh",name:"Sandbox Refresh",description:"Full sandbox refresh: backup data, seed test data, verify deployment.",category:"environment",steps:[{name:"Backup Target Data",type:"dataops:backup",description:"Export current target data before refresh."},{name:"Seed Test Data",type:"seed:execute",description:"Generate and insert test data from templates."},{name:"Verify Deployment",type:"compare:execute",description:"Compare metadata between source and target."}]},{id:"tpl-data-migration-dry",name:"Migration Pre-flight Check",description:"Describe source objects, deltas, field mappings and conflicts for a migration (steps do not run yet).",category:"migration",steps:[{name:"Describe Source Objects",type:"sync:describe-global",description:"List all queryable objects in source."},{name:"Detect Deltas",type:"sync:delta",description:"Identify new, modified, and deleted records."},{name:"Validate Field Mappings",type:"sync:describe-fields",description:"Verify field compatibility between orgs."},{name:"List Conflicts",type:"sync:preview",description:"List conflicts between source and target records."}]},{id:"tpl-nightly-cleanup",name:"Nightly Cleanup",description:"Scheduled cleanup: anonymize stale data, archive old records, refresh monitoring.",category:"maintenance",steps:[{name:"Anonymize PII",type:"dataops:anonymize",description:"Apply GDPR anonymization rules to sensitive data."},{name:"Archive Old Records",type:"dataops:backup",description:"Backup and archive records older than 90 days."},{name:"Refresh Monitor",type:"monitor:refresh",description:"Refresh org health and limit data."}]}];function Ag(s,e){return`${s}\0${e}`}var Mc=class{constructor(e){this.deps=e}deps;waiting=new Map;get canAsk(){return this.deps.ask!==void 0}ask(e,t){let r=this.deps.now??(()=>new Date),n=Ag(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=u=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(u))},d=()=>a({decision:"cancelled",at:r().toISOString()}),c=setTimeout(()=>a({decision:"timedOut",at:r().toISOString()}),e.timeoutMs);if(this.waiting.set(n,{question:o,settle:a}),t?.aborted){d();return}t?.addEventListener("abort",d,{once:!0}),this.deps.announce?.(o),this.deps.ask?.(o).then(u=>{if(u===void 0)return;let l=typeof u=="string"?{decision:u,via:void 0}:u,g=l.decision==="approve"?"approved":"rejected",p=l.via??"notification";this.answer(e.operationId,e.stepId,g,p)||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(Ag(e,t));if(!o)return!1;let i=this.deps.now??(()=>new Date),a=this.deps.who?.();return o.settle({decision:r,via:n,at:i().toISOString(),...a?{by:a}:{}}),!0}isWaiting(e,t){return this.waiting.has(Ag(e,t))}};var lA=50,hA={manual:"by hand",schedule:"by its schedule",sandbox_refresh:"by a sandbox refresh",event:"by an event",webhook:"by a webhook",deployment_complete:"by a deployment"};function _N(s,e){return`Pipeline "${s}" is already running: the run started ${hA[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function UN(s){return{stepName:s.stepName,stepType:s.stepType,status:s.status,...s.duration!==void 0?{duration:s.duration}:{},...s.summary!==void 0?{summary:s.summary}:{},...s.error!==void 0?{error:s.error}:{},...s.approval!==void 0?{approval:s.approval}:{}}}var HN={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function pA(){try{return _h(FN().username)}catch{return}}function BN(s,e){let t=s,r=0,n=!1,o=!1,i,a=()=>{o||(o=!0,e())},d=()=>{r=Date.now(),i=setTimeout(a,t)};return{start(){n||(n=!0,d())},hold(){i!==void 0&&(clearTimeout(i),i=void 0,t=Math.max(0,t-(Date.now()-r)))},resume(){!n||o||i!==void 0||d()},end(){o=!0,clearTimeout(i),i=void 0}}}var gA="A simulation of a pipeline is not available here: nothing ran. Run it, or simulate it again once SandForge has finished starting.",fA={release:()=>{}};function Tg(s){return s.flatMap(e=>e.type==="rewind"&&typeof e.id=="string"&&e.id!==""?[{id:e.id,config:typeof e.config=="object"&&e.config!==null?e.config:{}}]:[])}var qN=new Set(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","pipeline:export","marketplace:list","marketplace:install"]),Lc=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=ss();scheduler;reportTrigger=()=>{};approvalGate;unreadableSaid=new Map;liveTracker;dryRunApplier;pipelinesRootOverride;commandLineHistory;sandforgeVersion;setDryRunApplier(e){this.dryRunApplier=e}setPipelinesRoot(e){this.pipelinesRootOverride=e,this.commandLineHistory=void 0}setSandforgeVersion(e){this.sandforgeVersion=e}pipelinesRoot(){return this.pipelinesRootOverride??DS()}takeRunLock(e,t,r){if(typeof e.id!="string"||e.id==="")return fA;try{let n=jS(this.pipelinesRoot(),e.id,{pipelineName:e.name,ranFrom:this.deps.services?.runsFrom==="commandLine"?"commandLine":"editor",triggeredBy:t,...r?{dryRun:!0}:{}});return"busy"in n?n:(n.tookOver&&this.deps.log(`[INFO] ${LS(n.tookOver)}`),n.lock)}catch(n){return this.deps.log(`[WARN] the run lock of pipeline "${e.name}" could not be taken (${I(n)}): a run from the command line is not kept apart from this one.`),fA}}setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Mc({...e?.askApproval?{ask:e.askApproval}:{},announce:t=>this.postStepUpdate({operationId:t.operationId,stepId:t.stepId,status:"running",approval:{...t.message?{message:t.message}:{},expiresAt:t.expiresAt}}),tooLate:t=>e?.approvalTooLate?.(t),who:pA}),this.approvalGate}async askApproval(e,t,r){r.holdBudget(!0);try{let n=await this.approvals().ask({...e,operationId:r.operationId},t);return r.dryRun||this.recordApproval(e,n,r.operationId),n}finally{r.holdBudget(!1)}}async untimed(e,t){t.holdBudget(!0);try{return await e()}finally{t.holdBudget(!1)}}rewindGrants(){return new Ks(this.deps.configStore)}async runSyncUntimed(e,t,r,n,o){o.holdBudget(!0);try{return await e(t,r,n)}finally{o.holdBudget(!1)}}recordApproval(e,t,r){try{if(!(this.deps.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1))return;new To(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:HN[t.decision],objects:[],details:{pipeline:e.pipelineName??"",step:e.stepName,decision:t.decision,...t.via?{via:t.via}:{},...t.by?{answeredBy:t.by}:{}},timestamp:t.at})}catch(n){this.deps.log(`[WARN] audit trail: approval of run ${r} was not recorded \u2014 ${I(n)}`)}}setPipelineMarketplace(e){this.pipelineMarketplace=e}setStepRunners(e){this.stepRunners=e}startTriggers(e){e.claims&&(this.claims=e.claims),this.reportTrigger=e.report,this.triggerScheduler().start()}stopTriggers(){this.scheduler?.stop()}noticeSandboxRefresh(e){return this.scheduler?.onSandboxRefresh(e)??Promise.resolve()}triggerScheduler(){return this.scheduler??=new jc({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:ye(t,t.id),sandbox:t.orgType==="Sandbox"}:void 0},start:(e,t)=>this.startTriggeredRun(e,t),record:e=>this.recordEntry(e),store:this.deps.configStore,claims:{claim:e=>this.claims.claim(e),hold:(e,t)=>this.claims.hold(e,t),prune:e=>this.claims.prune(e)},report:e=>this.reportTrigger(e),log:this.deps.log}),this.scheduler}savedPipelines(){let e=this.deps.configStore.getByCategory("pipelines"),t=new Map,r=Object.entries(e).flatMap(([n,o])=>{let i=pa.safeParse(o);return i.success?[i.data]:(t.set(n,vl(i.error)),[])});for(let[n,o]of t){if(this.unreadableSaid.get(n)===o)continue;let i=e[n]?.name;this.deps.log(`[pipeline-triggers] saved pipeline ${typeof i=="string"?`"${i}"`:n} is not scheduled: it does not read as a pipeline (${o}).`)}this.unreadableSaid.clear();for(let[n,o]of t)this.unreadableSaid.set(n,o);return r}async pipelineProblems(e){return(await this.buildOrchestrator(void 0,e)).check(e)}startTriggeredRun(e,t){let r=this.claims.hold(e.id,{startedAt:new Date().toISOString(),triggeredBy:t});if("busy"in r)return{started:!1,busy:r.busy};let n=this.takeRunLock(e,t,!1);if("busy"in n)return r.release(),this.deps.log(`[pipeline-triggers] ${fp(n.busy,e.name)}`),{started:!1,busy:{startedAt:n.busy.acquiredAt,triggeredBy:n.busy.triggeredBy}};let o=`${_f}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,o).catch(a=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${I(a)}`),je(this.deps,o,I(a),!1,{context:{module:"automation",operation:"pipeline:execute"}}),a}).finally(()=>{n.release(),r.release()})}}async handle(e){if(!qN.has(e.type))return!1;switch(e.type){case"pipeline:execute":return await this.handlePipelineRun(e),!0;case"pipeline:templates":return this.handlePipelineTemplates(e),!0;case"pipeline:list":return await this.handlePipelineList(e),!0;case"pipeline:history":return this.handlePipelineHistory(e),!0;case"pipeline:save":return this.handlePipelineSave(e),!0;case"pipeline:delete":return this.handlePipelineDelete(e),!0;case"pipeline:approval":return this.handlePipelineApproval(e),!0;case"pipeline:sync-configs":return this.handleSyncConfigs(e),!0;case"pipeline:seed-templates":return this.handleSeedTemplates(e),!0;case"pipeline:masking-templates":return this.handleMaskingTemplates(e),!0;case"pipeline:rewind-steps":return await this.handleRewindSteps(e),!0;case"pipeline:rewind-grant":return await this.handleRewindGrant(e),!0;case"pipeline:rewind-revoke":return this.handleRewindRevoke(e),!0;case"pipeline:export":return await this.handlePipelineExport(e),!0;case"marketplace:list":return this.handleMarketplaceList(e),!0;case"marketplace:install":return this.handleMarketplaceInstall(e),!0;default:return!1}}async handlePipelineRun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(aw,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=r.dryRun===!0;if(a&&(!this.dryRunApplier||!this.stepRunners)){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(gA),{code:"DRY_RUN_UNAVAILABLE",retryable:!0});return}let d=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in d){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(_N(i.name,d.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}let c=this.takeRunLock(i,"manual",a);if("busy"in c){d.release(),E(this.deps,"pipeline:execute","pipeline:error",e,new Error(fp(c.busy,i.name)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let u=await this.runPipeline(i,r.variables??{},"manual",n,{dryRun:a}),l=A(this.deps,e,"pipeline:run:response",{...u,...a?{dryRun:!0}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(u){E(this.deps,"pipeline:execute","pipeline:error",e,u),je(this.deps,n,I(u),!1,{context:o})}finally{c.release(),d.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(pw,e,"pipeline:error",this.deps);if(!t)return;this.approvals().answer(t.operationId,t.stepId,t.decision,"page")||this.deps.log(`[WARN] pipeline:approval for a step that no longer waits: ${t.stepId}`)}async checkpointsOf(e){let t=new Map,r=this.stepRunners?.readCheckpoint;if(!e||!r)return t;for(let n of Tg(e.steps)){let o=$t.safeParse(n.config);if(!(!o.success||t.has(o.data.checkpointId)))try{t.set(o.data.checkpointId,await r(o.data.checkpointId))}catch(i){this.deps.log(`[WARN] checkpoint ${o.data.checkpointId} not read for a check: ${I(i)}`)}}return t}async revokeVoidGrants(){try{let e=this.stepRunners?.readCheckpoint,t=await this.rewindGrants().revokeVoid(e?async r=>(await e(r)).kept:void 0);for(let r of t)this.deps.log(`[INFO] the confirmation of Rewind step ${r.stepId} of pipeline ${r.pipelineId} was taken back: its pipeline is no longer saved, or its checkpoint ${r.checkpointId} is no longer kept`)}catch(e){this.deps.log(`[WARN] confirmations of Rewind steps not checked: ${I(e)}`)}}savedPipeline(e){let t=pa.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=$t.safeParse(t.config),o=n.success&&r?.readCheckpoint?await r.readCheckpoint(n.data.checkpointId):void 0,i=this.rewindGrants().get(e,t.id),a=i?{grantedAt:i.grantedAt,matches:i.takenBackAt===void 0&&Xs(t.config)===i.digest}:void 0;return r?{info:Sk(r,t,o,a),...o?{checkpoint:o}:{}}:{info:{stepId:t.id,valid:!1,why:"missing",...a?{granted:{at:a.grantedAt,digestMatches:a.matches}}:{}}}}async handleRewindSteps(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(gw,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of Tg(r?.steps??[]))n.push((await this.describeRewindStep(t.pipelineId,i)).info);let o=A(this.deps,e,"pipeline:rewind-steps:response",{pipelineId:t.pipelineId,steps:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} (${n.length} Rewind steps)`)}catch(r){E(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(fw,e,"pipeline:error",this.deps);if(!t)return;let{pipelineId:r,stepId:n,typed:o}=t,i=d=>{let c=A(this.deps,e,"pipeline:rewind-grant:response",d);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} ${d.granted?"granted":`refused ${d.code}`}`)},a=(d,c={})=>i({granted:!1,pipelineId:r,stepId:n,code:d,...c.why!==void 0?{why:c.why}:{},...c.reason!==void 0?{reason:c.reason}:{}});try{let d=this.savedPipeline(r),c=Tg(d?.steps??[]).find(h=>h.id===n);if(!c)return a("NOT_SAVED");let u=$t.safeParse(c.config);if(!u.success)return a("CONFIG_INVALID",{reason:u.error.issues[0]?.message??""});let l=this.deps.orgManager.getOrg(u.data.orgId);if(!l)return a("ORG_UNKNOWN");if(o!==ye(l))return a("TYPED_MISMATCH");let{info:g,checkpoint:p}=await this.describeRewindStep(r,c);if(!g.valid)return a("CHECKPOINT_INVALID",{why:g.why??"missing"});if(!p?.kept||p.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let f=pA();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:p.organizationId,checkpointId:u.data.checkpointId,digest:Xs(c.config)??"",grantedAt:new Date().toISOString(),...f!==void 0?{grantedBy:f}:{}}),this.deps.log(`[INFO] pipeline:rewind-grant: Rewind step ${n} of pipeline ${r} confirmed for ${ye(l)}, to checkpoint ${u.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){E(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hw,e,"pipeline:error",this.deps);if(t)try{let r=this.rewindGrants().revoke(t.pipelineId,t.stepId),n=A(this.deps,e,"pipeline:rewind-revoke:response",{pipelineId:t.pipelineId,stepId:t.stepId,revoked:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} revoked=${r}`)}catch(r){E(this.deps,"pipeline:rewind-revoke","pipeline:error",e,r)}}handleSeedTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?bk(this.stepRunners):[],r=A(this.deps,e,"pipeline:seed-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){E(this.deps,"pipeline:seed-templates","pipeline:error",e,t)}}handleMaskingTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?Rk(this.stepRunners):[],r=A(this.deps,e,"pipeline:masking-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){E(this.deps,"pipeline:masking-templates","pipeline:error",e,t)}}handleSyncConfigs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?fk(this.stepRunners):[],r=A(this.deps,e,"pipeline:sync-configs:response",{configs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} configurations)`)}catch(t){E(this.deps,"pipeline:sync-configs","pipeline:error",e,t)}}async buildOrchestrator(e,t){return(await this.buildRunParts(e,t)).orchestrator}async buildRunParts(e,t){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-MIDBQ7SD.mjs"),{StepLibrary:o}=await import("./chunk-6ZW6BLV5.mjs"),{StepExecutor:i}=await import("./chunk-3GATEVHC.mjs"),{ConditionalRouter:a}=await import("./chunk-LUNGNCM3.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,u=e??{operationId:"",holdBudget:()=>{}};c.wrapHandler("delay",p=>(f,h)=>this.untimed(()=>p(f,h),u));let l;if(this.stepRunners){let{runSync:p,seed:f,anonymize:h,takeCheckpoint:m,rewind:y,backup:R}=this.stepRunners,{simulateSync:S,previewSeed:w,previewMasking:O,estimateTake:P,previewRewind:v}=this.stepRunners,b=await this.checkpointsOf(t),C=this.rewindGrants();l={...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...u.triggeredBy?{trigger:u.triggeredBy}:{},rewindGrant:(k,T)=>C.verify(k,T),checkpointKept:k=>b.get(k),...p?{runSync:(k,T,x)=>this.runSyncUntimed(p,k,T,x,u)}:{},backup:(k,T)=>this.untimed(()=>R(k,T),u),...f?{seed:(k,T)=>this.untimed(()=>f(k,T),u)}:{},...h?{anonymize:(k,T)=>this.untimed(()=>h(k,T),u)}:{},...m?{takeCheckpoint:(k,T)=>this.untimed(()=>m(k,T),u)}:{},...y?{rewind:(k,T)=>this.untimed(()=>y(k,T),u)}:{},...S?{simulateSync:(k,T)=>this.untimed(()=>S(k,T),u)}:{},...w?{previewSeed:(k,T)=>this.untimed(()=>w(k,T),u)}:{},...O?{previewMasking:(k,T)=>this.untimed(()=>O(k,T),u)}:{},...P?{estimateTake:(k,T)=>this.untimed(()=>P(k,T),u)}:{},...v?{previewRewind:(k,T)=>this.untimed(()=>v(k,T),u)}:{},...this.approvals().canAsk?{askApproval:(k,T)=>this.askApproval(k,T,u)}:{}},kk(c,l)}if(u.dryRun){if(!this.dryRunApplier||!l)throw new Error(gA);await this.dryRunApplier(c,l)}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return{orchestrator:this.deps.services.automationOrchestrator({builder:new r,triggerEngine:new n,stepLibrary:new o,stepExecutor:c,conditionalRouter:new a,history:new d,services:this.deps.services}),stepExecutor:c}}async runPipeline(e,t,r,n,o={}){let i=o.dryRun===!0,a={module:"automation",operation:"pipeline:execute"},d=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,c=new AbortController,u=!1,l=BN(d,()=>{u=!0,c.abort()}),g=await this.buildOrchestrator({operationId:n,holdBudget:v=>v?l.hold():l.resume(),triggeredBy:r,...i?{dryRun:!0}:{}},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let p=`${i?"Pipeline simulation":"Pipeline"}: ${e.name}`;Je(this.deps,n,"automation",p);let f=ar(this.liveTracker,n,"automation",p,e.steps.length),h=v=>u&&v.status==="stopped"?{...v,status:"failed"}:v,m=(v,b)=>{let C=b,k=g.getActiveRuns(),T=e.steps.length,x=k[0]?.stepResults.length??0,J=Math.round(x/T*100),U=`Step: ${C.stepResult.stepName} (${C.stepResult.status})`;Fe(this.deps,n,J,x,T,U),f.progress(J,x,T,U)},y=(v,b)=>{let{stepId:C}=b;this.postStepUpdate({operationId:n,stepId:C,status:"running"})},R=(v,b)=>{let C=h(b.stepResult);this.postStepUpdate({operationId:n,stepId:C.stepId,status:C.status==="failed"||C.status==="skipped"||C.status==="stopped"?C.status:"completed",...C.duration!==void 0?{duration:C.duration}:{},...C.summary!==void 0?{summary:C.summary}:{},...C.error!==void 0?{error:C.error}:{}})};g.on("stepCompleted",m),g.on("stepStarted",y),g.on("stepCompleted",R),g.on("stepSkipped",R),l.start();let S=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",p,new Promise((v,b)=>{S=C=>C?b(C):v()}),c);let w;try{w=await g.execute(e,t,r,c.signal)}catch(v){throw S(new Error(I(v))),f.fail(I(v)),v}finally{l.end(),g.off?.("stepCompleted",m),g.off?.("stepStarted",y),g.off?.("stepCompleted",R),g.off?.("stepSkipped",R)}let O=u&&w.status==="cancelled",P=O?{...w,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${d} ms.`,stepResults:w.stepResults.map(h)}:w;return S(P.status==="failed"?new Error(P.error??"Pipeline failed"):void 0),P.status==="failed"?f.fail(P.error??"Pipeline failed"):P.status==="cancelled"?f.cancel():P.status==="completed_with_warnings"?f.partial():f.complete(),this.deps.infraServices?.performanceTracker?.complete(n),i||this.recordRun(P,e),P.status==="failed"?je(this.deps,n,P.error??"Pipeline failed",O,{context:a}):pe(this.deps,n,{status:P.status,stepResults:P.stepResults.length}),P}postStepUpdate(e){let t={id:this.deps.nextId(),type:"pipeline:step",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}recordRun(e,t){this.writeHistory({runId:e.id,pipelineId:e.pipelineId,pipelineName:e.pipelineName,status:e.status,triggeredBy:e.triggeredBy,startTime:e.startTime,duration:e.duration??0,stepCount:e.stepResults.filter(r=>r.status!=="skipped").length,errorCount:e.stepResults.filter(r=>r.status==="failed").length,steps:e.stepResults.map(UN)},{pipeline:t})}recordEntry(e){this.writeHistory(e)}writeHistory(e,t={}){try{let r=new Date(e.startTime).getTime();this.deps.configStore.set(`pipeline:history:${e.runId}`,{...e,timestamp:Number.isNaN(r)?Date.now():r,...t},"pipeline-history"),this.trimHistory()}catch(r){this.deps.log(`[ERR] pipeline history write: ${I(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=lA)return;let t=e.map(([r,n])=>{let o=n.timestamp;return{key:r,timestamp:typeof o=="number"?o:0}}).sort((r,n)=>r.timestamp-n.timestamp);for(let{key:r}of t.slice(0,e.length-lA))this.deps.configStore.delete(r)}exportInput(e,t){let r=this.deps.configStore,n=this.deps.services;return{pipeline:e,org:o=>this.deps.orgManager.getOrg(o),syncConfig:o=>new It(r).load(o),seedTemplate:o=>new un(r).load(o),maskingTemplate:o=>new Ta(r).load(o),setting:(o,i)=>n?.getSandforgeSetting?n.getSandforgeSetting(o,i):i,sandforgeVersion:t,exportedAt:new Date().toISOString(),machineTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,now:Date.now()}}outsideStatuses(e){let t=[];for(let r of e){let n=pa.safeParse(r);if(!n.success||n.data.runsOutside===void 0)continue;let o=n.data;try{let i=YS(this.exportInput(o,"0.0.0"));t.push({pipelineId:o.id,matches:i===n.data.runsOutside.digest,...i!==void 0?{digest:i}:{}})}catch(i){this.deps.log(`[WARN] pipeline "${o.name}": whether its exported file is up to date was not read: ${I(i)}`),t.push({pipelineId:o.id,matches:!1})}}return t}async exportPipeline(e){let t=this.savedPipeline(e);if(!t)return{exported:!1,pipelineId:e,code:"NOT_SAVED",message:"No pipeline is saved under this id: save the pipeline, then export it. An export takes the pipeline as saved."};let r=this.sandforgeVersion??this.deps.infraServices?.checkpointFiles?.sandforgeVersion;if(r===void 0)return{exported:!1,pipelineId:e,code:"VERSION_UNKNOWN",message:"This SandForge does not say which release it is, which the file and its launchers name: nothing was exported."};let{stepExecutor:n,orchestrator:o}=await this.buildRunParts(void 0,t),i=new Set((t.variables??[]).map(a=>a.name));return XS({...this.exportInput(t,r),stepRefusal:(a,d)=>n.check(a,{steps:t.steps,index:d,declared:i}),problems:o.check(t),checkedWhereItRuns:this.deps.services?.runsFrom==="commandLine"})}async handlePipelineExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(cw,e,"pipeline:error",this.deps);if(t)try{let r=await this.exportPipeline(t.pipelineId),n=A(this.deps,e,"pipeline:export:response",r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} ${r.exported?`exported ${r.fileName}`:`refused ${r.code}`}`)}catch(r){E(this.deps,"pipeline:export","pipeline:error",e,r)}}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"pipeline:templates:response",{templates:uA});this.deps.broker.postToWebview(t),this.deps.log("[TX] pipeline:templates:response")}async handlePipelineList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipelines"),r=Object.entries(t).map(([a,d])=>({key:a,...d})),n=await this.triggerScheduler().statuses();await this.revokeVoidGrants();let o=this.outsideStatuses(Object.values(t)),i=A(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n,...o.length>0?{outside:o}:{}});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){E(this.deps,"pipeline:list","pipeline:error",e,t)}}commandLineRuns(){try{return this.commandLineHistory??=BS(this.pipelinesRoot(),this.deps.log),this.commandLineHistory.read()}catch(e){return this.deps.log(`[WARN] the pipeline runs of the command line are not listed: ${I(e)}`),[]}}handlePipelineHistory(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipeline-history"),n=[...Object.values(t).map(i=>{let a={...i};return delete a.pipeline,a}),...this.commandLineRuns()].sort((i,a)=>{let d=typeof i.timestamp=="number"?i.timestamp:0;return(typeof a.timestamp=="number"?a.timestamp:0)-d}),o=A(this.deps,e,"pipeline:history:response",{history:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:history:response (${n.length} entries)`)}catch(t){E(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(uw,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.config.runsOutside;if(n!==void 0){let u=dw.safeParse(n);if(!u.success){E(this.deps,"pipeline:save","pipeline:error",e,new Error(`The pipeline was not saved: runsOutside.${vl(u.error)}`),{code:"INVALID_PAYLOAD",retryable:!1});return}}let o=r.id||crypto.randomUUID(),i=`pipeline:saved:${o}`;this.deps.configStore.set(i,{...r.config,id:o,savedAt:new Date().toISOString()},"pipelines");let a=Array.isArray(r.config.steps)?r.config.steps:[],d=this.rewindGrants().revokeChanged(o,a.map(u=>({...typeof u.id=="string"?{id:u.id}:{},...u.type==="rewind"?{type:"rewind"}:{},config:typeof u.config=="object"&&u.config!==null?u.config:{}})));for(let u of d)this.deps.log(`[INFO] pipeline:save ${o}: the confirmation of Rewind step ${u} was taken back, since the save changed what it does`);this.scheduler?.reload();let c=A(this.deps,e,"pipeline:save:response",{success:!0,id:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] pipeline:save:response id=${o}`)}catch(t){E(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(lw,e,"pipeline:error",this.deps);if(!t)return;let{id:r}=t,n=this.claims.hold(r,{startedAt:new Date().toISOString(),triggeredBy:"manual"});if("busy"in n){let a=this.deps.configStore.get(`pipeline:saved:${r}`),d=typeof a?.name=="string"?a.name:r;E(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${hA[n.busy.triggeredBy]} at ${n.busy.startedAt} has not ended. Delete it once that run has ended.`),{code:"PIPELINE_RUNNING",retryable:!0});return}let o;try{o=this.deps.configStore.delete(`pipeline:saved:${r}`);let a=this.rewindGrants().revokePipeline(r);a.length>0&&this.deps.log(`[INFO] pipeline:delete ${r}: the confirmations of Rewind steps ${a.join(", ")} were taken back`)}finally{n.release()}this.scheduler?.reload();let i=A(this.deps,e,"pipeline:delete:response",{id:r,deleted:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:delete:response id=${r} deleted=${o}`)}catch(t){E(this.deps,"pipeline:delete","pipeline:error",e,t)}}handleMarketplaceList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");let t=$(mw,e,"pipeline:error",this.deps);if(t===null)return;let r;t?.query?r=this.pipelineMarketplace.search(t.query):t?.category?r=this.pipelineMarketplace.getByCategory(t.category):r=this.pipelineMarketplace.getTemplates();let n=A(this.deps,e,"marketplace:list:response",{success:!0,templates:r.map(o=>({id:o.id,name:o.name,description:o.description,category:o.category,author:"SandForge",stepTypes:o.steps.map(i=>i.type),steps:o.steps.map(i=>({name:i.name,type:i.type,config:i.config,...i.condition?{condition:i.condition}:{}}))}))});this.deps.broker.postToWebview(n)}catch(t){this.deps.log(`[ERR] marketplace:list: ${I(t)}`);let r=A(this.deps,e,"marketplace:list:response",{success:!1,error:I(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(yw,e,"pipeline:error",this.deps);if(!t)return;let{templateId:r}=t;try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");if(!this.pipelineMarketplace.getById(r))throw new Error(`Template "${r}" not found.`);let o=this.pipelineMarketplace.exportTemplate(r),i;try{i=JSON.parse(o)}catch{throw new Error(`Template "${r}" contains invalid JSON.`)}let a=i.id;typeof a=="string"&&a!==""&&this.rewindGrants().revokePipeline(a);let d=A(this.deps,e,"marketplace:install:response",{success:!0,pipeline:i});this.deps.broker.postToWebview(d)}catch(n){this.deps.log(`[ERR] marketplace:install: ${I(n)}`);let o=A(this.deps,e,"marketplace:install:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var is=class{calls=new Map;begin(e){let t=new AbortController;return this.calls.has(e)||this.calls.set(e,t),{signal:t.signal,end:()=>{this.calls.get(e)===t&&this.calls.delete(e)}}}abort(e){let t=this.calls.get(e);return t?.abort(),t!==void 0}};function fo(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(mA())):new Promise((t,r)=>{let n=()=>r(mA());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function mA(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var yA=200,Eg=50,Pg="ai.enabled",Cg="ai.errorResolution",wA="ai:conversations:index",bA="ai",Fc="ai.anthropic.key",WN=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:delete","ai:conversation:delete-all","ai:conversation:list","ai:status","ai:save-key","ai:settings","ai:remove-key"]),_c=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new is;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!WN.has(e.type))return!1;switch(e.type){case"ai:chat":return await this.handleChat(e),!0;case"ai:chat:cancel":return this.handleChatCancel(e),!0;case"ai:conversation:create":return this.handleConversationCreate(e),!0;case"ai:conversation:load":return this.handleConversationLoad(e),!0;case"ai:conversation:list":return this.handleConversationList(e),!0;case"ai:conversation:delete":return this.handleConversationDelete(e),!0;case"ai:conversation:delete-all":return this.handleConversationDeleteAll(e),!0;case"ai:status":return await this.handleStatus(e),!0;case"ai:save-key":return await this.handleSaveKey(e),!0;case"ai:settings":return await this.handleSettings(e),!0;case"ai:remove-key":return await this.handleRemoveKey(e),!0;default:return!1}}conversationKey(e){return`ai:conversation:${e}`}loadIndex(){return this.deps.configStore.get(wA)??[]}saveIndex(e){this.deps.configStore.set(wA,e,bA)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,bA),this.updateIndexEntry(e)}updateIndexEntry(e){let t=this.loadIndex(),r=t.findIndex(o=>o.id===e.id),n={id:e.id,title:e.title,createdAt:e.createdAt,messageCount:e.messages.length,updatedAt:e.updatedAt};r>=0?t[r]=n:t.push(n),this.saveIndex(this.withinTheBound(t,e.id))}withinTheBound(e,t){if(e.length<=Eg)return e;let r=o=>o.updatedAt??o.createdAt,n=new Set([...e].filter(o=>o.id!==t).sort((o,i)=>r(o).localeCompare(r(i))).slice(0,e.length-Eg).map(o=>o.id));for(let o of n)this.forgetConversation(o);return this.deps.log(`[INFO] ai: ${n.size} conversation(s) written to least recently deleted (${Eg} are kept).`),e.filter(o=>!n.has(o.id))}forgetConversation(e){this.asking.abort(e),this.aiAssistant?.deleteConversation(e),this.deps.configStore.delete(this.conversationKey(e))}deleteAllConversations(){let e=this.conversationKey(""),t=new Set(this.loadIndex().map(r=>r.id));for(let r of this.deps.configStore.getKeysByPrefix(e))t.add(r.slice(e.length));for(let r of t)this.forgetConversation(r);return this.saveIndex([]),t.size}pruneMessages(e){if(e.length<=yA)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=yA-t.length;return[...t,...r.slice(-n)]}isChatRole(e){return e==="user"||e==="assistant"||e==="system"}toConversation(e){let t=e.messages.filter(r=>this.isChatRole(r.role)).map(r=>({id:r.id,role:r.role,content:r.content,timestamp:r.timestamp,tokenCount:r.tokenCount}));return{id:e.id,title:e.title,messages:t,createdAt:e.createdAt,updatedAt:e.updatedAt,totalTokens:t.reduce((r,n)=>r+(n.tokenCount??0),0)}}restoreConversationIfNeeded(e){let t=this.aiAssistant;if(!t||t.getConversation(e))return;let r=this.loadConversation(e);r&&(t.restoreConversation(this.toConversation(r)),this.deps.log(`Restored conversation ${e} from store.`))}async handleChat(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ey,e,"ai:error",this.deps);if(!t)return;let r=t,n=this.aiAssistant;if(!n){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}this.restoreConversationIfNeeded(r.conversationId);let o=this.asking.begin(r.conversationId);try{let i=await n.chat(r.conversationId,r.message,{signal:o.signal}),a=n.getConversation(r.conversationId);a&&this.persistConversationFromMemory(a);let d=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,message:{id:i.id,role:i.role,content:i.content,timestamp:i.timestamp,tokenCount:i.tokenCount},...a?{title:a.title}:{}});this.deps.broker.postToWebview(d),this.deps.log("[TX] ai:chat:response")}catch(i){if(o.signal.aborted){let c=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,code:"CANCELLED"});this.deps.broker.postToWebview(c),this.deps.log("[TX] ai:chat:response cancelled");return}let a=I(i),d=A(this.deps,e,"ai:error",{message:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ai:error: ${a}`)}finally{o.end()}}handleChatCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(la,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Py,e,"ai:error",this.deps);if(!t)return;let r=t;if(!this.aiAssistant){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}let n=this.aiAssistant.createConversation(r.title);this.persistConversationFromMemory(n);let o=A(this.deps,e,"ai:conversation:created",{conversation:{id:n.id,title:n.title,createdAt:n.createdAt}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:created id=${n.id}`)}handleConversationLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(la,e,"ai:error",this.deps);if(!t)return;let r=t;if(this.aiAssistant){let i=this.aiAssistant.getConversation(r.conversationId);if(i){let a=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:i.id,title:i.title,messages:i.messages.map(d=>({id:d.id,role:d.role,content:d.content,timestamp:d.timestamp}))}});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ai:conversation:loaded id=${i.id} (memory)`);return}}let n=this.loadConversation(r.conversationId);if(!n){let i=A(this.deps,e,"ai:error",{message:`Conversation ${r.conversationId} not found.`});this.deps.broker.postToWebview(i);return}let o=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:n.id,title:n.title,messages:n.messages.map(i=>({id:i.id,role:i.role,content:i.content,timestamp:i.timestamp}))}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:loaded id=${n.id} (store)`)}handleConversationList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.loadIndex(),r=A(this.deps,e,"ai:conversation:list:response",{conversations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:list:response count=${t.length}`)}handleConversationDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(la,e,"ai:error",this.deps);if(!t)return;let r=t;this.aiAssistant&&this.aiAssistant.deleteConversation(r.conversationId),this.deps.configStore.delete(this.conversationKey(r.conversationId));let n=this.loadIndex().filter(i=>i.id!==r.conversationId);this.saveIndex(n);let o=A(this.deps,e,"ai:conversation:deleted",{conversationId:r.conversationId});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:deleted id=${r.conversationId}`)}handleConversationDeleteAll(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deleteAllConversations(),r=A(this.deps,e,"ai:conversation:deleted-all",{count:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:deleted-all count=${t}`)}async handleStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`),await this.postStatus(e)}async postStatus(e){let t=await this.deps.secretVault.hasSecret(Fc),r=A(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?$f:"none",model:this.aiAssistant?Df(this.deps.services?.getSandforgeSetting?.("ai.model",xf.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(Cg,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",Pg,!0)}async writeSetting(e,t,r){if(!this.deps.services?.setSandforgeSetting)return this.deps.log(`[WARN] ${e}: no settings backend \u2014 sandforge.${t} left as-is.`),!1;try{return await this.deps.services.setSandforgeSetting(t,r),!0}catch(n){return this.deps.log(`[ERR] ${e}: writing sandforge.${t} failed: ${I(n)}`),!1}}async rebuildAIStack(e="ai:save-key"){let t=this.deps.services?.reinitAI;if(!t){this.deps.log(`[WARN] ${e}: no AI rebuild wired \u2014 the change applies after a reload.`);return}try{await t()}catch(r){this.deps.log(`[ERR] ${e}: rebuilding the AI stack failed: ${I(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Cy,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Fc);await this.deps.secretVault.storeSecret(Fc,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",Cg,n===!0),await this.enableAIFeature(),await this.rebuildAIStack();let i=A(this.deps,e,"ai:save-key:response",{success:!0});this.deps.broker.postToWebview(i),this.deps.log("[TX] ai:save-key:response success"),await this.postStatus(e)}catch(o){let i=I(o);this.deps.log(`[ERR] ai:save-key: ${i}`);let a=A(this.deps,e,"ai:save-key:response",{success:!1,error:i});this.deps.broker.postToWebview(a)}}async handleSettings(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$($y,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([Cg,t.errorResolution]),t.enabled!==void 0&&r.push([Pg,t.enabled]);let n=!0;for(let[i,a]of r)await this.writeSetting("ai:settings",i,a)||(n=!1);await this.rebuildAIStack("ai:settings");let o=A(this.deps,e,"ai:settings:response",{success:n,...n?{}:{error:"The setting could not be written: the SandForge log says why."}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:settings:response success=${n}`),await this.postStatus(e)}async handleRemoveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{await this.deps.secretVault.deleteSecret(Fc);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",Pg,!1),await this.rebuildAIStack("ai:remove-key");let r=A(this.deps,e,"ai:remove-key:response",{success:!0,conversationsDeleted:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:remove-key:response conversations=${t}`),await this.postStatus(e)}catch(t){let r=I(t);this.deps.log(`[ERR] ai:remove-key: ${r}`);let n=A(this.deps,e,"ai:remove-key:response",{success:!1,error:r});this.deps.broker.postToWebview(n)}}persistConversationFromMemory(e){let t=e.messages.map(n=>({id:n.id,role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount})),r={id:e.id,title:e.title,messages:this.pruneMessages(t),createdAt:e.createdAt,updatedAt:e.updatedAt};this.saveConversation(r)}};var zN=new Set(["ai:anomaly-scan"]),Uc=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return zN.has(e.type)&&e.type==="ai:anomaly-scan"?(await this.handleAnomalyScan(e),!0):!1}async handleAnomalyScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(xy,e,"ai:error",this.deps);if(!t)return;let{orgId:r,objectName:n,sampleSize:o}=t;try{if(!this.ruleModules?.anomalyDetector)throw new Error("Anomaly scan is still starting up. Try again in a moment.");let i=await q(r,this.deps.orgRegistry,this.deps.orgManager),a=wt(n),d=o??yn.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,u=await zh(i,a,c),l=u.records,g={records:l,fields:Object.keys(l[0]??{})},p=this.ruleModules.anomalyDetector.detectAnomalies(g,n),f=A(this.deps,e,"ai:anomaly-scan:response",{success:!0,anomalies:p.anomalies.map(h=>({field:h.field,type:h.type,description:h.description,severity:h.severity})),sample:{read:l.length,limit:u.limit??d}});this.deps.broker.postToWebview(f)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${I(i)}`);let a=A(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}}};function RA(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function GN(s){let e=[s];return s.endsWith("ies")&&s.length>3&&e.push(`${s.slice(0,-3)}y`),(s.endsWith("ses")||s.endsWith("xes")||s.endsWith("ches"))&&e.push(s.slice(0,-2)),s.endsWith("s")&&!s.endsWith("ss")&&e.push(s.slice(0,-1)),e}function JN(s){let e=new Map;for(let t of s)if(t.queryable!==!1)for(let r of[t.name,t.label,t.labelPlural]){if(!r)continue;let n=RA(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function vA(s,e,t=5){if(t<=0)return[];let r=JN(e),n=s.split(/[^A-Za-z0-9_]+/).filter(Boolean),o=[],i=new Set;for(let a=0;a<n.length;a++){let d=Math.min(4,n.length-a);for(let c=d;c>=1;c--){let u=n.slice(a,a+c).join(""),l=GN(RA(u)).map(g=>r.get(g)).find(g=>g!==void 0);if(l){if(!i.has(l)&&(i.add(l),o.push(l),o.length>=t))return o;a+=c-1;break}}}return o}var VN={sync:"Sync",seed:"Seed",dataops:"DataOps"};function SA(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=VN[s.page];return`The draft leaves out the ${e} work, which writes to an org: run it from the ${e} page, where Production Guard can stop or ask first.`}var KN=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),XN=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),YN=new Set(["AND","OR","NOT","WHERE"]),QN=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,ZN=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,ej=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,tj=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function rj(s){let e="",t=0;for(;t<s.length;){if(s[t]!=="'"){e+=s[t],t++;continue}for(t++;t<s.length&&s[t]!=="'";)t+=s[t]==="\\"?2:1;t++,e+="''"}return e}var kA=/\(\s*SELECT\b/iy;function nj(s){let e="",t=0;for(;t<s.length;){if(kA.lastIndex=t,s[t]!=="("||!kA.test(s)){e+=s[t],t++;continue}let r=0,n=t;for(;n<s.length;n++)if(s[n]==="(")r++;else if(s[n]===")"&&--r===0)break;e+="()",t=n+1}return e}function oj(s){let e=[],t=0,r=0;for(;r<s.length;){let n=s[r];if(n==="(")t++,r++;else if(n===")")t=Math.max(0,t-1),r++;else if(/\w/.test(n)){let o=r;for(;r<s.length&&/\w/.test(s[r]);)r++;t===0&&e.push({word:s.slice(o,r),start:o,end:r})}else r++}return e}function sj(s){let e=[],t=0,r=0;for(let n=0;n<s.length;n++)s[n]==="("?t++:s[n]===")"?t=Math.max(0,t-1):s[n]===","&&t===0&&(e.push(s.slice(r,n)),r=n+1);return e.push(s.slice(r)),e}function ij(s){let e=ZN.exec(s);if(e)return e[1];let t=ej.exec(s);if(t){let r=t[1].trim();return QN.test(r)?r:null}return null}function aj(s){let e=nj(rj(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=oj(e),r=h=>t[h]?.word.toUpperCase();if(r(0)!=="SELECT")return null;let n=t.findIndex(h=>h.word.toUpperCase()==="FROM");if(n<1||n+1>=t.length)return null;let o=t[n+1].word,i=new Set([o.toUpperCase()]),a=r(n+2)==="AS"?n+3:n+2,d=r(a),c=e.slice(t[n+1].end,t[a]?.start);d&&!KN.has(d)&&!c.includes(",")&&i.add(d);let u=[],l=e.slice(t[0].end,t[n].start);for(let h of sj(l)){let m=ij(h.trim());m&&u.push(m)}let g=t.findIndex((h,m)=>m>n+1&&h.word.toUpperCase()==="WHERE");if(g>=0){let h=t.findIndex((y,R)=>R>g&&XN.has(r(R)??"")),m=e.slice(t[g].end,h<0?e.length:t[h].start);for(let y of m.matchAll(tj))YN.has(y[1].toUpperCase())||u.push(y[1])}let p=new Set,f=[];for(let h of u){let[m,...y]=h.split("."),R=y.length>0&&i.has(m.toUpperCase())?y.join("."):h,S=R.toUpperCase();p.has(S)||(p.add(S),f.push(R))}return{objectApiName:o,fieldRefs:f}}async function OA(s,e){let t=aj(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(u=>u.name.toLowerCase()===r);if(!n)return{rootObject:t.objectApiName,fieldsChecked:0,problems:[{kind:"object-missing",object:t.objectApiName}]};let o;try{o=await e.describe(n.name)}catch(u){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:I(u)}]}}let i=new Set(o.fields.map(u=>u.name.toLowerCase())),a=new Set(o.fields.flatMap(u=>u.relationshipName?[u.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let u of t.fieldRefs){let[l,...g]=u.split(".");g.length===0?i.has(l.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:l}):!a.has(l.toLowerCase())&&!c.has(l.toLowerCase())&&(c.add(l.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:l}))}if(d.length===0)try{await e.explain(s)}catch(u){d.push({kind:"org-refused",detail:I(u)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function $g(s){return uj().text(s)}var cj=new Set;function uj(){let s=Qv(),e=new Map,t=o=>{let i=e.get(o);if(i!==void 0)return i;let a=s(o);return e.set(o,a),a},r=o=>{let i=Zv({text:o},cj,t).text;return typeof i=="string"?i:o},n=o=>typeof o=="string"?r(o):Array.isArray(o)?o.map(n):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,a])=>[i,n(a)])):o;return{text:r,deep:o=>n(o)}}var Bt=Ju,Vt=Ju.text,IA="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var tV=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Bt.maxKeyLength} characters at most.`,`- "name": at most ${Vt.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${Vt.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Bt.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${Vt.industry} characters.`,`- "topics": ${Bt.topics.min} to ${Bt.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${Vt.label} characters.`,`- "utterances": ${Bt.utterances.min} to ${Bt.utterances.max} a topic, two unless it needs more: what a customer whose case on the topic is still open says to the agent ("text"), and what the agent should do, in plain words ("expectedOutcome"), each at most ${Vt.utterance} characters. They may name the customer and the case with ${IA}, filled in when the pack is seeded.`,`- "decoy": an article close to the topic it "resembles", by its key, that does not answer it, so that a test tells the right article from the nearest. "title" at most ${Vt.articleTitle} characters, "summary" at most ${Vt.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Bt.outOfScope.min} to ${Bt.outOfScope.max}, three unless more are useful: what a customer may say that no topic covers, and that the agent should decline ("expectedOutcome"), each at most ${Vt.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var rV=[`- "article": what the agent answers the topic from. "title" at most ${Vt.articleTitle} characters and none of the titles above; "summary" at most ${Vt.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${Vt.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Bt.facts.min} to ${Bt.facts.max}, each a sentence of the body copied word for word, at most ${Vt.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Bt.caseTemplates.min} to ${Bt.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${Vt.caseSubject} characters, and may name {firstName}, {lastName}, {company} and {email}; "description" what the customer writes, under 600 characters; "priority" is High, Medium or Low; "origin" is Phone, Email or Web; "followUp" what the customer writes again while the case is open, under 300 characters; "resolution" ${Bt.resolutionSteps.min} to ${Bt.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${IA}.`,"- No word in braces but the placeholders named here, where they are allowed."];var lj=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),xg={success:!1,code:"CANCELLED"},AA="AI not configured. Set your API key in Settings > AI.";function pj(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var Hc=class{constructor(e){this.deps=e}deps;aiModules;drafting=new is;describeGlobalCache=new Gs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new Gs({defaultTtl:5*6e4,maxSize:50,maxSizeBytes:20*1024*1024});setAIModules(e){this.aiModules=e}forgetOrg(e){this.describeGlobalCache.invalidate(e),this.describeCache.invalidateByPrefix(`${e}::`)}async handle(e){if(!lj.has(e.type))return!1;switch(e.type){case"ai:forge-plan":return await this.handleForgePlan(e),!0;case"ai:generate-pipeline":return await this.handleGeneratePipeline(e),!0;case"ai:scenario-draft":return await this.handleScenarioDraft(e),!0;case"ai:tool:cancel":return this.handleCancel(e),!0;default:return!1}}handleCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(jy,e,"ai:error",this.deps);t&&this.drafting.abort(t.requestId)}async handleForgePlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Dy,e,"ai:error",this.deps);if(!t)return;let{orgId:r,prompt:n}=t,o=this.drafting.begin(e.id);try{let i=this.aiModules?.nl2soql;if(n!==void 0&&!i){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,code:"AI_NOT_CONFIGURED",error:AA}));return}let a=await fo(this.connect(r),o.signal),d=await fo(this.loadCatalog(r,a),o.signal),c=t.soql??"",u;if(n!==void 0&&i){let{result:g}=await this.draft(i,n,r,a,d,o.signal);c=g.soql,u=g.explanation}let l=await fo(OA(c,{catalog:d,describe:async g=>{let p=await this.describeObject(r,a,g);return{name:p.apiName,label:p.label,fields:p.fields.map(f=>({name:f.apiName,relationshipName:f.relationshipName}))}},explain:g=>a.request(`/query/?explain=${encodeURIComponent(g)}`)}),o.signal);this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:l.problems.length===0,soql:c,...u?{explanation:u}:{},...l.rootObject?{rootObject:l.rootObject}:{},...l.rootLabel?{rootLabel:l.rootLabel}:{},fieldsChecked:l.fieldsChecked,problems:l.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{...xg})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${I(i)}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,error:I(i)}))}finally{o.end()}}async connect(e){return await q(e,this.deps.orgRegistry,this.deps.orgManager)}async draft(e,t,r,n,o,i){let a=vA(t,o),d=await fo(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(l=>({apiName:l.name,label:l.label,fields:[]}))};return{result:await fo(e.generateSOQL(t,c,{signal:i}),i),described:d}}async loadCatalog(e,t){let r=this.describeGlobalCache.get(e);if(r)return r;let o=(await t.describeGlobal()).sobjects.filter(i=>i.queryable!==!1).map(i=>({name:i.name,label:i.label,labelPlural:i.labelPlural,queryable:i.queryable}));return this.describeGlobalCache.set(e,o),o}async describeObjects(e,t,r){let n=[];for(let o of r)try{n.push(await this.describeObject(e,t,o))}catch(i){this.deps.log(`[WARN] ai:nl2soql describe ${o}: ${I(i)}`)}return n}async describeObject(e,t,r){let n=`${e}::${r}`,o=this.describeCache.get(n);if(o)return o;let i=await t.describe(r),a={apiName:i.name,label:i.label??i.name,fields:i.fields.map(d=>({apiName:d.name,label:d.label??d.name,type:d.type,...d.relationshipName?{relationshipName:d.relationshipName}:{}}))};return this.describeCache.set(n,a),a}async handleGeneratePipeline(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ny,e,"ai:error",this.deps);if(!t)return;let{description:r,orgIds:n}=t,o=this.drafting.begin(e.id);try{if(!this.aiModules?.pipelineGenerator)throw new Error("AI not configured. Set your API key in Settings > AI to enable this feature.");let i=(n??[]).map(u=>{let l=this.deps.orgManager.getOrg(u);return{orgId:u,alias:l?.alias??u,type:pj(l?.orgType)}}),{suggestions:a=[],...d}=await fo(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let u=a.map(SA).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${u}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:u,suggestions:a}));return}if(d.steps.length===0)throw new Error("The AI returned a pipeline with no steps, so there is nothing to load. Name the operations it should run, for example: back up Account daily, then compare dev with uat.");let c=A(this.deps,e,"ai:generate-pipeline:response",{success:!0,pipeline:d,...a.length>0?{suggestions:a}:{}});this.deps.broker.postToWebview(c)}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{...xg})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${I(i)}`);let a=A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(My,e,"ai:error",this.deps);if(!t)return;let r=i=>this.deps.broker.postToWebview(A(this.deps,e,"ai:scenario-draft:response",i));if(t.maskOnly){r({success:!0,sentText:$g(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:AA,sentText:$g(t.text)});return}let o=this.drafting.begin(e.id);try{let i=await n.draft({text:t.text,language:t.language,...t.casePicklists?{casePicklists:t.casePicklists}:{},...t.agent?{agent:t.agent}:{},...t.draft?{from:t.draft}:{}},{signal:o.signal});i.kind==="failed"?this.deps.log(`[ERR] ai:scenario-draft (${i.failedAt.call}): ${i.error}`):i.kind==="stopped"&&this.deps.log("[TX] ai:scenario-draft:response cancelled"),r(gj(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${I(i)}`),r({success:!1,error:I(i)})}finally{o.end()}}};function gj(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...xg,sentText:s.sentText,...s.draft?{draft:s.draft}:{}};case"failed":return{success:!1,error:s.error,failedAt:s.failedAt,sentText:s.sentText,...s.issues?{issues:s.issues}:{},...s.draft?{draft:s.draft}:{}}}}var fj=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"]),Bc=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new _c(e),this.analysisHandler=new Uc(e),this.toolsHandler=new Hc(e),this.subHandlers=[this.chatHandler,this.analysisHandler,this.toolsHandler]}setAIAssistant(e){this.chatHandler.setAIAssistant(e)}setAIModules(e){this.toolsHandler.setAIModules(e)}setRuleModules(e){this.analysisHandler.setRuleModules(e)}forgetOrg(e){this.toolsHandler.forgetOrg(e)}async handle(e){if(!fj.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function TA(s,e,t){return{records:s.totalRows,estimateMB:e.estimateMB,verdict:e.verdict,...e.verdict==="unread"?{unread:e.unread}:{remainingMB:e.remainingMB,maxMB:e.maxMB},...t.verdict==="unread"?{}:{apiRequests:{estimate:t.estimate,remaining:t.remaining,max:t.max,verdict:t.verdict}}}}function EA(s,e,t){let{mode:r,share:n}=s,o=r.all!==void 0||Object.keys(r.caps??{}).length>0;return{module:"autopilot",...n!==void 0?{share:n}:{},...o?{capped:!0}:{},...r.withinMB!==void 0?{withinMB:r.withinMB}:{},kept:e,inSource:t}}var hj=new Set(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"]),mj=10,Dg=3e4,CA=6e4;function $A(s){return`autopilot:${s}`}var Ng=(s,e)=>e==="insert"||e==="update",qc={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},as={code:"AUTOPILOT_RUNNING",message:"An Autopilot run is still writing to this target org: Monitor's Live Operations shows where it is. Start another once it has ended."},yj=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),Wc=class{constructor(e){this.deps=e}deps;operations=new Map;currentOperationId;executingOperations=new Set;runningRequests=new Set;writingTargets=new Map;beforeRunCheckpoints;orchestrator;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setOrchestrator(e){this.orchestrator=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}isWritingTo(e,t){let r=this.writingTargets.get(e);return r!==void 0&&(t===void 0||t!==$A(r))}async handle(e){if(!hj.has(e.type))return!1;switch(e.type){case"autopilot:list-objects":return await this.handleListObjects(e),!0;case"autopilot:count-objects":return await this.handleCountObjects(e),!0;case"autopilot:scan-schema":return await this.handleScanSchema(e),!0;case"autopilot:generate-plan":return await this.handleGeneratePlan(e),!0;case"autopilot:fit-plan":return await this.handleFitPlan(e),!0;case"autopilot:fit-undo":return await this.handleFitUndo(e),!0;case"autopilot:execute":return await this.handleExecute(e),!0;case"autopilot:pause":return this.handlePause(e),!0;case"autopilot:resume":return this.handleResume(e),!0;case"autopilot:skip-node":return this.handleSkipNode(e),!0;case"autopilot:compliance-report":return this.handleComplianceReport(e),!0;default:return!1}}refuseNotReady(e){E(this.deps,e.type,"autopilot:error",e,new Error(qc.message),{code:qc.code}),yj.has(e.type)&&Ie(this.deps,"error","Autopilot",qc.message,{code:qc.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>mj;){let e=this.operations.keys().next();if(e.done||this.executingOperations.has(e.value))return;this.operations.delete(e.value),this.currentOperationId===e.value&&(this.currentOperationId=[...this.operations.keys()].pop())}}async handleListObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(yy,e,"autopilot:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.orchestrator.listObjects(r,n,t.includeStandardObjects),i=A(this.deps,e,"autopilot:objects-listed",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){E(this.deps,"autopilot:list-objects","autopilot:error",e,r)}}async handleCountObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(wy,e,"autopilot:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await this.orchestrator.countObjects(r,t.objectApiNames),o=A(this.deps,e,"autopilot:objects-counted",{counts:Object.fromEntries(n)});this.deps.broker.postToWebview(o)}catch(r){E(this.deps,"autopilot:count-objects","autopilot:error",e,r)}}async handleScanSchema(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(by,e,"autopilot:error",this.deps);if(!t)return;let r=t,n=this.currentOperationId,o={id:e.id,targetOrgId:r.targetOrgId,sourceOrgId:r.sourceOrgId};this.operations.set(e.id,o),this.currentOperationId=e.id,this.evictOldOperations();try{let i=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),d=await this.orchestrator.scanSchemas(i,a,{selectedObjects:r.selectedObjects,includeStandardObjects:r.includeStandardObjects,...r.maxDepth!==void 0?{maxDepth:r.maxDepth}:{},...r.maxObjects!==void 0?{maxObjects:r.maxObjects}:{},maxRecordsPerObject:this.maxRecordsPerObject()});o.scanResult=d;let c=this.orchestrator.buildGraph(d);o.graph=c;let u=A(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(u)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),E(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Ie(this.deps,"error","Autopilot",`Schema scan failed: ${I(i)}`)}}async handleGeneratePlan(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.graph){Ie(this.deps,"error","Autopilot","No schema scan result available. Run scan-schema first.");return}let r=$(Ry,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?vR(this.deps.infraServices?.piiDetector??new Pa,t.scanResult.objectDescribes):[],{profile:i,rules:a}=this.orchestrator.buildCompliance(n.complianceFramework,[],o);t.profile=i,t.rules=a;let d=this.orchestrator.generatePlan(t.graph,n.complianceFramework,a,t.scanResult?.scope);t.plan=d,t.fit&&(t.fit={...t.fit,plan:this.orchestrator.generatePlan(t.fit.graph,n.complianceFramework,a,t.fit.scan.scope)}),await this.sendPlanReady(e,t)}catch(o){E(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Ie(this.deps,"error","Autopilot",`Plan generation failed: ${I(o)}`)}}async sendPlanReady(e,t,r,n){let{plan:o,graph:i}=t.fit??t,a=t.fit?.scan??t.scanResult;if(!o||!i)return;let d;try{d=a?await this.planWriteGate(t.targetOrgId,Bl(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(u){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${I(u)})`)}if((t.fit??t).plan!==o)return;let c=A(this.deps,e,"autopilot:plan-ready",{plan:o,graph:i,...d?{writeGate:d}:{},...n?{fitNotApplied:n}:{}});this.deps.broker.postToWebview(c)}async planWriteGate(e,t,r,n){let o=await xR(t,r,()=>this.readApiBudgetOf(e),n);return TA(t,Ir(t,r),o)}refuseFit(e,t,r,n){E(this.deps,e.type,"autopilot:error",e,new Error(r),{code:t,...n?{extraPayload:n}:{}})}async handleFitPlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let{orchestrator:t}=this;if(!t){this.refuseNotReady(e);return}let r=$(Sy,e,"autopilot:error",this.deps);if(!r)return;let n=this.resolveCurrentOperation(),{plan:o,graph:i,rules:a,scanResult:d}=n??{};if(!n||!o||!i||!a||!d){this.refuseFit(e,_o.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,as.code,as.message);return}try{let u=await this.readTargetAutomation(c,o),l=r.muteAutomation===!0?await this.planMute(c,u).catch(R=>{if(!Dt(R))throw R}):void 0,g=await this.readTargetDataStorage(c),p=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:u,...l?{mute:l}:{}},new AbortController().signal):void 0,f=RR({storage:g,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},api:"unread"in g?await this.readApiBudgetOf(c).catch(R=>({unread:I(R)})):g.dailyApiRequests??{unread:"the target's /limits did not list them"},otherRequests:Fo(p&&"estimate"in p?p.estimate:void 0)});if("unread"in f){this.refuseFit(e,_o.STORAGE_UNREAD,`The plan cannot be fitted: the target's data storage left could not be read (${f.unread}). Give the most MB it may use to fit it to that.`,{reason:f.unread});return}let h=await q(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=await q(c,this.deps.orgRegistry,this.deps.orgManager),y;try{y=await t.fitPlan(h,{scan:d,graph:i,plan:o,rules:a,mode:r.mode,budget:f,automation:u,...l?.plan?{mutePlan:l.plan}:{},describeLookups:async R=>PR((await m.describe(R)).fields)})}catch(R){let S=I(R);this.refuseFit(e,_o.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${S}).`,{reason:S});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,_o.STALE,"The plan changed while it was fitted: fit it again.");return}if(y.fitted){n.fit={...y.fitted,report:y.report},await this.sendPlanReady(e,n,g);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,g,y.report)}catch(u){E(this.deps,"autopilot:fit-plan","autopilot:error",e,u)}}async handleFitUndo(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan){this.refuseFit(e,_o.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,as.code,as.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){E(this.deps,"autopilot:fit-undo","autopilot:error",e,r)}}async handleExecute(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan||!t.graph||!t.rules||!t.scanResult){Ie(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=$(vy,e,"autopilot:error",this.deps);if(!r)return;let n=r,{rules:o,fit:i}=t,a=i?.plan??t.plan,d=i?.graph??t.graph,c=i?.scan??t.scanResult,u=this.deps.infraServices?.productionGuard;if(!u){Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Re.code}),E(this.deps,"autopilot:execute","autopilot:error",e,new Error(Re.message),{code:Re.code});return}if(this.writingTargets.has(t.targetOrgId)){E(this.deps,"autopilot:execute","autopilot:error",e,new Error(as.message),{code:as.code});return}this.writingTargets.set(t.targetOrgId,e.id),this.runningRequests.add(e.id);try{await this.executeRun(e,t,{plan:a,graph:d,rules:o,scanResult:c,...i?{fit:i}:{}},n,u)}finally{this.writingTargets.delete(t.targetOrgId),this.runningRequests.delete(e.id)}}async executeRun(e,t,{plan:r,graph:n,rules:o,scanResult:i,fit:a},d,c){if(!this.orchestrator)return;let u=Array.from(i.recordCounts.values()).reduce((H,X)=>H+X,0),l=a?EA(a.report,u,[...t.scanResult?.recordCounts.values()??[]].reduce((H,X)=>H+X,0)):void 0,g=new AbortController,p=()=>{},f=new Promise((H,X)=>{p=ae=>ae===void 0?H():X(ae)});f.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",f,g);let h=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Pe(h),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:u,module:"autopilot"},{check:y,decision:R}=await et(c,m),S=R;if((R==="refused"||R==="declined")&&Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:R,...l?{fit:l}:{}}),R==="refused"){let H=Rn(y.blockedReason??y.impactSummary);E(this.deps,"autopilot:execute","autopilot:error",e,H,{code:xt.blocked}),p(H);return}if(R==="declined"){let H="Operation cancelled by user (confirmation declined).";E(this.deps,"autopilot:execute","autopilot:error",e,new Error(H),{code:xt.declined}),p(new Error(H));return}let w=Bl(r,i.recordCounts,i.personAccounts),O,P;if(d.muteAutomation===!0)try{({mute:O,read:P}=await this.runMute(t.targetOrgId,r))}catch(H){if(!Dt(H))throw H;Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:H.code}),E(this.deps,"autopilot:execute","autopilot:error",e,H,{code:H.code}),p(H);return}let v;if(d.checkpointFirst!==void 0&&w.totalRows>0){P??=await this.readTargetAutomation(t.targetOrgId,r);let H=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:P,mute:O},g.signal);if("refused"in H){Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:zs.CHECKPOINT_REFUSED});let X=new Error(H.refused);E(this.deps,"autopilot:execute","autopilot:error",e,X,{code:zs.CHECKPOINT_REFUSED}),p(X);return}v=H}w.totalRows>0&&(P??=await this.readTargetAutomation(t.targetOrgId,r));let b=await this.targetEmails(t.targetOrgId,r,w,O?O.automation:P),C=new Set(w.objects.map(({objectApiName:H})=>H)),k=(H,X)=>C.has(H)&&Ng(H,X),T=ye(h,t.targetOrgId),x=ye(this.deps.orgManager.getOrg(t.sourceOrgId),t.sourceOrgId),J=P?await dr({read:P,...O?.plan?{plan:O.plan}:{},writes:k,readDeliverability:async()=>m.orgTier==="production"?zt:Gt(await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:T,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,U=await DR({plan:w,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readApiBudgetOf(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:b.checks,...b.unread!==void 0?{emailsUncounted:b.unread}:{},org:T,orgTier:m.orgTier,confirm:H=>c.confirmRun(H),...v?{checkpointFirst:v}:{},readBack:$R(w),mute:Zr(O?.plan),...J?{runEmails:J}:{},source:{org:x,readApiBudget:()=>this.readApiBudgetOf(t.sourceOrgId)}});if(!U.go){Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:U.code,details:to(U.emails)});let H=new Error(U.message),X="source"in U?U.source:void 0;E(this.deps,"autopilot:execute","autopilot:error",e,H,{code:zs[U.code],...X?{extraPayload:{source:{org:x,...X}}}:await this.fitOffer(t,U,w,v)}),p(H);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",u),br({action:"autopilot_execute",orgId:t.targetOrgId,operationId:e.id},U.check.estimateMB),this.executingOperations.add(t.id);let K=new Map,re=!1,N=O?.muted,L=U.checkpoint,B,te=!1,se=H=>{re||(re=!0,Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:H,guard:S,objects:[...K.values()],source:{origin:"org",orgId:t.sourceOrgId},...H==="stopped"?{code:rt}:{},...N?{muted:ut(N)}:{},...B?.state==="taken"?{checkpointId:B.checkpointId}:{},...l?{fit:l}:{},details:to(U.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let Y of r.waves)for(let F of Y.objects)this.sendNodeProgress(e,String(F),"processing",Y.order);let H=new Map;for(let Y of r.waves)for(let F of Y.objects)H.set(String(F),Y.order);let X=O?.prepared?await O.prepared.acquire(e.id).catch(Y=>{if(!Dt(Y))throw Y;return Y}):void 0;if(Dt(X)){L&&(B=await this.settleCheckpoint(L,!1)),re=!0,Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:X.code}),this.liveTracker?.fail(e.id,X.message),E(this.deps,"autopilot:execute","autopilot:error",e,X,{code:X.code,...B?{extraPayload:{checkpoint:B}}:{}}),p(X);return}X&&(N=X.outcome);let ae=X?J?.afterLease(X.outcome,U.emails?.accepted===!0):void 0;if(X&&ae){N=await X.release(),L&&(B=await this.settleCheckpoint(L,!1)),re=!0,Q(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,code:ae.code,muted:ut(N),details:to(U.emails)});let Y=Ob(ae.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),F=new Error(Y);this.liveTracker?.fail(e.id,Y),E(this.deps,"autopilot:execute","autopilot:error",e,F,{code:zs.EMAILS_NOT_ACCEPTED,...B?{extraPayload:{checkpoint:B}}:{}}),p(F);return}te=!0;let ce=await this.orchestrator.executePlan(r,n,o,i.recordCounts,Y=>{let F=String(Y.objectApiName);K.set(F,{...mt(F),...Y.type==="node-completed"?{created:Y.successCount,failed:Y.failureCount}:{created:Y.partialSuccessCount,failed:Y.failureCount??0}});let Z=[...K.values()].reduce((_,de)=>_+de.created+de.failed,0);this.liveTracker?.updateProgress(e.id,u>0?Math.round(Z/u*100):0,Z,u,F),Y.type==="node-completed"?this.sendNodeProgress(e,F,"completed",H.get(F)??0,{recordCount:Y.successCount,failureCount:Y.failureCount,linkedCount:Y.linkedCount,refusals:Y.refusals,apiCallsUsed:Y.apiCallsUsed}):this.sendNodeProgress(e,F,"failed",H.get(F)??0,{recordCount:Y.partialSuccessCount,failureCount:Y.failureCount,linkedCount:Y.linkedCount,refusals:Y.refusals,error:Y.errors[0]??`Execution failed for ${F}`})},g.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...X?{lease:{assigned:X.outcome.assigned.length,giveBack:()=>X.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{X&&(N=await X.release())});L&&(B=await this.settleCheckpoint(L,ce.totalSuccess>0));let be=new Set(ce.completedObjects),Ye=new Set(ce.failedObjects),De=new Set(ce.skippedObjects),_e=new Set(ce.stoppedObjects??[]),z=[],oe=0,ee=[],fe=[];for(let Y of r.waves)for(let F of Y.objects){let Z=String(F),_=ce.objectOutcomes?.[Z],de=ce.statuses?.[Z],Se=ce.lookups?.[Z],Ue=(_?.leftToThePlatform??[]).reduce((Be,Ve)=>Be+Ve.count,0),He={..._?{recordCount:_.written,failureCount:_.failed,linkedCount:_.linked,refusals:_.refusals,...Ue>0?{leftToThePlatform:Ue}:{},..._.currenciesReplaced?{currenciesReplaced:_.currenciesReplaced}:{},..._.pricesSettled?{pricesSettled:_.pricesSettled}:{},..._.recordTypeGiven?{recordTypeGiven:_.recordTypeGiven}:{},..._.cutSinceFit!==void 0?{cutSinceFit:_.cutSinceFit}:{},..._.sentAgainForALock?{sentAgainForALock:_.sentAgainForALock}:{}}:{},...de?{statusesApplied:de.applied,statusRefusals:de.refusals}:{},...Se?{lookupsFilled:Se.filled,lookupRefusals:Se.refusals}:{}};if(be.has(Z))this.sendNodeProgress(e,Z,"completed",Y.order,{recordCount:i.recordCounts.get(Z)??0,failureCount:0,...He});else if(Ye.has(Z))this.sendNodeProgress(e,Z,"failed",Y.order,{...He,error:ce.nodeErrors?.[Z]??`Execution failed for ${Z}`});else if(De.has(Z)){let Be=i.recordCounts.get(Z)??0;K.set(Z,{...mt(Z),skipped:"counted",...Be>0?{notSent:Be}:{}}),this.sendNodeProgress(e,Z,"skipped",Y.order,{recordCount:0,failureCount:0,...Be>0?{notSent:Be}:{}})}else if(_e.has(Z)){let Be=_?.notSent??0;oe+=_?.heldForTheirTask??0,K.set(Z,{...mt(Z),created:_?.written??0,failed:_?.failed??0,...Be>0?{notSent:Be}:{}}),this.sendNodeProgress(e,Z,"stopped",Y.order,{...He,recordCount:_?.written??0,failureCount:_?.failed??0,...Be>0?{notSent:Be}:{}})}let ie=()=>K.get(Z)??{...mt(Z),created:_?.written??0,failed:_?.failed??0},Ee=_?.lookupsLeftEmpty??0,Ne=_?.statusesNotGivenBack??0;if(Ee+Ne>0){let Be={...Ee>0?{lookupsLeftEmpty:Ee}:{},...Ne>0?{statusesNotGivenBack:Ne}:{}};z.push({objectApiName:Z,...Be}),K.set(Z,{...ie(),...Be})}Se?.leftEmpty!==void 0&&(ee.push({objectApiName:Z,records:Se.leftEmpty,refusals:Se.refusals}),K.set(Z,{...ie(),lookupsNotFilled:Se.leftEmpty}));let st=de?.leftDraft??0;de&&st>0&&(fe.push({objectApiName:Z,records:st,refusals:de.refusals}),K.set(Z,{...ie(),statusesNotApplied:st}))}let D=ER(ce);se(ce.stopped?ce.totalSuccess+ce.totalFailure>0?"cancelled":"stopped":D);let W=A(this.deps,e,"autopilot:completed",{status:D,totalRecords:ce.totalSuccess+ce.totalFailure+ce.totalSkipped,totalSuccessCount:ce.totalSuccess,totalFailureCount:ce.totalFailure,totalElapsedMs:ce.elapsedMs,totalApiCalls:0,...N?{mutedAutomation:N}:{},...B?{checkpoint:B}:{},...ce.cutSinceFit!==void 0?{cutSinceFit:ce.cutSinceFit}:{},...ee.length>0?{lookupsNotFilled:ee}:{},...fe.length>0?{statusesNotApplied:fe}:{},...ce.stopped?{stopped:!0,notWritten:ce.stoppedObjects??[],...z.length>0?{leftByStop:z}:{},...oe>0?{emailsHeldForTheirTask:oe}:{}}:{}});this.deps.broker.postToWebview(W),ce.stopped?this.liveTracker?.cancel(e.id):D==="failure"?this.liveTracker?.fail(e.id,ce.fatalError??"No record could be written."):D==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),p()}catch(H){this.liveTracker?.fail(e.id,I(H)),p(H),L&&B===void 0&&(B=await this.settleCheckpoint(L,te)),se("failure"),E(this.deps,"autopilot:execute","autopilot:error",e,H,B?{extraPayload:{checkpoint:B}}:void 0),Ie(this.deps,"error","Autopilot",`Execution failed: ${I(H)}`)}finally{this.executingOperations.delete(t.id)}}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",5e4);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Fi):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",rn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):rn}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Dg).withTimeout("autopilot:limits",()=>Or(cr(t,e)))}catch(t){return{unread:I(t)}}}setMuteLeases(e){this.muteLeases=e}muteLeases={};async runMute(e,t){let r=await this.readTargetAutomation(e,t);return{mute:await this.planMute(e,r),read:r}}planMute(e,t){return Ot(async()=>_t(await q(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:Ng})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(CA).withTimeout("autopilot:automation",()=>r.read(e,Ga(t))).catch(n=>({unread:I(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:kr(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,u="objects"in d?Vr(d,c?.plan,Ng):{firing:[]},l={module:"autopilot",orgId:t,operationId:e.id,written:Ga(r),running:u,request:n},g={operationId:$A(e.id)};try{return{estimate:await a.scope(l,g),take:f=>a.take(l,g,{planned:f,signal:i})}}catch(p){return{refused:kr(p)}}}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return this.deps.log(`[WARN] autopilot:execute: the checkpoint '${e.name}' taken before the run is kept, as it could not be settled (${I(n)})`),e}}async fitOffer(e,t,r,n){if(t.code!=="STORAGE_EXCEEDED"&&t.code!=="API_BUDGET_EXCEEDED")return{};let{targetOrgId:o}=e,{check:i}=t,a=this.deps.orgManager.getOrg(o),d={org:ye(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB,...Ar(i)}};try{let c=await this.planWriteGate(o,r,await this.readTargetDataStorage(o),n?.estimate);return{extraPayload:{...d,writeGate:c}}}catch(c){return this.deps.log(`[WARN] autopilot:execute: what the plan comes to could not be read again (${I(c)})`),{extraPayload:d}}}async readApiBudgetOf(e){let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(Dg).withTimeout("autopilot:limits",()=>ur(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await CR({plan:r,objects:Ga(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new ge(CA).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(Dg).withTimeout("autopilot:limits",()=>Tr(a))}});i.unread!==void 0&&this.deps.log(`[WARN] autopilot:execute: the emails the target's flows send were not counted: ${i.unread} could not be read`);for(let a of i.checks.filter(d=>d.verdict==="unread"))this.deps.log(`[WARN] autopilot:execute: about ${a.emails} ${a.limit} from the target's flows, against a limit that could not be read: ${a.unread??""}`);return i}sendNodeProgress(e,t,r,n,o){let i=A(this.deps,e,"autopilot:node-progress",{nodeId:t,objectName:t,status:r,wave:n,...o??{}});this.deps.broker.postToWebview(i)}hasExecutingOperation(){return this.executingOperations.size>0}handlePause(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);Ie(this.deps,"info","Autopilot","Execution paused.")}catch(t){E(this.deps,"autopilot:pause","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Pause failed: ${I(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.resume();for(let t of this.runningRequests)this.liveTracker?.resume(t);Ie(this.deps,"info","Autopilot","Execution resumed.")}catch(t){E(this.deps,"autopilot:resume","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Resume failed: ${I(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(ky,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),Ie(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){E(this.deps,"autopilot:skip-node","autopilot:error",e,n),Ie(this.deps,"error","Autopilot",`Skip failed: ${I(n)}`)}}handleComplianceReport(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.profile||!t.rules||!t.scanResult){Ie(this.deps,"error","Autopilot","No compliance data available. Run generate-plan first.");return}try{let r=t.fit?.scan??t.scanResult,n=this.orchestrator.generateReport(t.profile,t.rules,r.recordCounts,"","",r.totalObjectsScanned),o=A(this.deps,e,"autopilot:compliance-report",{report:n});this.deps.broker.postToWebview(o)}catch(r){E(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Ie(this.deps,"error","Autopilot",`Report generation failed: ${I(r)}`)}}};import{dirname as Fg}from"node:path";import{AsyncLocalStorage as wj}from"node:async_hooks";var bj=new wj;async function xA(s){let e=new Map;return{result:await bj.run(e,s),sent:e}}function DA(s,e){let t=s.get(e.sourceOrgId)??0,r=e.targetOrgId===e.sourceOrgId?0:s.get(e.targetOrgId)??0;return t+r>0?{source:t,target:r}:void 0}import*as jg from"node:path";var zc="forge:imported-templates",Rj=10,NA="forge",vj=V({folder:j().min(1),templates:ve(mn()),replacing:ve(j())});function gn(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function vi(s,e,t){let r=new Map;for(let i of e)r.has(i.id)||r.set(i.id,i);let n=s.map(i=>t.has(i.id)?r.get(i.id)??i:i),o=new Set(s.map(i=>i.id));for(let[i,a]of r)o.has(i)||n.push(a);return n}function Mg(s,e){return jg.resolve(s)===jg.resolve(e)}function Lg(s){let e=s.get(zc);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=vj.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(gn),replacing:a})}return t}function Gc(s,e){return Lg(s).find(t=>Mg(t.folder,e))}function jA(s,e,t,r){if(t.length===0)return;let n=Lg(s),o=n.findIndex(d=>Mg(d.folder,e)),i=o>=0?n.splice(o,1)[0]:void 0,a=new Map((i?.templates??[]).map(d=>[d.id,d]));for(let d of t)a.set(d.id,d);n.push({folder:i?.folder??e,templates:[...a.values()],replacing:[...new Set([...i?.replacing??[],...r])]}),s.set(zc,n.slice(-Rj),NA)}function MA(s,e){let t=Lg(s).filter(r=>!Mg(r.folder,e));t.length>0?s.set(zc,t,NA):s.delete(zc)}function Sj(s){return{...s.window?{window:{field:s.window.field,...s.window.from!==void 0?{from:s.window.from}:{},...s.window.to!==void 0?{to:s.window.to}:{},...s.window.lastDays!==void 0?{lastDays:s.window.lastDays}:{}}}:{},...s.whereObjects?{whereObjects:[...s.whereObjects]}:{},...s.strataFields?{strataFields:[...s.strataFields]}:{}}}function kj(s){return{seed:s.seed,draw:s.draw,share:s.share,sha256:s.sha256,drawnAt:s.drawnAt,...s.drawnBy?{drawnBy:s.drawnBy}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},...s.roots?{roots:Sj(s.roots)}:{},objects:s.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:e.whole}:{},...e.childrenCut?{childrenCut:e.childrenCut.map(({field:t,rows:r})=>({field:t,rows:r}))}:{},...e.rootsInTheSource!==void 0?{rootsInTheSource:e.rootsInTheSource}:{},...e.rootsInTheDraw!==void 0?{rootsInTheDraw:e.rootsInTheDraw}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...s.leftEmpty?{leftEmpty:s.leftEmpty.map(({objectApiName:e,field:t,rows:r})=>({objectApiName:e,field:t,rows:r}))}:{}}}function LA(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let l of e??[])r.set(l.reason,(r.get(l.reason)??0)+1);let n=[...r].map(([l,g])=>({reason:l,count:g})).sort((l,g)=>g.count-l.count||l.reason.localeCompare(g.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,u=a?.sample?{...a.sample}:void 0;return u&&delete u.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:u?{...a,sample:u}:a}:{},...i?{sample:kj(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var FA="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function _A(s,e){let t=s.flatMap(r=>{let{Id:n,Name:o,Username:i}=r;return typeof n!="string"||typeof o!="string"?[]:[{id:n,name:o,username:typeof i=="string"?i:""}]});return{users:t.slice(0,2e3),truncated:e||t.length>2e3}}var qg=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,ho=j().min(1).max(128),Ij=V({recordId:j().regex(qg,"Invalid Salesforce record ID"),orgId:ho}),Bn=Rf.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=Wu(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=Aj(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function Aj(s){if(s?.plan!==void 0)return{message:"The panel names no plan of a sample: a run takes up the plan of its last simulation of itself. plan must be left out",path:["sample","plan"]};if(s?.maxTotal!==void 0)return{message:"The panel bounds a sample by the data storage it may take, not by its records (the command line\u2019s --max-total). maxTotal must be left out",path:["sample","maxTotal"]}}var Tj=V({config:Bn}),Ej=V({graph:qr,config:Bn,anonymizationRules:_i.optional(),files:Sf.optional(),retryOf:j().min(1).max(200).optional(),reviewSkipped:Ke().optional(),muteAutomation:Ke().optional(),checkpointFirst:om.optional()}).superRefine((s,e)=>{let t=vf(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function Pj(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var UA="FILES_NOT_ACCEPTED",HA="RETRY_UNAVAILABLE",Cj="GRAPH_WITHOUT_EDGES",$j="This graph is the one the history keeps of a clone of the whole org, without the relations between its objects, and cannot be run as it is. Discover the org again from the Forge panel. Nothing was read or written.",xj="WHOLE_ORG_DIRECT",Dj="A clone of the whole org is not started by Clone directly: Review lists what it leaves out and the personal fields it copies as they are. Open Review and execute it from there. Nothing was read or written.",Nj="WHOLE_ORG_REHEARSAL",jj="A clone of the whole org is not rehearsed: a rehearsal holds every row it prepares. Simulate it, which stops at its gate, and its confirmation lists what it writes. Nothing was read or sent.",Mj="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",_g="JOURNAL_UNAVAILABLE",Lj="RESUME_TARGET_UNREAD",fn=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function BA(s){let e=s!==null&&typeof s=="object"&&"code"in s?String(s.code):void 0,t=e==="ENOSPC"||e==="EDQUOT"?"Free some space on that disk":e==="EACCES"||e==="EPERM"||e==="EROFS"?"Let your user write in that folder":"Free some space on that disk, or let your user write in that folder";return{reason:I(s),lift:t}}function Fj(s,e){let t=o=>o.catch(i=>{throw e.err??=i,i}),{serverTime:r,readJob:n}=s;return{queryPages:o=>(async function*(){try{yield*s.queryPages(o)}catch(a){throw e.err??=a,a}})(),userId:()=>t(s.userId()),...r?{serverTime:()=>t(r.call(s))}:{},...n?{readJob:o=>t(n.call(s,o))}:{}}}var Vc="A checkpoint taken before the run takes the org back (Checkpoints \u2192 Rewind\u2026); without one, DataOps \u2192 Emptying \u2192 Empty objects empties its objects, every record of them.",ds="JOURNAL_GONE",_n=`The ids of this run's records were kept in its journal, which is gone: they can no longer be removed, verified, retried against or exported from here. ${Vc}`,cs="RUN_NOT_IN_HISTORY",Ug="REMOVAL_RUNNING",Si="RUN_WRITING",_j="VERIFY_RUNNING",qA="The org this run wrote to is no longer registered. Add the same org again on Organizations, then try again; a sandbox refreshed since is another org, and holds nothing this run wrote.",Uj="RESUME_UNAVAILABLE",WA="remove the records it created (Forge \u2192 History), then run the clone again. Nothing was read or written.",zA="RESUME_TARGET_CHANGED",Hg="RESUME_CHANGED",Hj=V({forgeId:j().min(1).max(200),graph:qr.optional(),config:Bn.optional(),muteAutomation:Ke().optional()}).strict(),GA=new Set(["cancelled","failure","interrupted"]),Un="Forge execution was aborted before it started. Nothing was written.",Bg="FORGE_RUNNING",Bj="FORGE_STOP_AMBIGUOUS",qj={stopped:{code:"DISCOVERY_STOPPED",message:"The discovery was stopped before it finished. Discover again to see the graph."},superseded:{code:"DISCOVERY_SUPERSEDED",message:`The discovery was stopped to make way for a newer one: ${3} discoveries at most are walked at once in this window. Discover again to see the graph.`}},Wj=V({requestId:j().min(1).max(200).optional()}).optional(),zj=V({template:zu}),Gj=V({forgeId:j().min(1).max(200),includeChanged:Ke().optional(),sweep:Ke().optional(),again:Ke().optional(),muteAutomation:Ke().optional(),sweepLate:Ke().optional(),sweepUntied:Ke().optional()}),Jj=V({forgeId:j().min(1).max(200),again:Ke().optional(),sweptObjects:nm.optional()}),Vj=V({forgeId:j().min(1).max(200)}),Kj=V({forgeId:j().min(1).max(200),recordId:j().regex(qg,"Invalid Salesforce record ID")}).strict(),Xj=V({forgeId:j().min(1).max(200)}).strict(),Yj=V({forgeId:j().min(1).max(200)}).strict(),Qj=5e3,Zj=V({templateId:j().min(1).max(200)}),eM=V({graph:qr,config:Bn}),tM=V({framework:j().min(1).max(50),graph:qr,config:Bn,anonymizationRules:_i.optional()}),rM=V({sourceOrgId:ho,targetOrgId:ho,objectApiNames:ve(j().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),nM=V({graph:qr,config:Bn,anonymizationRules:_i.optional()}),oM=V({targetOrgId:ho,graph:qr}),sM=V({graph:qr,config:Bn}),iM=V({orgId:ho}),aM=V({targetOrgId:ho,objectApiNames:ve(j().min(1).max(255)).max(5e3)}),dM=V({graph:qr,config:Bn,muteAutomation:Ke().optional()}).refine(s=>s.config.inputMode==="org",{message:"A sample is drawn from a clone of the whole org alone (inputMode org, depth all)",path:["config","inputMode"]}),cM=V({sourceOrgId:ho,soqlQuery:j().min(1).max(2e4),maxRoots:Te().int().min(1).max(wf).optional()}),uM=[[/Give the most it may take \(--fit-within <MB>\) or the most records \(--max-total <n>\)/g,"Set the MB it may take under Sample settings, on Review,"],[/Lower the bound \(--fit-within or --max-total\), or leave objects out \(--exclude-object\) or narrow them \(--filter\)\./g,"Let it take fewer MB under Sample settings, or leave objects out on Review or narrow them by their filter in Review \u2192 Controls."],[/ Or draw among fewer roots: a window of dates \(--fit-window\) or a filter on the roots of the large objects \(--fit-where\)\./g," Or draw among fewer roots, under Which roots: a window of dates, or a filter on the roots of the large objects."],[/ instead: --fit-where "[^"=]+=([^"]*)"/g," instead, under Which roots: $1"],[/ \(--fit-(?:window|where|strata)\b[^)]*\)/g," (under Which roots)"],[/ \(--exclude-object\)/g," (left out on Review)"],[/--filter leaves records of it out of the copy\./g,"Its filter, in Review \u2192 Controls, leaves records of it out of the copy."]],lM=[[/raise --max-roots \(the sandforge\.forge\.maxRoots setting\)/g,"raise the sandforge.forge.maxRoots setting"],[/raise --max-roots/g,"raise the sandforge.forge.maxRoots setting"]],aT=new Set(["SAMPLE_DRAW_INVALID","SAMPLE_DRAW_EMPTY"]),pM=new Set([...aT,"SAMPLE_STORAGE_UNREAD","SAMPLE_TOO_LARGE"]);function gM(s){if(s.code==="ROOTS_EXCEEDED")return new pt(s.code,lM.reduce((t,[r,n])=>t.replace(r,n),s.message));if(!pM.has(s.code))return s;let e=uM.reduce((t,[r,n])=>t.replace(r,n),s.message);return new pt(s.code,e,void 0,void 0,void 0,{...s.sample?{sample:s.sample}:{}})}var fM="The run to retry cloned the records its query chose, and neither its journal nor its entry in the history keeps them any more: retried, it would write the records its query chooses now, which may be others. Run the clone again from Review.",hM="A sample of the whole org keeps its plan on disk, in the extension\u2019s storage, which this window has none of. Nothing was read or written.",mM=16;function JA(s){let e=s.fit();return e?{fit:e}:{}}function Jc(s,e){let t=0,r=null,n=null,o=a=>{s(...a),t=Date.now(),r=null},i=((...a)=>{r=a;let d=e-(Date.now()-t);d<=0?(n&&(clearTimeout(n),n=null),o(a)):n||(n=setTimeout(()=>{n=null,r&&o(r)},d))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&o(r)},i}function yM(){let s=new Map;return e=>{let t=s.get(e.objectName)??{},r={...t,...typeof e.recordCount=="number"?{recordCount:(t.recordCount??0)+e.recordCount}:{},...typeof e.fieldCount=="number"?{fieldCount:e.fieldCount}:{},...typeof e.createableFieldCount=="number"?{createableFieldCount:e.createableFieldCount}:{}};return s.set(e.objectName,r),{...e,...r}}}function it(s,e,t,r){return $(s,e,t,r)}var wM={holder:s=>gv(s),take:(s,e)=>{let t=pv(s,{...e,ranFrom:"editor"});return"busy"in t?t:{release:()=>t.lock.release()}}};function ki(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Hn(s,e=1){s.requests+=e,s.target!==void 0&&(s.target+=e)}function bM(s,e){let t=new Set,r=e.find(n=>n.forgeId===s);for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.checkpoint?.state==="taken")return r.checkpoint;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function VA(s){return s.successCount+s.updatedCount>0}function KA(s,e){let t=new Set,r=s;for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.undo)return r;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function RM(s){let e=new Set([...s.created,...s.unattributed??[]].flatMap(({ids:r})=>r.map(n=>n.slice(0,15)))),t=new Set(s.remap.withTheirRecord??[]);return s.remap.linked.filter(r=>{let n=s.remap.table[r];return!t.has(r)&&n!==void 0&&e.has(n.slice(0,15))}).length}function vM(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=RM(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>Va?{idRemapTable:{},idRemapExisting:[],idRemapCreated:[],idRemapByObject:s.remap.createdByObject.map(({objectApiName:d,sourceIds:c})=>({objectApiName:d,created:c.length,linked:0})),remapInJournal:!0,...i.length>0?{withTheirRecordCount:i.length}:{}}:{idRemapTable:s.remap.table,idRemapExisting:s.remap.linked,idRemapCreated:s.remap.createdByObject,...i.length>0?{idRemapWithTheirRecord:i}:{}};return{forgeId:s.parts>1?`${s.journalId}-${s.parts-1}`:s.journalId,status:"partial",interrupted:!0,graph:e,duration:0,timestamp:s.partStartedAt,idRemapCount:r,...a,createdCount:t,linkedExistingCount:s.remap.linked.length,...n>0?{linkedToCreatedCount:n}:{},journalId:s.journalId,journalPart:Math.max(0,s.parts-1),...s.endBefore?{retryOf:s.endBefore.forgeId,resumed:!0}:{},...s.runUserId?{runUserId:s.runUserId}:{},...s.checkpoint?{checkpoint:s.checkpoint}:{}}}var SM=new Set(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request","forge:previewRoots"]),XA=3e4,kM=6e4,OM=3e4,IM=6e4,Oi=6e4,AM=12e4;function YA(s){let e=Date.parse(s.writtenBetween?.first??""),t=Date.parse(s.writtenBetween?.last??"");if(Number.isFinite(e)&&Number.isFinite(t))return{from:e,to:t};let r=Date.parse(s.timestamp);return{from:r-Math.max(0,s.duration),to:r}}var QA="The history no longer holds this run: what its id map holds cannot be told from what the target\u2019s automation created, and nothing is swept. Remove its records without the sweep.",TM=6e4,EM=10*6e4,PM=8,CM=8,us=3e4,$M=3e4,ZA="forge:templates",eT="forge:history";function tT(s){return s.runUserId!==void 0&&s.undo!==void 0&&!Bf(s.undo)}function xM(s,e,t){let r=new Set([s]),n=new Set;for(let o=!0;o;){o=!1;let i=a=>{r.has(a)||(r.add(a),o=!0)};for(let a of e)a.journalId!==void 0&&r.has(a.forgeId)&&!n.has(a.journalId)&&(n.add(a.journalId),o=!0);for(let a of n)for(let d of t.get(a)??[])i(d);for(let a of e){a.journalId!==void 0&&n.has(a.journalId)&&i(a.forgeId);let d=a.retryOf;d!==void 0&&(r.has(a.forgeId)?i(d):r.has(d)&&i(a.forgeId))}}return{inLine:r,journals:n}}function DM(s,e,t,r){let n=new Map;for(let i of[...e,...t])i.retryOf!==void 0&&!n.has(i.forgeId)&&n.set(i.forgeId,i.retryOf);let o=i=>{let a=new Set;for(let d=n.get(i);d!==void 0;d=n.get(d)){if(d===s)return!0;if(a.has(d))return!1;a.add(d)}return!1};return e.flatMap(i=>{if(!i.resumed||i.remapInJournal||i.targetOrgId!==r)return[];if(!o(i.forgeId))return[];let a=i.idRemapTable??{},d=(i.idRemapExisting??[]).flatMap(u=>{let l=a[u];return l!==void 0?[l]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:dT(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function dT(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function NM(s,e){let t=[...new Set(s.flatMap(r=>r.keptDependents>0?r.heldBy:[]))];return e.flatMap(r=>{if(r.undo)return[];let n=[...s.map(a=>a.objectApiName),...e.flatMap(a=>a===r?[]:a.objects)],o=Oa(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function jM(s){return s.map(e=>({objectApiName:e.objectApiName,jobId:e.jobId,rows:e.rows,...e.state!==void 0?{state:e.state}:{},...e.processed!==void 0?{processed:e.processed}:{},...e.graceLeftMs!==void 0?{minutesLeft:Math.max(1,Math.ceil(e.graceLeftMs/6e4))}:{}}))}function MM(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function LM(s,e){if(!e||e.calls===0)return MM({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return Gl(e)+r}function FM(s,e){if(!e.journalRead)return;let t=e.callsNotLookedFor??0,r=e.reconciled?.lookedFor??new Set,n=t>0?0:(s??[]).reduce((o,{sourceIds:i})=>o+i.filter(a=>!r.has(a)).length,0);if(!(t===0&&n===0))return{...t>0?{callsAfterRemoval:t}:{},...n>0?{notJournaled:n}:{}}}function _M(s,e){if(!s)return;let t=s.map(r=>({...r}));for(let{objectApiName:r,rows:n}of e){let o=t.find(i=>i.objectApiName===r);o?o.created+=n:t.push({objectApiName:r,created:n,linked:0})}return t}var rT="forge";function UM(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function HM(s){let e=(s.errors??[]).filter(r=>!r.objectApiName.startsWith("__")),t=[...new Set(e.filter(r=>r.failedCount>0||r.skipped).map(r=>r.objectApiName))];return{status:s.status,created:s.createdCount??s.idRemapCount-(s.linkedExistingCount??0),linked:s.linkedExistingCount??0,updated:s.updatedCount??0,failed:e.reduce((r,n)=>r+n.failedCount,0),durationMs:s.duration,...t.length>0?{objectsWithFailures:t.slice(0,20),why:BM(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function BM(s){let e=new Map;for(let t of s){if(t.failedCount===0&&!t.skipped)continue;let r=e.get(t.objectApiName)??new Set;e.set(t.objectApiName,r);let n=t.samples.flatMap(o=>o.messages).map(o=>/^([A-Z][A-Z0-9_]+):/.exec(o)?.[1]).filter(o=>o!==void 0);n.length===0&&r.add(t.stage);for(let o of n)r.add(o)}return Object.fromEntries([...e].slice(0,20).map(([t,r])=>[t,[...r].slice(0,5)]))}function qM(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=db,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=qu(e),a=0;for(let d of t)if(d.recordCountUnknown===!0){if(o===void 0)return{objectName:r,recordCount:"unknown",alsoWrites:n};a+=o,i=!0}else a+=o===void 0?d.recordCount:Math.min(d.recordCount,o);return{objectName:r,recordCount:i?{atMost:a}:a,alsoWrites:n}}function WM(s,e,t){return{forgeId:`forge-${Date.now()}`,status:t.wouldBeRefused.length>0?"failure":"success",graph:s,duration:Date.now()-e,timestamp:new Date().toISOString(),idRemapCount:0,createdCount:0,dryRun:!0,wouldInsertCount:t.totalRows}}function nT(s,e){let t=e.nodes.map(n=>`${n.objectApiName}:${n.included||n.leftOutByUser===!0?1:0}`).sort(),r=e.edges.map(n=>`${n.sourceObject}>${n.targetObject}:${n.required===!0?1:0}`).sort();return JSON.stringify([s,t,r])}function oT(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function zM(s,e){return e.size===0?s:{...s,objectsRead:s.objectsRead.filter(t=>!e.has(t)),objects:s.objects.filter(t=>!e.has(t.objectApiName))}}function sT(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function iT(s,e){return!s.sample||!e||!e.drawnAgain&&!e.ofTheRunRetried?s:{...s,sample:{...s.sample,...e.drawnAgain?{drawnAgain:e.drawnAgain}:{},...e.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}}function GM(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Kc=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function JM(s){return{sampled:s.sampled,judged:s.judged,passed:s.passed,linked:s.linked??0,refused:s.judged-s.passed-(s.linked??0),notJudged:s.notJudged,updatesJudged:s.updatesJudged,updatesRefused:s.updatesJudged-s.updatesPassed,updatesNotRehearsed:s.updatesNotRehearsed,calls:s.calls}}var Xc=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new Mr,this.saveDialog=r??new An}deps;abortController=null;stops=new nv;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;requestsSentTo;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;journalLocks=wM;describeGlobalCache=new Gs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new aa;removing=new Set;trials=new uv;simulations=new Xb;sampleSimulations=new Map;samplePlansSwept=new Set;verifying=new Set;automationReads=new Map;automationReadAgain=new Set;discoverySent=new Map;liveTracker;lastWriteAt=new Map;static DUPLICATE_COOLDOWN_MS=6e4;static MAX_HISTORY=20;externalBrowser;saveDialog;forgetOrg(e){this.describeGlobalCache.invalidate(e),this.orchestrator?.clearDiscoveryCache([e]);for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t)}setForgeOrchestrator(e,t){this.orchestrator=e,t&&(this.planGenerator=t.planGenerator,this.complianceService=t.complianceService,this.metadataDiff=t.metadataDiff,this.targetAutomation=t.targetAutomation,this.targetGaps=t.targetGaps,this.templateStore=t.templateStore,this.removalPlans=t.removalPlans,this.runJournal=t.runJournal,this.requestsSent=t.requestsSent,this.requestsSentTo=t.requestsSentTo,this.muteOrgOf=t.muteOrg,this.muteLeases=t.muteLeases,this.lostBulkJobs=t.lostBulkJobs,this.rehearser=t.rehearser,t.journalLocks&&(this.journalLocks=t.journalLocks))}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}trackRun(e,t,r,n=!1){let o=this.deps.infraServices?.backgroundRegistry;if(!o)return()=>{};let i=()=>{},a=new Promise((c,u)=>{i=l=>{l===void 0?c():u(l instanceof Error?l:new Error(String(l)))}}),d=new AbortController;return d.signal.addEventListener("abort",()=>{r.abort(),n&&this.orchestrator?.abort()},{once:!0}),o.register(e,"forge",t,a,d),i}isWritingTo(e,t){return this.writingTo===e&&(t===void 0||t!==this.executeOperationId)}async handle(e){if(!SM.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"forge:preview":return await this.handleForgePreview(e),!0;case"forge:discover":return await this.handleDiscover(e),!0;case"forge:execute":return await this.handleExecute(e),!0;case"forge:pause":return this.handlePause(e),!0;case"forge:resume":return this.handleResume(e),!0;case"forge:abort":return this.handleAbort(e),!0;case"forge:templates:list":return await this.handleTemplatesList(e),!0;case"forge:templates:save":return await this.handleSaveTemplate(e),!0;case"forge:templates:delete":return await this.handleDeleteTemplate(e),!0;case"forge:history:list":return await this.handleHistoryList(e),!0;case"forge:undo":return await this.handleUndo(e),!0;case"forge:resume-run":return await this.handleResumeRun(e),!0;case"forge:open-record":return await this.handleOpenRecord(e),!0;case"forge:verify:request":return await this.handleVerify(e),!0;case"forge:export-ids:request":return await this.handleExportIds(e),!0;case"forge:plan:request":return await this.handlePlanRequest(e),!0;case"forge:compliance:request":return await this.handleComplianceRequest(e),!0;case"forge:metadata-diff:request":return await this.handleMetadataDiffRequest(e),!0;case"forge:rehearse:request":return await this.handleRehearseRequest(e),!0;case"forge:automation:request":return await this.handleAutomationRequest(e),!0;case"forge:undo-automation:request":return await this.handleUndoAutomation(e),!0;case"forge:undo-sweep:request":return await this.handleUndoSweep(e),!0;case"forge:gaps:request":return await this.handleGapsRequest(e),!0;case"forge:users:request":return await this.handleUsersRequest(e),!0;case"forge:target-records:request":return await this.handleTargetRecordsRequest(e),!0;case"forge:sample-budget:request":return await this.handleSampleBudgetRequest(e),!0;case"forge:previewRoots":return await this.handlePreviewRoots(e),!0;default:return!1}}async loadTemplates(){if(!this.templateStore){let e=this.deps.configStore.get(ZA);return{templates:Array.isArray(e)?e.filter(gn):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Gc(this.deps.configStore,e.workspacePath);if(!t)return{templates:await e.list()};let r;try{r=await e.merge(t.templates,new Set(t.replacing))}catch(n){let o=I(n);return ne.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return MA(this.deps.configStore,e.workspacePath),ne.info("Merged an imported set of forge templates into .sandforge/"),{templates:r}}async saveTemplates(e){if(!this.templateStore){this.deps.configStore.set(ZA,e,rT);return}let t=await this.templateStore.list();for(let r of t.filter(n=>!e.some(o=>o.id===n.id)))await this.templateStore.delete(r.id);for(let r of e)await this.templateStore.save(r)}loadHistory(){return this.deps.configStore.get(eT)??[]}saveHistory(e){this.deps.configStore.set(eT,e,rT)}noteForgeWrite(e){let t=Date.now();for(let[r,n]of this.lastWriteAt)t-n>=s.DUPLICATE_COOLDOWN_MS&&this.lastWriteAt.delete(r);this.lastWriteAt.set(e,t)}async handleForgePreview(e){let t=it(Ij,e,"forge:preview:error",this.deps);if(!t)return;let{recordId:r,orgId:n}=t;try{let o=await q(n,this.deps.orgRegistry,this.deps.orgManager),i=r.substring(0,3),a=this.describeGlobalCache.get(n);if(!a){let w=await o.describeGlobal();xe(o.limitInfo,"forge:preview describeGlobal"),a=w.sobjects.map(O=>({name:O.name,label:O.label,keyPrefix:O.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(w=>w.keyPrefix===i),c=ye(this.deps.orgManager.getOrg(n),n),u=(w,O)=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:preview:error",{code:w,orgName:c,message:O}))};if(!d){u("UNKNOWN_KEY_PREFIX",`No object of ${c} has ids starting "${i}": the record is read from the source org picked.`);return}let l=await Wh(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${rr(r)}' LIMIT 1`);if(xe(o.limitInfo,`forge:preview query ${d.name}`),!l||l.length===0){u("RECORD_NOT_FOUND",`Record ${r} is not in ${c}, or the user connected there cannot see it: the record is read from the source org picked.`);return}let g=l[0],p=new Set(["attributes","Id"]),f=Object.entries(g).filter(([w])=>!p.has(w)).filter(([,w])=>w!=null&&String(w)!=="").slice(0,8).map(([w,O])=>({name:w,value:String(O)})),h=await o.describe(d.name);xe(o.limitInfo,`forge:preview describe ${d.name}`);let m=h.fields.length,y=0;try{y=(await o.query(`SELECT COUNT() FROM ${d.name}`)).totalSize}catch{}let R=y*.001,S=A(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:f,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:R});this.deps.broker.postToWebview(S)}catch(o){E(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){E(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=it(Tj,e,"forge:discover:error",this.deps);if(!t)return;let r=this.withMaxRoots(t.config),n=new AbortController,o=`forge-discover-${this.deps.nextId()}`,{discovery:i,superseded:a}=this.stops.beginDiscovery(e.id,n,o);for(let l of a)this.stopDiscovery(l);Je(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,u=Jc(l=>{let g=A(this.deps,e,"forge:discover:progress",l);this.deps.broker.postToWebview(g)},100);try{ne.info("Forge discover started");let l=this.orchestrator,{result:g,sent:p}=await xA(()=>l.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{u(y)}}));if(u.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let f=DA(p,r),h=oT(r,g);this.discoverySent.delete(h),f&&this.discoverySent.set(h,f);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=CM)break;this.discoverySent.delete(y)}let m=A(this.deps,e,"forge:discover:response",{graph:f?{...g,discoveryRequests:f}:g});this.deps.broker.replyToRequester(m),pe(this.deps,o,{nodeCount:g.nodes?.length??0}),ne.info("Forge discover finished",{objects:g.nodes?.length??0,records:g.totalRecords})}catch(l){if(u.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=l,E(this.deps,"forge:discover","forge:discover:error",e,l,{code:"DISCOVER_ERROR",retryable:!0}),je(this.deps,o,I(l),!0)}finally{d(c),this.stops.endDiscovery(i)}}stopDiscovery(e){this.deps.infraServices?.backgroundRegistry?.abort(e.operationId),e.controller.abort()}answerStoppedDiscovery(e,t){let{code:r,message:n}=qj[t.stop??"stopped"];E(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:it(Ej,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,anonymizationRules:o,files:i,reviewSkipped:a,muteAutomation:d}=r,c=this.withMaxRoots(r.config),u=t?t.forgeId:r.retryOf,l=u!==void 0?bM(u,this.loadHistory()):void 0,g=u===void 0?r.checkpointFirst:void 0;u!==void 0&&r.checkpointFirst!==void 0&&ne.info("Forge run: no checkpoint taken for a retry or a resume, which takes up a run that wrote",{checkpoint:l?.checkpointId??"none"});let p=c.dryRun===!0,f=Xl(n,c),h=Kb(c),m=new lv(c,{reviewSkipped:a===!0,...this.trials.before(f)}),y=c.inputMode==="org",R=y&&c.sample!==void 0,S=($e,Ge)=>{p||Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:$e,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Ge),{code:$e})};if(n.withoutEdges===!0){S(Cj,$j);return}if(y&&a===!0){S(xj,Dj);return}let w=y?ZR(n):void 0;if(w){S(w.code,w.message);return}let O=i?yf(c.anonymizePII,i.acceptedAsIs):null;if(O){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:UA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(O),{code:UA});return}let P,v,b;if(u!==void 0&&!t){let $e=await this.runToRetry(u,c.targetOrgId);if("refused"in $e){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:HA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error($e.refused),{code:HA});return}P=$e.written,v=$e.journalId!==void 0?{journalId:$e.journalId}:{},b=$e.roots}let C=this.deps.infraServices?.productionGuard;if(!C){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:Re.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Re.message),{code:Re.code});return}let k=this.deps.orgManager.getOrg(c.targetOrgId),T=Pe(k),x=ye(k,c.targetOrgId);if(T==="production"){this.refuseAtGate(e,c.targetOrgId,new pt("PRODUCTION_TARGET",`${x} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: Forge writes to those only. Nothing was read or written.`),void 0,m.context());return}let J=await this.ownerMapRefusal(c);if(J){p||Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:J.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,J,{code:J.code,retryable:!0});return}let U={orgId:c.targetOrgId,orgTier:T,operation:"insert",...qM(n,c),module:"forge"},K=new AbortController,re=this.stops.awaitGuard(e.id,K),{check:N,decision:L}=p?Pj(C,U):await et(C,U).finally(re);p&&re();let B=L;if(N.warnings.length>0&&ne.warn("Forge run: Production Guard warnings",{warnings:N.warnings}),(L==="refused"||L==="declined")&&Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,context:m.context()}),L==="refused"){E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${N.blockedReason??N.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(L==="declined"){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(K.signal.aborted){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:bt,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Un),{code:bt,retryable:!0});return}let te=`${c.sourceOrgId}:${c.targetOrgId}:${c.recordId??""}`,se=n.nodes?.map($e=>$e.objectApiName).join(",")??"",H=`forge:${te}:${se}:${n.totalRecords??0}`+(u!==void 0?`:${t?"resume":"retry"}:${u}`:""),X=this.dmlTracker.isDuplicate(H)?this.dmlTracker.get(H):void 0,ae=this.lastWriteAt.get(H),me=ae!==void 0&&Date.now()-ae<s.DUPLICATE_COOLDOWN_MS;if(X?.status==="pending"||me){ne.warn("Duplicate forge execution detected",{operationId:H}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${H}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:Bg,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error("Another Forge run is still under way in this window: start this one once it has ended. A run asked to stop ends once the step under way is done."),{code:Bg,retryable:!0});return}let ce=n.totalRecords??0;X?(X.status="pending",X.recordCount=ce,X.registeredAt=new Date().toISOString()):this.dmlTracker.register(H,"forge","upsert",ce),this.abortController=K;let be=`forge-execute-${this.deps.nextId()}`,Ye=p?"Simulating forge operation":"Executing forge operation";Je(this.deps,be,"forge",Ye);let De=this.trackRun(be,Ye,K,!0);this.liveTracker?.register(be,"forge",Ye),this.executeOperationId=be,this.writingTo=p?null:c.targetOrgId,this.stops.beginRun(e.id,K);let _e=Date.now(),z,oe,ee,fe,D,W=!1,Y=()=>{W||!oe||(W=!0,oe.close())},F={keep:!1},Z=!1,_,de=async()=>{if(!z||Z)return;Z=!0;let $e=z,Ge=F;Y(),await(Ge.keep?this.runJournal?.stop($e,Ge.status,Ge.forgeId):this.runJournal?.end($e))?.catch(Qe=>{ne.warn(`Forge run journal not ${Ge.keep?"kept":"dropped"}: ${I(Qe)}`)}),this.journalsRunning.delete($e),_?.release(),_=void 0},Se={requests:0,target:0},Ue,He,ie=()=>{let $e=this.requestsSent?.();return $e===void 0||Ue===void 0?void 0:Se.requests+$e-Ue},Ee,Ne=!1,st=[],Be,Ve=0,fs=()=>{let $e=this.requestsSentTo?.(c.targetOrgId),Ge=$e===void 0||He===void 0?0:$e-He;return Ve+(this.discoverySent.get(oT(c,n))?.target??0)+(Se.target??0)+Ge},Wn,zn,jt,Ci,hr=[],$i,mo=()=>($i??=this.jobsStillRunning(c.targetOrgId,Ci,Se).then($e=>{hr=$e}),$i),yo,Gn={firing:[]},hs,mr,xi,Ur,Di=!1,Et,hn,Zt=Jc($e=>{let Ge=A(this.deps,e,"forge:progress",$e);this.deps.broker.postToWebview(Ge)},100),wo=Jc($e=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:sampling:progress",{...$e}))},100),Jn=this.liveProgressOf(be,n),Ni=yM(),ji=this.orchestrator.on("forge:progress",$e=>{let Ge=Ni($e),Qe=ie(),at=Qe===void 0?Ge:{...Ge,apiCalls:Qe};Jn(at);let St=at.status;if(St==="done"||St==="error"||St==="skipped"||St==="stopped"){Zt.flush();let nt=A(this.deps,e,"forge:progress",at);this.deps.broker.postToWebview(nt);return}Zt(at)});try{ne.info("Forge execute started",{source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),"unknown org"),target:ye(this.deps.orgManager.getOrg(c.targetOrgId),"unknown org")});let $e=this.maxRecordsPerObject(),Ge=_l(n,{leftOut:new Set(n.nodes.filter(Ji).map(ue=>ue.objectApiName)),retry:u!==void 0}),Qe=new Set(Ge.map(ue=>ue.objectApiName)),at=(ue,Me)=>Me==="insert"||Me==="update"&&Qe.has(ue);if(p){if(g!==void 0||y||R){let ue=await this.automationBeforeTheRun(c.targetOrgId,n);if("automation"in ue){let Me=d===!0?await Ot(()=>this.muteOrg(c.targetOrgId),ue.automation,{...this.muteLeases,writes:at}).then(ot=>ot.plan,ot=>{ne.warn(`Forge simulation: the mute could not be planned (${I(ot)})`)}):void 0;Gn=Vr(ue.automation,Me,at),hs=Me}}}else{let ue=await this.automationBeforeTheRun(c.targetOrgId,n);Ve=$n("automation"in ue?ue.automation:ue);let Me=ue,ot;if(d===!0){let Ae=await Ot(()=>this.muteOrg(c.targetOrgId),"automation"in ue?ue.automation:ue,{...this.muteLeases,writes:at});zn=Ae.prepared,jt=Ae.muted,ot=Ae.plan,"automation"in ue&&Ae.automation&&(Me={...ue,automation:Ae.automation})}if("automation"in ue&&(Gn=Vr(ue.automation,ot,at)),Be=Me,"automation"in Me&&(st=Vf(Me.automation)),K.signal.aborted)throw Ne=!0,new Error(Un);if(m.automationRead(Me,Ge),Ur=await dr({read:"automation"in ue?ue.automation:ue,...ot?{plan:ot}:{},writes:at,applyAssignmentRules:c.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(c.targetOrgId,K.signal),accepted:!1,target:x,run:"clone",keepsAddresses:c.keepContactPoints===!0}),Se.requests+=Ur.ofRun.read?.requests??0,K.signal.aborted)throw Ne=!0,new Error(Un);m.emailsRead(Ur.gate.audit);let Br=await this.confirmAutomation(C,{orgId:c.targetOrgId,org:x,orgTier:T,username:k?.username},Me,Ge,a===!0,Ur.gate.confirmation);Br==="confirmed"&&(m.confirm("automation"),Ur.gate.verdict==="asks"&&(Di=!0,m.confirm("emails"))),B=eo(B,Br);let ht=y?[]:Jb(n,c.maxRecordsPerObject,$e);if(ht.length>0){if(K.signal.aborted)throw Ne=!0,new Error(Un);let Ae=await this.confirmReadCeiling(C,{org:x,orgTier:T,source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId)},ht,$e);Ae==="confirmed"&&m.confirm("volume"),B=eo(B,Ae)}}if(K.signal.aborted)throw Ne=!0,new Error(Un);let St=p?void 0:this.runUserOf(c.targetOrgId),nt=await this.loadRecordTypeMappings(c,K.signal,Se);if(K.signal.aborted)throw Ne=!0,new Error(Un);ee=await St,_e=Date.now(),Ue=this.requestsSent?.(),He=this.requestsSentTo?.(c.targetOrgId),Ci=this.lostBulkJobs?.count;let ct=p?void 0:this.runJournal,Mt;if(ct){let ue=t?.journalId??`forge-run-${_e}`,Me;try{Me=this.journalLocks.take(ct.pathOf(ue),{journalId:ue,target:x,...t?{resumes:!0}:{}})}catch(ht){ne.warn(`Forge run journal: its lock not taken (${I(ht)})`)}if(Me&&"busy"in Me)throw new fn(Si,`${ki(Xa(Me.busy))}: taken up now, two runs would write it; ${Ya(Me.busy)}, then resume it. Nothing was written.`);_=Me,z=ue,this.journalsRunning.add(ue);let ot=ht=>new fn(Lj,`${x} could not be read for the insert calls the run had under way when it stopped (${I(ht)}): taken up without them, the run would write their records twice. Reconnect ${x} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(oe=await(t?ct.resuming(ue).then(async()=>{let ht=await q(c.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(Ct=>{throw ot(Ct)}),Ae={},qe=await ct.reconcile(ue,Fj(Wl(ht),Ae)).catch(Ct=>{throw Ae.err!==void 0?ot(Ae.err):Ct});for(let Ct of zl(qe,x))ne.info(`Forge resume: ${Ct.trim()}`);fe=qe.uncertain,D=qe.underway;let Ze=this.loadHistory().find(Ct=>Ct.forgeId===t.forgeId);Ze&&qe.found.length>0&&await this.withRowsFoundAfterStop(Ze,qe.found)}):ct.begin(ue,c.targetOrgId,new Date(_e),{...this.resumeHeadOf(n,c,o,$e),...d===!0?{muteAutomation:!0}:{},...i?{files:i}:{}},ee)).then(()=>ct.open(ue)).catch(ht=>{ne.warn(`Forge run journal not started: ${I(ht)}`),Mt={err:ht}}),t&&!oe){let ht=Mt?.err;if(ht instanceof fn)throw ht;let{reason:Ae,lift:qe}=BA(ht);throw new fn(_g,`The journal of the run to resume, in ${Fg(ct.pathOf(ue))}, could not be opened (${Ae}). ${qe}, then resume it again. Nothing was written.`)}}if(y&&!p&&!oe){if(!ct||!z||Mt===void 0)throw new fn(_g,Mj);let{reason:ue,lift:Me}=BA(Mt.err);throw new fn(_g,`A clone of the whole org keeps its journal on disk, in ${Fg(ct.pathOf(z))}, which could not be opened (${ue}). ${Me}, then run it again. Nothing was written.`)}R&&(Et=await this.sampleOf({graph:n,config:c,anonymizationRules:o,readCeiling:$e,dryRun:p,...z!==void 0?{journalId:z}:{},resumes:t!==void 0,...v?{retried:v}:{},volumeCase:h,target:x,lookup:Se,room:()=>Hl(Gn,at).perRecord,sentBefore:fs,updatedAfterInsert:[...Qe],onProgress:wo}));let Hr=await this.rootsOfTheRun({graph:n,config:c,anonymizationRules:o,readCeiling:$e,dryRun:p,resumes:t!==void 0,...b?{retried:b}:{},lookup:Se});if(K.signal.aborted)throw Ne=!0,new Error(Un);let Pt,er=y?YR(c):void 0,tr=this.writeGate({guard:C,targetOrgId:c.targetOrgId,operationId:be,org:x,source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),orgTier:T,lookup:Se,emailsPerInsert:st,...Be!==void 0?{automation:Be}:{},...xn(Ur?.ofRun),sentBefore:fs,mute:Zr(zn?.plan??hs),mayBeInTarget:fe,...D&&D.length>0?{jobsUnderway:D}:{},...p?{}:{simulated:this.simulations.of(h)},updatedAfterInsert:[...Qe],automationRoom:()=>Hl(Gn,at).perRecord,...y?{wholeOrg:{source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),sourceOrgId:c.sourceOrgId,graph:n,anonymizePII:c.anonymizePII,...er?{carried:er}:{}}}:{},...g!==void 0?{checkpoint:{ask:{module:"forge",orgId:c.targetOrgId,operationId:be,running:Gn,request:g},own:{operationId:be},signal:K.signal,onEstimate:ue=>{xi=ue},onTaken:ue=>{mr=ue,ct&&z&&oe&&ct.keepCheckpoint(z,ue).catch(Me=>{ne.warn(`Forge run journal: the checkpoint taken first not named (${I(Me)})`)})},onProgress:ue=>{let Me=jo(ue);Fe(this.deps,be,ue,0,0,Me),this.liveTracker?.updateProgress(be,ue,0,0,Me)}}}:{},onSimulated:ue=>{Wn=ue},...R?{sampled:ue=>{wo.flush();let Me=Et?.drawnAgain,ot=Me||Et?.ofTheRunRetried?{...ue,plan:{...ue.plan,...Me?{drawnAgain:Me}:{},...Et?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:ue;return m.sampled(ot),ot}}:y?{onSampleOffer:ue=>{hn=ue}}:{},onConfirmed:()=>{B=eo(B,"confirmed"),m.confirm("volume")}}),M=await this.orchestrator.execute(n,c,{recordTypeMappings:nt,anonymizationRules:o,files:i,writtenBefore:P,stream:{ceiling:$e,...oe?{store:oe,summaryBound:Va}:{},...Et?{sample:Et.stream}:{}},...ee?{runUserId:ee}:{},...Hr?{roots:Hr}:{},beforeWrite:async ue=>{let Me=await tr(ue);if(!zn||ue.dryRun||Pt)return Me;let ot=await zn.acquire(be);Pt=ot,jt=ot.outcome;let Br=Ur?.afterLease(ot.outcome,Di);if(Br)throw new pt(Br.code,Br.message);return{...Me,lease:{assigned:ot.outcome.assigned.length,giveBack:async()=>(await mo(),ot.release())}}}}).catch(ue=>{if(!ev(ue))throw ue;return yo=ue.dryRun,WM(n,_e,ue.dryRun)}).finally(Y).finally(async()=>{Pt&&(await mo(),jt=await Pt.release())}),G=iT(sT(M,Se.requests),Et),ke=(G.remapInJournal===!0||Et!==void 0&&G.status!=="success")&&oe&&z?{journalId:z,journalPart:Math.max(0,oe.partCount-1)}:{},we=jt?{mutedAutomation:jt,...hr.length>0?{bulkJobsPastMute:hr,errors:[...G.errors??[],...Kl(hr)]}:{}}:{},Le=p?xi:mr?await this.settleCheckpoint(mr,(G.createdCount??G.idRemapCount-(G.linkedExistingCount??0))+(G.updatedCount??0)>0):l,he=Le?{checkpoint:Le}:{},Xe=t&&!p&&oe&&z?await this.wroteToEarlierPartsOf(G,z,oe.partCount-1):{},Ce=u!==void 0?{...G,...ke,...we,...he,retryOf:u,...t?{resumed:!0}:{},...Xe}:{...G,...ke,...we,...he};"journalId"in ke&&!p&&(F={keep:!0,status:"success",forgeId:Ce.forgeId});let qt=Ce.createdCount??Ce.idRemapCount-(Ce.linkedExistingCount??0);Ce.status!=="failure"&&qt>0&&this.noteForgeWrite(H),Ce.status==="failure"&&(Ee=new Error("Forge execution finished with a failure status.")),p?(this.trials.note("simulation",f),Wn&&this.simulations.note(h,Wn),Et&&yo?.sample&&this.noteSampleSimulation(h,Et.fingerprint)):(Q(this.deps,{action:"forge_execute",module:"forge",operationId:be,orgId:c.targetOrgId,outcome:Ce.status,guard:B,objects:gl(Ce),source:{origin:"org",orgId:c.sourceOrgId},carried:fl(Ce),...Es(Ce.contactPoints),...JA(m),context:m.context(Ce.decisionsApplied),...jt?{muted:ut(jt)}:{},...Le?.state==="taken"?{checkpointId:Le.checkpointId}:{}}),this.addToHistory(Ce,c)),ne.info("Forge execute finished",HM(Ce)),await de(),wo.flush();let kt=A(this.deps,e,"forge:execute:response",{result:Ce,operationId:be,...yo?{wholeOrgDryRun:yo}:{},...hn?{sampleOffer:hn}:{}});this.deps.broker.postToWebview(kt),this.dmlTracker.markCompleted(H),pe(this.deps,be,{status:Ce.status}),Ce.status==="failure"?this.liveTracker?.fail(be,"Forge execution finished with a failure status."):Ce.status==="partial"?this.liveTracker?.partial(be):this.liveTracker?.complete(be)}catch($e){wo.flush();let Ge=aR($e,t?"resume":"draw")??$e,Qe=za(Ge)?Ge:wR(Ge),at=Dt(Ge)?Ge:void 0;(Qe?.code==="AUTOMATION_DECLINED"||Qe?.code==="READ_DECLINED"||Qe?.code==="WRITE_DECLINED")&&(B=eo(B,"declined"));let St=Ne||GM(Ge)||Qe!==void 0||at!==void 0;St||(Ee=Ge);let nt=Qe||at?void 0:LR(Ge),ct=nt?Bh(nt):void 0,Mt=ct?gl(ct):[],Hr=Ne||Qe||at?"stopped":St?qh(nt,Mt):"failure",Pt=Qe?Qe.code:at?at.code:Ne?bt:Hr==="stopped"?rt:Ge instanceof fn?Ge.code:void 0,er=mr?await this.settleCheckpoint(mr,nt?VA(nt):!(Ne||Qe||at)):l;ne.info("Forge execute stopped",{outcome:Hr,...Pt?{code:Pt}:{},...nt?{created:nt.successCount,linked:nt.linkedCount,failed:nt.failedCount}:{}});let tr=nt&&!p?this.keepStoppedRun(iT(nt,Et),n,c,{startedAt:_e,cancelled:St,retryOf:u,resumed:t!==void 0,callsBefore:Se.requests,...oe&&z?{journalId:z,journalPart:Math.max(0,oe.partCount-1)}:{},...er?{checkpoint:er}:{},...ee?{runUserId:ee}:{},...hr.length>0?{bulkJobsPastMute:hr}:{},...t&&oe&&z?await this.wroteToEarlierPartsOf({idRemapTable:nt.remapTable,idRemapCreated:nt.createdByObject,...nt.remapInJournal?{remapInJournal:!0}:{}},z,oe.partCount-1):{}}):void 0;oe&&z&&tr?F={keep:!0,status:St?"cancelled":"failure",forgeId:tr.forgeId}:t&&(F={keep:!0,...t.end}),p||Q(this.deps,{action:"forge_execute",module:"forge",operationId:be,orgId:c.targetOrgId,outcome:Hr,...Pt?{code:Pt}:{},guard:B,...ct?{objects:Mt,source:{origin:"org",orgId:c.sourceOrgId},carried:fl(ct)}:{},...Es(nt?.contactPoints),...JA(m),context:m.context(nt?.decisionsApplied),...jt?{muted:ut(jt)}:{},...er?.state==="taken"?{checkpointId:er.checkpointId}:{}}),this.dmlTracker.markFailed(H),this.lastWriteAt.delete(H),Et?.adoptedFrom!==void 0&&z!==void 0&&!F.keep&&!(nt&&VA(nt))&&await this.giveThePlanBack(z,Et.adoptedFrom),await de();let M=mr&&er?{checkpoint:er}:{},G=Qe&&za(Qe)?gM(Qe):Ge;E(this.deps,"forge:execute","forge:execute:error",e,G,{code:Pt??(St?rt:"EXECUTE_ERROR"),retryable:!(Qe&&za(Qe)&&aT.has(Qe.code)),...tr?{extraPayload:{result:F.keep?{...tr,resumable:!0}:tr}}:Qe?.stop?{extraPayload:{gate:Qe.stop,...M,...hn?{sampleOffer:hn}:{}}}:mr?{extraPayload:M}:{}}),St?(this.deps.infraServices?.backgroundRegistry?.abort(be),pe(this.deps,be,{aborted:!0}),this.liveTracker?.cancel(be)):(je(this.deps,be,I(Ge),!0),this.liveTracker?.fail(be,I(Ge))),F.keep&&this.liveTracker?.offerResume(be,F.forgeId)}finally{await de(),_?.release(),De(Ee),this.executeOperationId===be&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),ji(),Zt.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?LA(e):e,config:UM(t),targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId},n=[r,...this.loadHistory()];this.saveHistory(n.slice(0,s.MAX_HISTORY)),this.keepRemovalPlans(r,n.slice(s.MAX_HISTORY))}keepStoppedRun(e,t,r,n){if(!(e.remapInJournal?e.successCount>0:e.createdByObject.some(d=>d.sourceIds.length>0)))return;let i=sT(Hh(e,t,{startedAt:n.startedAt,status:n.cancelled?"partial":"failure"}),n.callsBefore),a={...i,...n.cancelled?{cancelled:!0}:{},...n.retryOf!==void 0?{retryOf:n.retryOf}:{},...n.retryOf!==void 0&&n.resumed?{resumed:!0}:{},...n.journalId?{journalId:n.journalId}:{},...n.journalId&&n.journalPart!==void 0?{journalPart:n.journalPart}:{},...n.checkpoint?{checkpoint:n.checkpoint}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.wroteToEarlierParts?{wroteToEarlierParts:n.wroteToEarlierParts}:{},...n.bulkJobsPastMute?{bulkJobsPastMute:n.bulkJobsPastMute,errors:[...i.errors??[],...Kl(n.bulkJobsPastMute)]}:{}};return this.addToHistory(a,r),a}async wroteToEarlierPartsOf(e,t,r){let n=this.runJournal;if(!n||e.remapInJournal||r<1)return{};let o=new Set(zr(e).flatMap(({ids:i})=>i.map(a=>a.slice(0,15))));try{let i=(await n.wroteIn(t,r)).filter(a=>!o.has(a.slice(0,15)));return i.length>0&&i.length<=Va?{wroteToEarlierParts:i}:{}}catch(i){return ne.warn(`Forge run journal not read for what the part wrote: ${I(i)}`),{}}}async ownerMapRefusal(e){let t=e.ownerMappings??{};if(Object.keys(t).length!==0)try{let r=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager);return await MR(t,async n=>(await r.query(n)).records)}catch(r){ne.warn(`Forge run: the users its owners are mapped to could not be read first (${I(r)})`);return}}runUserOf(e){return av(async()=>(await q(e,this.deps.orgRegistry,this.deps.orgManager)).identity(),"forge:execute")}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return ne.warn(`Forge run: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${I(n)})`),e}}async runToRetry(e,t){let r=this.loadHistory(),n=r.find(c=>c.forgeId===e);if(!n)return{refused:"The run to retry is no longer in the history, so what it wrote is not known. Run the clone again from Review."};if(n.targetOrgId!==t)return{refused:"The run to retry wrote to another org than this one."};if(!n.idRemapTable)return{refused:"The run to retry kept no record of what it wrote. Run the clone again from Review."};let o=new Set,i=n;for(;i&&!o.has(i.forgeId);){if(o.add(i.forgeId),i.undo)return{refused:`The records ${i===n?"the run to retry created":"a run it was built on created"} were removed on ${i.undo.removedAt}: there is nothing to retry against. Run the clone again from Review.`};let c=i.retryOf;i=c===void 0?void 0:r.find(u=>u.forgeId===c)}let a=await this.withIdsOf(n);if("gone"in a)return{refused:a.gone};let d=n.roots?await this.rootsOfTheRunRetried(n):void 0;return n.roots&&!d?{refused:fM}:{written:a.entry.idRemapTable??{},...n.journalId!==void 0?{journalId:n.journalId}:{},...d?{roots:d}:{}}}async rootsOfTheRunRetried(e){let t=e.roots;if(!t)return;let r=this.runJournal;if(e.journalId!==void 0&&r){let i=(await r.read(e.journalId).catch(a=>{ne.warn(`Forge retry: the journal of the run retried could not be read (${I(a)})`)}))?.roots;if(i&&i.objectApiName.toLowerCase()===t.objectApiName.toLowerCase()&&xl(i.ids)===i.sha256)return i}if(!t.ids||t.idsLeftOut!==void 0||t.ids.length!==t.asked)return;let n=Nb(t.ids.map(o=>o.source));if(xl(n)===t.sha256)return{objectApiName:t.objectApiName,ids:n,sha256:t.sha256,readAt:t.readAt,...t.query?{query:{...t.query}}:{}}}liveProgressOf(e,t){let r=t.nodes.filter(i=>i.included).length,n=new Set,o=0;return i=>{(i.status==="done"||i.status==="error"||i.status==="skipped")&&!n.has(i.objectName)&&(n.add(i.objectName),o+=i.recordCount??0);let d=r>0?Math.min(100,Math.round(n.size/r*100)):0;this.liveTracker?.updateProgress(e,d,o,0,i.message)}}handlePause(e){this.orchestrator?.pause(),this.executeOperationId&&this.liveTracker?.pause(this.executeOperationId),ne.info("Forge paused")}handleResume(e){this.orchestrator?.resume(),this.executeOperationId&&this.liveTracker?.resume(this.executeOperationId),ne.info("Forge resumed")}handleAbort(e){let t=it(Wj,e,"forge:abort:error",this.deps);if(t===null)return;let r=this.stops.stop(t?.requestId,{discovery:n=>this.stopDiscovery(n),run:()=>{this.executeOperationId&&this.deps.infraServices?.backgroundRegistry?.abort(this.executeOperationId),this.abortController?.abort(),this.abortController=null,this.orchestrator?.abort()}});if("refused"in r){if(r.refused==="none"){ne.info("Forge stop: no operation under way answers it");return}E(this.deps,"forge:abort","forge:abort:error",e,new Error(`${r.live} Forge operations are under way in this window, and the stop did not say which one it was for: nothing was stopped. Stop it from its own screen, or from Live Operations.`),{code:Bj});return}ne.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:t,outcome:"stopped",...n?{guard:n}:{},code:r.code,...o?{context:o}:{}}),E(this.deps,"forge:execute","forge:execute:error",e,r,{code:r.code,retryable:!0,...r.stop?{extraPayload:{gate:r.stop}}:{}})}keepAutomationRead(e,t,r){let n=nT(e,t);this.automationReads.delete(n),this.automationReads.set(n,{orgId:e,at:Date.now(),read:r});for(let o of this.automationReads.keys()){if(this.automationReads.size<=PM)break;this.automationReads.delete(o)}r.catch(()=>{this.automationReads.get(n)?.read===r&&this.automationReads.delete(n)})}readAutomationAgain(e){for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t);this.automationReadAgain.add(e)}async removalMute(e,t,r,n=[],o=!1){let i=this.targetAutomation,a=[...new Set([...Oa(t,n,{userKept:o}),...r])],d=i?await new ge(Oi).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(u=>({unread:I(u)})):{unread:"no reader of the target org's automation is set up"},c=new Set(ir(t));return Ot(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(u,l)=>l==="delete"||l==="update"&&c.has(u)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):_t(await q(e,this.deps.orgRegistry,this.deps.orgManager))}async automationBeforeTheRun(e,t){let r=new Set(t.nodes.filter(d=>!d.included).map(d=>d.objectApiName)),o=this.automationReadAgain.delete(e)?void 0:this.automationReads.get(nT(e,t));if(o&&Date.now()-o.at<EM)try{return{automation:zM(await o.read,r),reused:!0}}catch{}let i=this.targetAutomation;if(!i)return{unread:"no reader of the target org's automation is set up"};let a=new Set(t.nodes.filter(Ji).map(d=>d.objectApiName));try{return{automation:await new ge(Oi).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:I(d)}}}async confirmAutomation(e,t,r,n,o,i={}){let a="automation"in r?r.automation:void 0,d=n.map(y=>y.objectApiName),c=a?Ll(a):[],u=a?Fl(a,d):[],l=a?Ul(a):[{part:"automation",reason:"unread"in r?r.unread:""}];ne.info("Forge target automation before the run",{..."reused"in r?{reused:r.reused}:{},firedOnInsert:c.length,firedOnUpdate:u.length,unread:l.map(y=>y.part)});let g=c.length===0&&u.length===0&&l.length===0,p=a?Kf(a):[],f=i.deliverability!==void 0;if(g&&!f&&!(o&&p.length>0))return"allowed";let h=a&&!g?mR(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:u,updateSteps:hR(n.filter(y=>u.some(R=>R.objectApiName===y.objectApiName))),unread:l,bypass:h,assign:a&&!g?yR(a,h,t.username?{alias:t.org,username:t.username}:void 0):[],...p.length>0?{removal:p}:{},...i});if(m==="confirmed")return"confirmed";throw this.readAutomationAgain(t.orgId),m==="declined"?new pt("AUTOMATION_DECLINED",g&&!f?"Forge execution was cancelled at the confirmation of what may refuse a removal of the records it creates. Nothing was read or written.":"Forge execution was cancelled at the confirmation of what the target org runs as it inserts and updates the records. Nothing was read or written."):new pt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of what the target org runs as it inserts and updates the records, and there was no one to ask. Nothing was read or written.")}async confirmReadCeiling(e,t,r,n){ne.info("Forge read past the ceiling",{ceiling:n,objects:Object.fromEntries(r.slice(0,20).map(i=>[i.objectApiName,i.rows]))});let o=await e.confirmRun({stage:"read",org:t.org,orgTier:t.orgTier,source:t.source,objects:r,ceiling:n});if(o==="confirmed")return"confirmed";throw o==="declined"?new pt("READ_DECLINED","Forge execution was cancelled at the confirmation of the tables it reads with no cap per object. Nothing was read or written.",void 0,n):new pt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of the tables it reads with no cap per object, and there was no one to ask. Nothing was read or written.")}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",Nl);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Fi):Nl}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",rn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):rn}async readTargetEmailLimits(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(us).withTimeout("forge:limits",()=>Tr(t))}catch(t){return{unread:I(t)}}}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(us).withTimeout("forge:limits",()=>Or(cr(t,e)))}catch(t){return{unread:I(t)}}}async readTargetApiBudget(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(us).withTimeout("forge:limits",()=>ur(t))}catch(t){return{unread:I(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new ge(us).withTimeout("forge:limits",()=>ur(r))}catch(r){return{unread:I(r)}}}limitsTransportOf(e,t){return{request:async r=>{t();let n=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(us).withTimeout("forge:limits",()=>n.request(r))}}}async jobsStillRunning(e,t,r){let n=this.lostBulkJobs;if(!n||t===void 0)return[];let o=n.since(t,e);if(o.length===0)return[];ne.info("Forge execute: waiting for the Bulk API jobs the run lost before the mute is given back",{jobs:o.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)});let i=await n.stillRunning(o,()=>{Hn(r)});return i.length>0&&ne.warn("Forge execute: Bulk API jobs still running as the mute is given back; what they write now goes in with the target\u2019s automation",{jobs:i.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)}),i.map(({objectApiName:a,jobId:d})=>({objectApiName:a,...d?{jobId:d}:{}}))}async sampleOf(e){let{config:t}=e,r=this.runJournal?.storagePath;if(r===void 0)throw new Error(hM);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,u,l=h=>{if(!(h instanceof FR))throw h};if(e.dryRun||e.journalId===void 0)i=UR(r,n);else if(e.retried&&!e.resumes){i=Ja(r,e.journalId);let h=e.retried.journalId,m=h!==void 0?await ql.open(Ja(r,h),{fingerprint:n}).catch(l):void 0;m?(a=await WR(m,r,e.journalId),c=!0):d="planGone"}else if(i=Ja(r,e.journalId),!e.resumes){let h=await HR(r,n,o);if(h instanceof ql)a=await BR(h,r,e.journalId).catch(l),a?u=h.dir:d="planTaken";else if(h==="tooOld"||this.samplePlansSwept.has(n))d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await this.sweepSamplePlansOf(r,o);let g;if(!a&&!e.resumes){let h=await this.readSourceApiBudget(t,e.lookup);"unread"in h||(g=h.remaining)}let p=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{Hn(e.lookup);let h=await this.readTargetDataStorage(t.targetOrgId),m=sR({storage:h,bounds:p!==void 0?{withinMB:p}:{},target:e.target});if(m)throw pt.of(m);let y;"unread"in h?(Hn(e.lookup),y=await this.readTargetApiBudget(t.targetOrgId)):y=h.dailyApiRequests;let R="unread"in h?void 0:h.dailyBulkApiBatches,S=Ka({storage:h,...p!==void 0?{withinMB:p}:{},automation:e.room(),allowances:{...y?{requests:y}:{},...R?{bulkBatches:R}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{}}});if(!S)throw new Error("No budget of the sample could be read. Nothing was written.");return S},keepAt:i,fingerprint:n,...a?{plan:a}:{},...g!==void 0?{sourceRequestsLeft:g}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...u!==void 0?{adoptedFrom:u}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await qR(r,e,t).catch(n=>{ne.warn(`Forge sample: the plan of the simulation was not put back (${I(n)})`)})}async sweepSimulationPlans(e=new Date){let t=this.runJournal?.storagePath;t!==void 0&&(await this.sweepSamplePlansOf(t,e),await Vl(t,e).catch(r=>{ne.warn(`Forge roots: the roots of past simulations were not swept (${I(r)})`)}))}async sweepSamplePlansOf(e,t){try{for(let r of await zR(e,t))this.samplePlansSwept.add(r)}catch(r){if(r instanceof _R)for(let n of r.removed)this.samplePlansSwept.add(n);ne.warn(`Forge sample: the plans of past simulations were not all swept (${I(r)})`)}}noteSampleSimulation(e,t){this.samplePlansSwept.delete(t),this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=mM)break;this.sampleSimulations.delete(r)}}writeGate(e){let t=e.checkpoint,r=n=>t&&{...t.ask,written:n.objects.filter(({rows:o})=>o>0).map(o=>o.objectApiName)};return async n=>{let o=e.wholeOrg,i=n.wholeOrg;if(o&&!i)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let a=i?.sample?e.sampled?.(i.sample.report)??i.sample.report:void 0;if(n.dryRun&&o&&i){let{sentBefore:N}=e,L=Ml(n.objects,i);e.onSimulated?.(L);let B=r(L),te;t&&B&&this.beforeRunCheckpoints&&L.totalRows>0&&(te=await this.beforeRunCheckpoints.scope(B,t.own).then(H=>(t.onEstimate(H),H),H=>{ne.warn(`Forge simulation: ${kr(H)}`)}));let se=await oR({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...te?{checkpoint:te}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...N?{sentBefore:()=>({target:N()})}:{},target:{org:e.org,limits:cr(this.limitsTransportOf(e.targetOrgId,()=>Hn(e.lookup)),e.targetOrgId)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,()=>{e.lookup.requests++})},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&se.storage.verdict==="exceeds"){let H=Ka({storage:se.storage});H&&e.onSampleOffer?.(H.budget)}throw ne.info("Forge write gate: the dry run of a clone of the whole org",{records:se.totalRows,objects:se.wouldInsert.length,targetRequests:se.targetRequests.estimate,sourceRequests:se.sourceRequests.estimate,...se.bulkBatches?{bulkBatches:se.bulkBatches.estimate}:{},wouldBeRefused:se.wouldBeRefused.map(H=>H.code)}),new QR(se)}if(n.dryRun){let N=jl(n.objects);e.onSimulated?.(N);let L=r(N);return t&&L&&this.beforeRunCheckpoints&&N.totalRows>0&&await this.beforeRunCheckpoints.scope(L,t.own).then(t.onEstimate,B=>{ne.warn(`Forge simulation: ${kr(B)}`)}),{}}let d=i?eR(i.readWholeOver):void 0;if(d)throw pt.of(d);let c=i?Ml(n.objects,i):jl(n.objects);if(c.totalRows===0)return{};Hn(e.lookup);let u=await this.readTargetDataStorage(e.targetOrgId),l=Ir(c,u,e.automationRoom?nR(c,e.automationRoom()):0);if(a){let N=iR({sample:a,storage:u,target:e.org});if(N)throw pt.of(N)}let g=this.confirmAboveRecords(),p=g>0&&c.totalRows>g?g:void 0,f=sb(e.orgTier),h=f!==void 0&&c.totalRows>f?f:void 0;ne.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(N=>[N.objectApiName,N.rows])),storageEstimateMB:Ws(l.estimateMB),...l.verdict==="unread"?{storageUnread:l.unread}:{storageRemainingMB:l.remainingMB,storageMaxMB:l.maxMB},storage:l.verdict});let m=bR(l,e.org);if(m&&l.verdict==="exceeds"){if(o&&!a&&!("unread"in u)){let L=Ka({storage:u});L&&e.onSampleOffer?.(L.budget)}let N=n.roots&&!o?Db(l,e.org,n.roots):void 0;throw N?pt.of(N):new pt("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(Ws(l.estimateMB)),remainingMB:l.remainingMB,...Ar(l)})}l.verdict==="near"?ne.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):l.verdict==="unread"&&ne.warn("Forge write gate: the data storage the target has left could not be read"),h!==void 0&&ne.warn(`Forge write gate: more than ${h} records, a large volume`);let y=i?tR(i.files,u,e.org):void 0;if(y?.stop)throw pt.of(y.stop);let R;"unread"in u?(Hn(e.lookup),R=await this.readTargetApiBudget(e.targetOrgId)):R=u.dailyApiRequests;let S=r(c),w;if(t&&S){let N=this.beforeRunCheckpoints;if(!N)throw new pt(Cn,kr(new Error("SandForge's checkpoints are not set up in this window")));w=await N.scope(S,t.own).catch(L=>{throw new pt(Cn,kr(L))})}let O=o?await this.readSourceApiBudget(o,e.lookup):void 0,P=rR({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...w?{checkpoint:w}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},budget:R,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in u?u:u.dailyBulkApiBatches,sourceBudget:O,source:o.source}}:{}});if(ne.info("Forge write gate: API requests",{estimate:P.api.estimate,verdict:P.api.verdict,...P.api.verdict==="unread"?{unread:P.api.unread}:{remaining:P.api.remaining,max:P.api.max},...P.api.parts?{parts:P.api.parts}:{}}),P.stop)throw pt.of(P.stop);let v=wa(P.api),b=o&&i&&P.wholeOrg?tv({run:o,measures:i,plan:c,budget:{api:P.api,wholeOrg:P.wholeOrg},...y?.files?{files:y.files}:{},...a?{sample:a,now:Date.now()}:{}}):void 0;b&&ne.info("Forge write gate: a clone of the whole org",{sourceRequests:P.wholeOrg?.source.estimate,sourceApi:P.wholeOrg?.source.verdict,jobs:b.bulk?.jobs??0,...P.wholeOrg?.bulkBatches?{bulkBatches:P.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(b.durationSeconds),managedPackages:b.managedPackages?.length??0,personalAsIs:b.personalAsIs?.length??0});let C=async()=>{let N=this.beforeRunCheckpoints;if(!t||!S||!w||!N)return;let L=w,B=await qa(()=>N.take(S,t.own,{planned:L,signal:t.signal,onProgress:({percentage:te})=>t.onProgress?.(te)}));if("stop"in B)throw B.stop.code===Cn?pt.of({...B.stop,code:Cn}):Object.assign(new Error(B.stop.message),{name:"ForgeAbortedError"});t.onTaken(B.checkpoint)},k=()=>br({action:"forge_execute",orgId:e.targetOrgId,operationId:e.operationId},l.estimateMB),T=[],x=[];if(e.emailsPerInsert.length>0){Hn(e.lookup);for(let N of dR(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))N.verdict==="exceeds"?T.push(lR(N)):N.verdict==="unread"&&x.push(pR(N));x.length>0&&ne.warn("Forge write gate: a daily email limit of the target could not be read",{limits:x.map(({limit:N,emails:L})=>({limit:N,emails:L}))}),T.length>0&&ne.warn("Forge write gate: the records take the target past a daily email limit",{limits:T.map(({limit:N,emails:L,remaining:B})=>({limit:N,emails:L,remaining:B}))})}let J=e.automation===void 0?void 0:"automation"in e.automation?uR(e.automation.automation,cR(c)):`the target's automation: ${e.automation.unread}`;J!==void 0&&ne.warn("Forge write gate: what of the target sends emails could not all be read, and its emails were not counted");let U=(e.mayBeInTarget??[]).filter(({rows:N})=>N>0),K=e.simulated?Yb(e.simulated,c.totalRows):void 0;if(K?.farAbove&&ne.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:K.total}),p===void 0&&l.verdict==="fits"&&T.length===0&&x.length===0&&J===void 0&&U.length===0&&K?.farAbove!==!0&&!P.asks)return await C(),k(),v;let re=await e.guard.confirmRun({stage:"write",...n.roots?{roots:{...n.roots,source:e.source}}:{},org:e.org,orgTier:e.orgTier,objects:c.objects.map(({objectApiName:N,rows:L})=>({objectApiName:N,rows:L})),total:c.totalRows,...p!==void 0?{aboveRecords:p}:{},...h!==void 0?{largeVolume:h}:{},storage:Dn(l),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(N=>N.counted)?{counted:!0}:{},...T.length>0?{emails:T}:{},...x.length>0?{emailsUnread:x}:{},...J!==void 0?{emailsUncounted:J}:{},...Qb(c),...Zb(c),...U.length>0?{mayBeInTarget:U.map(({objectApiName:N,rows:L})=>({objectApiName:N,rows:L}))}:{},...U.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:jM(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...K?{simulated:K}:{},...b?{wholeOrg:b,...P.confirmation.checkpoint?{checkpoint:P.confirmation.checkpoint}:{}}:P.confirmation});if(re==="confirmed")return e.onConfirmed(),await C(),k(),v;throw re==="declined"?new pt("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new pt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation before it wrote the records it had read, and there was no one to ask. Nothing was written.")}}async loadRecordTypeMappings(e,t,r){let n=()=>{},o=new Promise(i=>{n=()=>i(void 0),t.addEventListener("abort",n,{once:!0})});try{let i=new ge($M).withTimeout("forge:record-types",()=>this.readRecordTypeMappings(e,r));return await Promise.race([i,o])}catch(i){ne.warn(`[forge] Record types could not be read from both orgs (${I(i)}); cloned records keep their source RecordTypeId.`);return}finally{t.removeEventListener("abort",n)}}async readRecordTypeMappings(e,t){let[r,n]=await Promise.all([e.sourceOrgId,e.targetOrgId].map(async o=>{let i=await q(o,this.deps.orgRegistry,this.deps.orgManager),a=()=>{o===e.targetOrgId?Hn(t):t.requests++},{records:d}=await or({query:async c=>(a(),i.query(c)),queryMore:async c=>(a(),i.queryMore(c))},kR);return OR(d)}));for(let o of IR(r,n))ne.warn(`[forge] ${AR(o)}`);return new TR().buildMapping(r,n)}async handleTemplatesList(e){let{templates:t,importNotMerged:r}=await this.loadTemplates(),n=A(this.deps,e,"forge:templates:list:response",{templates:t.filter(o=>zu.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=it(zj,e,"forge:templates:save:error",this.deps);if(!t)return;let{template:r}=t;try{let o=[r,...(await this.loadTemplates()).templates.filter(i=>i.id!==r.id)];await this.saveTemplates(o)}catch(o){E(this.deps,"forge:templates:save","forge:templates:save:error",e,o);return}let n=A(this.deps,e,"forge:templates:save:response",{success:!0});this.deps.broker.postToWebview(n)}async handleDeleteTemplate(e){let t=it(Zj,e,"forge:templates:delete:error",this.deps);if(!t)return;let{templateId:r}=t;try{let o=(await this.loadTemplates()).templates.filter(i=>i.id!==r);await this.saveTemplates(o)}catch(o){E(this.deps,"forge:templates:delete","forge:templates:delete:error",e,o);return}let n=A(this.deps,e,"forge:templates:delete:response",{success:!0});this.deps.broker.postToWebview(n)}async handleHistoryList(e){await this.keepRunsLeftOver();let t=this.loadHistory(),r=await this.resumableRuns(t),n=[];try{n=await this.removalPlans?.list()??[]}catch(u){ne.warn(`Forge removal plans could not be read: ${I(u)}`)}let o=await this.journalsPresent([...t.flatMap(u=>u.remapInJournal&&u.journalId?[u.journalId]:[]),...n.flatMap(u=>u.inJournal?[u.inJournal.journalId]:[])]),i=t.map(u=>({...u,...r.has(u.forgeId)?{resumable:!0}:{},...u.remapInJournal&&!(u.journalId&&o.has(u.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(u=>u.forgeId)),d=n.filter(u=>!a.has(u.forgeId)&&Gr(u).length>0).map(u=>u.inJournal&&!o.has(u.inJournal.journalId)?{...u,journalGone:!0}:u);await this.dropJournalsNoLongerNamed(t,n);let c=A(this.deps,e,"forge:history:list:response",{history:i,...d.length>0?{olderRuns:d}:{}});this.deps.broker.postToWebview(c)}async handleUndo(e){let t={};try{await this.undoUnderItsLock(e,t)}finally{t.lock?.release()}}async undoUnderItsLock(e,t){let r=it(Gj,e,"forge:undo:error",this.deps);if(!r)return;let{forgeId:n}=r,o=r.includeChanged===!0,i=r.sweep===!0,a=r.again===!0,d=r.muteAutomation===!0,c=i&&r.sweepLate===!0,u=i&&r.sweepUntied===!0,l=(O,P)=>this.refuseUndo(e,O,P),g=this.loadHistory().find(O=>O.forgeId===n),p=g?void 0:await this.keptRemovalPlan(n),f,h={},m=g?.targetOrgId??p?.targetOrgId,y=g?g.journalId:p?.inJournal?.journalId;if(y){let O=this.journalBusy(y,"remove");if(O){l(O,Si);return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Ug);return}let P=this.lockToRemove(y,m);if(P&&"busy"in P){l(P.busy,Si);return}P&&(t.lock=P)}if(m&&y&&(!g||g.idRemapCreated)){if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Ug);return}this.removing.add(n);try{let O=await this.callsLookedForBeforeRemoval({forgeId:n,targetOrgId:m,journalId:y,removedBefore:(g??p)?.undo!==void 0});if("unread"in O){l(O.unread,"IN_FLIGHT_UNREAD");return}f=O.reconciled,h=O,f&&f.found.length>0&&(g?g=await this.withRowsFoundAfterStop(g,f.found):p&&(p=await this.planWithRowsFoundAfterStop(p,f.found)))}finally{this.removing.delete(n)}}let R,S,w=()=>{};if(g){let O=Date.parse(g.timestamp);if(!g.idRemapCreated||!g.targetOrgId||Number.isNaN(O)){l(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${Vc}`,"NOT_RECORDED");return}let P=g.remapInJournal&&g.journalId&&g.journalPart!==void 0?{journalId:g.journalId,part:g.journalPart}:void 0,v=FM(g.mayHaveBeenWritten,{...h,reconciled:f});if(R={...g,targetOrgId:g.targetOrgId,unreachable:LM(g.mayHaveBeenWritten,f),...v?{notLookedFor:v}:{},...P?{inJournal:P}:{}},g.remapInJournal){if(S=[],a||wn(g).length>0){let b=await this.journalRecordsOf(P,g.undo,a);if("gone"in b){l(b.gone,ds);return}S=b.records,w=b.close}}else S=a?zr(g):bs(g)}else if(p){if(i){l(QA,"SWEEP_UNAVAILABLE");return}R={...p,unreachable:f&&f.calls>0?Gl(f):p.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:O}=p;if(O&&(a||Gr(p).length>0)){let P=await this.journalRecordsOf(O,p.undo,a);if("gone"in P){l(P.gone,ds);return}S=P.records,w=P.close}else S=a?p.objects.map(({objectApiName:P,ids:v})=>({objectApiName:P,ids:[...v]})):tl(p)}else{l("This run is no longer in the Forge history.",cs);return}try{let O=Il(S),P=i&&R.undo!==void 0,v=O===0&&tT(R),b=v&&o;if(O===0&&!P&&!b){R.undo?l(`The records this run created were already removed, on ${R.undo.removedAt}.`+(v?" What that removal kept as changed since the run, the duplicate record sets the target's rules made of them, goes once the records changed since are included.":""),"ALREADY_REMOVED"):l("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Ug);return}this.removing.add(n);let C=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,R,S,{includeChanged:o,again:a,muteAutomation:d,sweepLate:c,sweepUntied:u,...b?{setsAgain:!0}:{},...!i&&g?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},i?g:void 0,C)}finally{this.removing.delete(n),C?.release()}}finally{w()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:_n};try{let o=await n.recordsOf(e.journalId,e.part,r);if(o)return o;let i=await this.planRecordsOf({inJournal:e,...t?{undo:t}:{}},r);return"gone"in i?i:{records:i.records,close:()=>{}}}catch(o){return ne.warn(`Forge run journal could not be read: ${I(o)}`),{gone:_n}}}async journalsPresent(e){let t=this.runJournal;if(e.length===0)return new Set;if(!t)return new Set;try{return await t.present(e)}catch(r){return ne.warn(`Forge run journals could not be listed: ${I(r)}`),new Set(e)}}async dropJournalsNoLongerNamed(e,t){let r=this.runJournal;if(r)try{let n=new Set([...e.map(o=>o.journalId),...t.map(o=>o.inJournal?.journalId),...this.journalsRunning].filter(o=>o!==void 0).map(o=>r.fileNameOf(o)));for(let o of await r.endedFiles())n.has(o)||await r.forgetFile(o)}catch(n){ne.warn(`Forge run journals could not be dropped: ${I(n)}`)}}async withIdsOf(e,t=!1){if(!e.remapInJournal)return{entry:e};let r=this.runJournal;if(!r||!e.journalId||e.journalPart===void 0)return{gone:_n};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:_n};let o=await r.leftOf(e.journalId,e.journalPart),i={...e.removalStamps,...await r.stampsOf(e.journalId,e.journalPart)};return{entry:{...e,idRemapTable:n.table,idRemapExisting:n.existing,idRemapCreated:n.createdByObject,...o?{removalLeft:o}:{},...Object.keys(i).length>0?{removalStamps:i}:{},...t&&n.withTheirRecord?{idRemapWithTheirRecord:n.withTheirRecord}:{}}}}catch(n){return ne.warn(`Forge run journal could not be read: ${I(n)}`),{gone:_n}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:_n};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:_n};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:zr(a)};let d=await r.leftOf(n,o);return{records:bs({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return ne.warn(`Forge run journal could not be read: ${I(n)}`),{gone:_n}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){ne.warn(`Forge removal plans could not be read: ${I(t)}`);return}}async callsLookedForBeforeRemoval(e){let t=this.runJournal,{forgeId:r,journalId:n}=e;if(!t||this.journalsRunning.has(n))return{};try{if((await t.lastEnd(n))?.forgeId!==r)return{};let a=t.callsInFlight(n);if(e.removedBefore)return a>0?{journalRead:!0,callsNotLookedFor:a}:{};if(a===0)return{journalRead:!0}}catch{return{}}let o=ye(this.deps.orgManager.getOrg(e.targetOrgId),e.targetOrgId);try{let i=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await t.reconcile(n,Wl(i));for(let d of zl(a,o,"removal"))ne.info(`Forge removal: ${d.trim()}`);return{reconciled:a,journalRead:!0}}catch(i){return{unread:`${o} could not be read for the insert calls this run had under way when it stopped (${I(i)}): removed without them, the records those calls wrote would stay behind. Nothing was deleted. Reconnect ${o} on Organizations if its session expired, then remove the run again.`}}}async datedByItsJournal(e,t){let r=this.runJournal,{journalId:n,part:o,scope:i}=e;if(!(!r||!n))try{return(await r.present([n])).has(n)?await r.writtenBetween(n,t,o,i):void 0}catch(a){ne.warn(`Forge run not dated from its journal: ${I(a)}`);return}}async withRowsFoundAfterStop(e,t){let r=this.runJournal,{journalId:n,journalPart:o}=e;if(!r||!n||o===void 0)return e;let i=t.reduce((u,{rows:l})=>u+l,0),a=_M(e.idRemapByObject,t),d;if(e.remapInJournal)d={...e,idRemapCount:e.idRemapCount+i,createdCount:(e.createdCount??0)+i,...a?{idRemapByObject:a}:{}};else{let u=await r.idsOf(n,o).catch(()=>{});if(!u)return e;d={...e,idRemapTable:u.table,idRemapExisting:u.existing,idRemapCreated:u.createdByObject,idRemapCount:Object.keys(u.table).length,createdCount:u.createdByObject.reduce((l,{sourceIds:g})=>l+g.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(u=>u.forgeId===d.forgeId?d:u));let c=Gi(d);return c&&await this.removalPlans?.put(c).catch(u=>{ne.warn(`Forge removal plan not kept: ${I(u)}`)}),d}async planWithRowsFoundAfterStop(e,t){let{inJournal:r}=e;if(!r)return e;let n=r.left.map(i=>({...i}));for(let{objectApiName:i,rows:a}of t){let d=n.find(c=>c.objectApiName===i);d?d.count+=a:n.unshift({objectApiName:i,count:a})}let o={...e,inJournal:{...r,left:n}};return await this.removalPlans?.put(o).catch(i=>{ne.warn(`Forge removal plan not kept: ${I(i)}`)}),o}async keepRunsLeftOver(){let e=this.runJournal;if(e)try{let t=new Set(this.journalsRunning);for(let r of await e.leftOver(t)){if(this.journalBusy(r.journalId,"remove")!==void 0)continue;let n=r.resume?.startedWith;if(!n){let o=GR.planOf(r),i=this.removalPlans;o&&i&&await i.putIfAbsent(o),(!o||i)&&await e.forget(r.journalId);continue}if(r.created.length>0||e.callsInFlight(r.journalId)>0){let o=vM(r,n.graph);this.addToHistory(o,n.config),await e.stop(r.journalId,"interrupted",o.forgeId)}else r.endBefore?await e.stop(r.journalId,r.endBefore.status,r.endBefore.forgeId):await e.forget(r.journalId)}}catch(t){ne.warn(`Forge run journals could not be read: ${I(t)}`)}}async resumableRuns(e){let t=new Set,r=this.runJournal;if(!r)return t;for(let n of e)if(!(!n.journalId||this.journalsRunning.has(n.journalId))){try{let o=await r.lastEnd(n.journalId);if(o?.forgeId!==n.forgeId||!GA.has(o.status))continue}catch{continue}KA(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(l=>l.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known. Run the clone again from Review. Nothing was read or written."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:`This run kept no journal to take it up from: ${WA}`,targetOrgId:n};if(this.journalsRunning.has(r.journalId))return{refused:"This run is being taken up already.",targetOrgId:n};let i=this.journalBusy(r.journalId,"resume");if(i)return{refused:i,targetOrgId:n};let a=await o.lastEnd(r.journalId);if(!a||a.forgeId!==r.forgeId||!GA.has(a.status))return{refused:"This run was taken up already, or its run ended: only the last part of a run that stopped can be resumed.",targetOrgId:n};let d=KA(r,t);if(d!==void 0)return{refused:`The records ${d===r?"this run created":"a part of this run created"} were removed on ${d.undo?.removedAt}: there is nothing to resume against.`,targetOrgId:n};let c=await o.head(r.journalId),u=c?.resume?.startedWith;return!c?.resume||!u||c.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${WA}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...c.resume,startedWith:u},targetOrgId:c.targetOrgId,end:a}}async handleResumeRun(e){let t=it(Hj,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,R,S)=>{S&&Q(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:S,outcome:"stopped",code:y}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(R),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(Uj,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,u=this.deps.orgManager.getOrg(d);if(!u){r(zA,"The org this run wrote to is no longer registered in SandForge: add the same org again on Organizations, then resume \u2014 the run checks it is the org it wrote to. Refreshed since, it holds nothing the run wrote: run the clone again. Nothing was read or written.",d);return}if(a.targetSalesforceOrgId!==void 0&&u.orgId&&u.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(zA,`${ye(u,d)} is no longer the org this run wrote to \u2014 refreshed or replaced since: what the run wrote is not there. Run the clone again from Review into it as it is now. Nothing was read or written.`,d);return}let{graph:l,config:g,anonymizationRules:p}=a.startedWith,f=Wu(g);if(f!==void 0){r(Hg,`${f}. Nothing was read or written.`,d);return}let h=this.maxRecordsPerObject(),m=y=>XR(a.fingerprint,y.graph,this.runSetupOf(y.config,p,h,a.targetSalesforceOrgId));if(!m({graph:l,config:g})){r(Hg,"This run would now be set up otherwise than the part it resumes (sandforge.forge.maxRecordsPerObject changed since): put the setting back to take it up, or retry it.",d);return}if(t.graph&&t.config&&!m({graph:t.graph,config:this.withMaxRoots(t.config)})){r(Hg,"The clone on this page is set up otherwise than the run to resume: its objects, filters or decisions changed since.",d);return}await this.handleExecute(e,{forgeId:o.forgeId,journalId:i,head:a,end:c,startedWith:{graph:l,config:g,...p?{anonymizationRules:p}:{},...t.muteAutomation===!0||a.muteAutomation===!0?{muteAutomation:!0}:{},...a.files?{files:a.files}:{}}})}resumeHeadOf(e,t,r,n){let o=this.targetSalesforceOrgIdOf(t);return{sourceOrgId:t.sourceOrgId,fingerprint:this.setupFingerprintOf(e,t,r,n),...o?{targetSalesforceOrgId:o}:{},startedWith:{graph:e,config:t,...r?{anonymizationRules:r}:{}}}}targetSalesforceOrgIdOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId)?.orgId;return t&&qg.test(t)?t:void 0}setupFingerprintOf(e,t,r,n){return this.fingerprintOf(e,t,r,n,this.targetSalesforceOrgIdOf(t))}fingerprintOf(e,t,r,n,o){return KR(e,this.runSetupOf(t,r,n,o))}runSetupOf(e,t,r,n){return{config:{...e,dryRun:void 0},anonymizationRules:t??{},ceiling:e.inputMode==="org"?null:r,targetSalesforceOrgId:n?.slice(0,15)??null}}keepRemovalPlans(e,t){let r=this.removalPlans;if(!r)return;let n=Gi(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=Gi(i);return a&&Gr(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{ne.warn(`Forge removal plan not kept: ${I(i)}`)})}refuseUndo(e,t,r){E(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=it(Kj,e,"forge:open-record:error",this.deps);if(!t)return;let r=(u,l)=>{E(this.deps,"forge:open-record","forge:open-record:error",e,new Error(u),{code:l})},n=this.loadHistory().find(u=>u.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",cs);return}if(!n.targetOrgId){r("This run was recorded before Forge kept the org it wrote to.","NOT_RECORDED");return}let o=await this.withIdsOf(n);if("gone"in o){r(o.gone,ds);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:u,ids:l}of zr(o.entry)){let g=l.find(p=>p.slice(0,15)===i);if(g){a={objectApiName:u,id:g};break}}if(!a){r("This record is not one this run created.","NOT_CREATED");return}let d=this.deps.orgManager.getOrg(n.targetOrgId);if(!d){r(qA,"ORG_NOT_FOUND");return}let c=cc(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let u=c.reason==="not-https"?`its instance URL must use HTTPS, got "${c.protocol}"`:c.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${ye(d)}": ${u}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let u=await this.externalBrowser.open(c.url),l=A(this.deps,e,"forge:open-record:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${u.status}`)}catch(u){E(this.deps,"forge:open-record","forge:open-record:error",e,u)}}async handleVerify(e){let t=it(Xj,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(u,l)=>{E(this.deps,"forge:verify:request","forge:verify:error",e,new Error(u),{code:l})},o=this.loadHistory().find(u=>u.forgeId===r);if(!o){n("This run is no longer in the Forge history.",cs);return}if(o.dryRun===!0){n("A simulation wrote nothing: there is nothing of it to verify.","SIMULATION");return}let i=o.targetOrgId;if(!o.idRemapCreated||!o.idRemapTable||!i){n(`This run was recorded before Forge kept what a run created: its records cannot be verified. ${Vc}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&wn(o).length>0){let u=await this.withIdsOf(o,!0);if("gone"in u){n(u.gone,ds);return}a=u.entry}let d=o.remapInJournal&&a===o?[]:bs(a);if(d.length===0){o.undo?n(`The records this run created were removed, on ${o.undo.removedAt}: there is nothing of it to verify.`,"ALREADY_REMOVED"):n("This run created no record to verify.","NOTHING_TO_VERIFY");return}if(!this.deps.orgManager.getOrg(i)){n(qA,"ORG_NOT_FOUND");return}if(this.verifying.has(r)){n("The records of this run are being verified already: its verdict shows under the run once it ends.",_j);return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let u=await q(i,this.deps.orgRegistry,this.deps.orgManager),l=new mv({target:Yl(u,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),g=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},u),p=await l.verify({records:d,remapTable:a.idRemapTable??{},...g?{runStartedAt:new Date(g.first),runEndedAt:new Date(g.last)}:{runRecordedAt:new Date(o.timestamp)},...a.removalStamps?{removalStamps:a.removalStamps}:{},...o.config?.fieldExclusions?{fieldExclusions:o.config.fieldExclusions}:{},...o.config?.fieldMappings?{fieldMappings:o.config.fieldMappings}:{},writtenWithout:bv(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:wv(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(h=>h.forgeId===r?{...h,verification:p}:h)),Q(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:p.verdict==="verified"?"success":"partial",verdict:p.verdict,details:{forgeId:r,...yv(p)}});let f=A(this.deps,e,"forge:verify:response",{verification:p});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id} verdict=${p.verdict}`)}catch(u){Q(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),E(this.deps,"forge:verify:request","forge:verify:error",e,u,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=it(Yj,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,u)=>{E(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:u})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",cs);return}if(!n.remapInJournal){r("This run keeps its ids in its results: save its Id map from there.","NOT_IN_JOURNAL");return}let o=await this.idMapRowsInJournal(n),i,a=()=>{};if(o)i=o.rows,a=o.close;else{let c=await this.withIdsOf(n);if("gone"in c){r(c.gone,ds);return}i=Wf(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async g=>{await g(zf([]));let p=0,f=[];for(let h of i)f.push(h),!(f.length<Qj)&&(await g(`
|
|
18
|
-
${rl(f)}`),p+=f.length,f=[]);return f.length>0&&await g(`
|
|
19
|
-
${rl(f)}`),p+f.length},["csv"]),u=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,l=A(this.deps,e,"forge:export-ids:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}finally{a()}}async idMapRowsInJournal(e){let t=this.runJournal;if(!(!t||!e.journalId||e.journalPart===void 0))try{return await t.idMapRowsOf(e.journalId,e.journalPart)}catch(r){ne.warn(`Forge run journal could not be read: ${I(r)}`);return}}async verificationSource(e){if(!e)return{unavailable:"This run was recorded before Forge kept the org it read from."};if(!this.deps.orgManager.getOrg(e))return{unavailable:"The org this run read from is no longer registered."};try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return Yl(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${I(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:u}=t,l=Il(r),g=l>0||n.setsAgain===!0,p=(T,x)=>this.refuseUndo(e,T,x),f=this.deps.infraServices?.productionGuard;if(!f){Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",code:Re.code}),p(Re.message,Re.code);return}let h=this.deps.orgManager.getOrg(u),m=Pe(h),{check:y,decision:R}=g?await et(f,{orgId:u,orgTier:m,operation:"delete",objectName:l>0?Al(r).join(", "):ka,recordCount:l>0?l:"unknown",module:"forge"}):{check:void 0,decision:"allowed"};if(y&&(R==="refused"||R==="declined")){Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:R}),R==="refused"?p(`Operation blocked by Production Guard: ${y.blockedReason??y.impactSummary}`,"GUARD_BLOCKED"):E(this.deps,"forge:undo","forge:undo:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(i?.signal.aborted){Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:R,code:bt});let T={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"forge:undo:response",{result:T,operationId:e.id}));return}let S=e.id,w=l>0?`Removing ${l} record(s) a Forge run created`:n.setsAgain?"Removing the duplicate record sets a Forge run\u2019s records went in":"Sweeping what the target\u2019s automation created during a Forge run",O=new AbortController;Je(this.deps,S,"forge",w);let P=this.trackRun(S,w,O);this.liveTracker?.register(S,"forge",w,l);let v,b,C,k;try{let T=await q(u,this.deps.orgRegistry,this.deps.orgManager),{inJournal:x}=t,J=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??x?.journalId,part:t.journalPart??x?.part},T),U={...t.removalStamps,...x?await this.runJournal?.stampsOf(x.journalId,x.part).catch(F=>(ne.warn(`Forge removal stamps not read: ${I(F)}`),{})):{}};l>0&&(b=await this.otherPartsOf(c,u,T));let K=Tl(t.removalSpans,b?.spans);o&&(C=await this.sweepOfRemoval({conn:T,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:K,signal:O.signal,guard:f,orgTier:m,operationId:S,muted:()=>g?void 0:k}));let re=C;await re?.ask();let N=re?.takes??[],L=n.muteAutomation===!0&&(g||N.length>0)?await this.removalMute(u,Al(r),n.setsAgain?[...N,ka]:N,b?.parts.flatMap(F=>F.objects)??[],t.runUserId!==void 0&&l>0):void 0,B;k=L?.muted;let te=async()=>{let F=L?.prepared;!F||O.signal.aborted||(B=await F.acquire(S),k=B.outcome)},H=await(g?qw(Kt(T,"forge:undo"),r,{...J?{runStartedAt:new Date(J.first),runEndedAt:new Date(J.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(U).length>0?{removalStamps:U}:{},...K.length>0?{removalSpans:K}:{},...b&&b.laterParts.length>0?{laterParts:b.laterParts}:{},...re?{sweep:F=>re.first(F),afterRemoval:F=>re.afterRemoval(F),automationMade:re.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...b&&b.parts.length>0?{otherParts:b.parts.map(F=>F.alongside)}:{},includeChanged:a,onUndeletable:Kr(this.deps,u,"forge:undo"),beforeFirstWrite:te,signal:O.signal,onProgress:(F,Z,_)=>{let de=Math.min(100,Math.round(F/Math.max(Z,1)*100));Fe(this.deps,S,de,F,Z,_),O.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(S,de),this.liveTracker?.updateProgress(S,de,F,Z,_)}}):(async()=>(await te(),await re?.first(),await re?.afterRemoval(),Bw))()).finally(async()=>{B&&(k=await B.release())});b&&await this.keepOtherPartStamps(b.parts,H.otherPartStamps??[]);let X=await C?.settle(),ae=d?void 0:t.undo?.removedAt,me=t.unreachable,ce=b?NM(H.objects,b.parts):[],be=(b?.parts??[]).flatMap(F=>F.undo&&F.records>0?[{forgeId:F.forgeId,records:F.records}]:[]),Ye={forgeId:c,status:Ww(H.objects,H.cancelled),includeChanged:a,objects:H.objects,finishedAt:new Date().toISOString(),...ae?{leftBy:ae}:{},...me>0?{mayHaveBeenWritten:me}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...k?{mutedAutomation:k}:{},...ce.length>0?{heldByOtherParts:ce}:{},...be.length>0?{otherPartsLeft:be}:{}};g&&Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:S,orgId:u,outcome:$o(Ye),guard:R,objects:In(Ye.objects),...ae?{leftBy:ae}:{},...k?{muted:ut(k)}:{}});let De={...Ye,status:Co(Ye.status,X),...X?{sweep:X}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&ne.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let _e=zw(De,l,t.undo,d)??(n.setsAgain&&t.undo&&De.status!=="cancelled"?Gw(De,t.undo):void 0),z=X&&iv(X,new Date().toISOString(),o?.sweep),oe=Object.keys(H.stamps).length>0,ee=H.span,fe,D;if(x)(H.objects.some(Z=>Z.deleted+Z.alreadyGone>0)||d&&_e!==void 0)&&(D=await this.runJournal?.keepLeftPages(x.journalId,x.part,H.left()).catch(Z=>{ne.warn(`Forge removal left not kept: ${I(Z)}`)})),oe&&await this.runJournal?.keepStamps(x.journalId,x.part,H.stamps).catch(Z=>{ne.warn(`Forge removal stamps not kept: ${I(Z)}`)});else if((H.gone.length>0||d&&_e)&&!Hw(r)){let F=new Set(H.gone);fe=r.flatMap(({ids:Z})=>Z.filter(_=>!F.has(_)))}if(_e||oe||ee||fe||D||z){let F=Z=>({...Z,..._e?{undo:_e}:{},...z?{sweep:z}:{},...oe&&!x?{removalStamps:{...Z.removalStamps,...H.stamps}}:{},...ee?{removalSpans:[...Z.removalSpans??[],ee]}:{},...fe?{removalLeft:fe}:{}});this.saveHistory(this.loadHistory().map(Z=>Z.forgeId===c?{...F(Z),...D?{removalLeftByObject:D}:{}}:Z)),await this.removalPlans?.update(c,Z=>{let _={...F(Z),...Z.inJournal&&D?{inJournal:{...Z.inJournal,left:D}}:{}};return Gr(_).length>0?_:void 0}).catch(Z=>{ne.warn(`Forge removal plan not updated: ${I(Z)}`)})}let W=A(this.deps,e,"forge:undo:response",{result:De,operationId:S});this.deps.broker.postToWebview(W);let Y=De.status==="failure"?"No record this run created could be removed.":!g&&X&&X.status!=="success"?X.refusal??"The sweep left records in the org.":void 0;De.status==="cancelled"||X?.status==="cancelled"?(pe(this.deps,S,{aborted:!0}),this.liveTracker?.cancel(S)):(pe(this.deps,S,{status:Y&&!g?"failure":De.status}),Y?(v=new Error(Y),this.liveTracker?.fail(S,Y)):De.status==="partial"?this.liveTracker?.partial(S):this.liveTracker?.complete(S))}catch(T){v=T,await C?.settle().catch(J=>{ne.warn(`Forge sweep not recorded: ${I(J)}`)});let x=Dt(T)?T:void 0;Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:S,orgId:u,outcome:x?"stopped":"failure",guard:R,...x?{code:x.code}:{}}),E(this.deps,"forge:undo","forge:undo:error",e,T,{code:x?.code??"UNDO_ERROR",retryable:!0}),pe(this.deps,S,{status:"failure"}),this.liveTracker?.fail(S,I(T))}finally{b?.close(),P(v)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(l=>l.forgeId)),d=(await this.keptRemovalPlans()).filter(l=>!a.has(l.forgeId)),c=l=>DM(l,i,d,t),u=[];for(let l of await this.runLineOf(e,i,d)){let g=i.find(h=>h.forgeId===l),p=g?void 0:d.find(h=>h.forgeId===l);(g??p)?.targetOrgId===t&&u.push((g??p)?.removalSpans??[]);let f=g?await this.otherPartFromEntry(g,t,r,c(l)):await this.otherPartFromPlan(p,t,r,c(l));f&&(f.close&&n.push(f.close),o.push(f.part))}return{parts:o,spans:Tl(...u),laterParts:c(e),close:()=>n.forEach(l=>l())}}async otherPartObjectsOf(e,t){let r=this.loadHistory(),n=new Set(r.map(a=>a.forgeId)),o=(await this.keptRemovalPlans()).filter(a=>!n.has(a.forgeId)),i=new Set;for(let a of await this.runLineOf(e,r,o)){let d=r.find(l=>l.forgeId===a),c=d?void 0:o.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let u=d?wn(d):c?Gr(c):[];for(let{objectApiName:l}of u)i.add(l)}return[...i]}async runLineOf(e,t,r){let n=[...t.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.journalId!==void 0?{journalId:a.journalId}:{}})),...r.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.inJournal?{journalId:a.inJournal.journalId}:{}}))],o=this.runJournal,i=new Map;for(;;){let{inLine:a,journals:d}=xM(e,n,i),c=o?[...d].filter(u=>!i.has(u)):[];if(!o||c.length===0)return[...a].filter(u=>u!==e);for(let u of c)i.set(u,await o.partsOf(u).catch(l=>(ne.warn(`Forge run journal parts not read: ${I(l)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return ne.warn(`Forge removal plans could not be read: ${I(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||wn(e).length===0)return;let o=e.remapInJournal&&e.journalId&&e.journalPart!==void 0?{journalId:e.journalId,part:e.journalPart}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=bs(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:e.journalId,part:e.journalPart},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:wn(e).map(c=>c.objectApiName),records:wn(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||Gr(e).length===0)return;let o=e.inJournal?{journalId:e.inJournal.journalId,part:e.inJournal.part}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=tl(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:o?.journalId,part:o?.part},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:Gr(e).map(c=>c.objectApiName),records:Gr(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async alongside(e,t,r,n,o,i){let a={...n,...o?await this.runJournal?.stampsOf(o.journalId,o.part).catch(()=>({})):{}};return{plan:e,span:dT(t,r),...Object.keys(a).length>0?{removalStamps:a}:{},...i.length>0?{laterParts:i}:{}}}async keepOtherPartStamps(e,t){for(let[r,n]of e.entries()){let o=t[r]??{};if(Object.keys(o).length===0)continue;if(n.inJournal){await this.runJournal?.keepStamps(n.inJournal.journalId,n.inJournal.part,o).catch(a=>{ne.warn(`Forge removal stamps of another part not kept: ${I(a)}`)});continue}let i=a=>({...a,removalStamps:{...a.removalStamps,...o}});this.saveHistory(this.loadHistory().map(a=>a.forgeId===n.forgeId?i(a):a)),await this.removalPlans?.update(n.forgeId,a=>i(a)).catch(a=>{ne.warn(`Forge removal plan not updated: ${I(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return zo({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:nn(t,"forge:undo sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:e.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:n,orgTier:e.orgTier,operation:"delete",module:"forge"},onGuardDecision:(o,i)=>{let a=e.muted();Q(this.deps,{action:"cleanup_delete",module:"forge",operationId:`${e.operationId}-sweep`,orgId:n,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Go(i)}:{},objects:Bo(o),details:qo(o,r.forgeId),...a?{muted:ut(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{ne.warn(`Forge sweep finds not kept: ${I(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=zr(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(g=>g.slice(0,15))),c=this.targetAutomation,u=e.targetOrgId??"",l;if(!c)l={error:"Target automation reader not configured"};else try{l=await new ge(Oi).withTimeout("forge:undo-sweep automation",()=>c.read(u,i.map(g=>g.objectApiName)))}catch(g){l={error:I(g)}}return Wo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:sv(l),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},Kt(t,"forge:undo-sweep copies"))}async sweepPartsBeside(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.forgeId)),n=(await this.keptRemovalPlans()).filter(a=>!r.has(a.forgeId)),o=[],i=0;for(let a of await this.runLineOf(e.forgeId,t,n)){i++;let d=t.find(l=>l.forgeId===a),c=d?void 0:n.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let u;if(d){let l=await this.withIdsOf(d);"gone"in l||(u=zr(l.entry))}else if(c?.inJournal){let l=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in l||(u=l.records)}else c&&(u=c.objects);u&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:u})}return o}async tiesOf(e){let t=e.writtenBetween,r=await this.localRunsOn(e.targetOrgId,t,e.forgeId);e.targetOrgId!==void 0&&r.push(...await this.otherModuleRuns(e.targetOrgId,t).catch(()=>[]));let n=e.mutedAutomation,o=Tv(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:Ov(t,r),...n?.state==="muted"?{muted:{silenced:n.silenced,stillRan:n.stillRan}}:{},...o?{removalBegan:o}:{},...i&&i.length>0?{madeEarlier:i}:{},...a&&a.length>0?{lateEarlier:a}:{}}}async localRunsOn(e,t,r){let n=await this.removalPlans?.list().catch(()=>[]),o=new Set,i=[],a=async(d,c)=>{if(!Iv(t,d))return{ids:[],...d};let u=await c();return u?{ids:u.flatMap(({ids:l})=>l),...d}:{ids:[],idsUntold:!0,...d}};for(let d of this.loadHistory()){if(o.add(d.forgeId),d.forgeId===r||d.targetOrgId!==e)continue;let c=YA(d);i.push(d.remapInJournal?await a(c,async()=>{let u=await this.withIdsOf(d);return"gone"in u?void 0:zr(u.entry)}):{ids:zr(d).flatMap(({ids:u})=>u),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=YA(d),u=d.inJournal;i.push(u?await a(c,async()=>{let l=await this.planRecordsOf({...d,inJournal:u},!0);return"gone"in l?void 0:l.records}):{ids:d.objects.flatMap(({ids:l})=>l),...c})}return i}setOtherModuleRuns(e){this.otherModuleRuns=e}setJournalLocks(e){this.journalLocks=e}journalBusy(e,t){let r=t==="remove"?"Removing its records now would delete under it what it goes on writing; remove them once it has ended.":"Taken up now, two runs would write the same journal; resume it once it has ended.";if(this.journalsRunning.has(e))return`A run of this window still writes this run's journal \u2014 a part that resumes it. ${r} Stop it on the Forge page, or let it end. Nothing was read or written.`;let n=this.runJournal;if(!n)return;let o;try{o=this.journalLocks.holder(n.pathOf(e))}catch(i){return`The lock of this run's journal, in ${Fg(n.pathOf(e))}, could not be read (${I(i)}): whether a run still writes it is not known. Try again once the folder can be read. Nothing was read or written.`}if(o)return`${ki(Xa(o))}. ${r} ${ki(Ya(o))}. Nothing was read or written.`}lockToRemove(e,t){let r=this.runJournal;if(!r)return;let n;try{n=this.journalLocks.take(r.pathOf(e),{journalId:e,...t!==void 0?{target:ye(this.deps.orgManager.getOrg(t),t)}:{},removes:!0})}catch(o){ne.warn(`Forge removal: the lock of the run's journal could not be taken (${I(o)})`);return}return"busy"in n?{busy:`${ki(Xa(n.busy))}. Removing its records now would delete under it what it goes on writing; remove them once it has ended. ${ki(Ya(n.busy))}. Nothing was read or written.`}:n}async handleUndoSweep(e){let t=it(Vj,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(a,d)=>E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(a),{code:d}),n=this.loadHistory().find(a=>a.forgeId===t.forgeId);if(!n){r(QA,cs);return}let o=n.journalId?this.journalBusy(n.journalId,"remove"):void 0;if(o){r(o,Si);return}let i=n.targetOrgId;if(!n.idRemapCreated||!i){r("This run was recorded before Forge kept what a run created: nothing of it can be swept. "+Vc,"NOT_RECORDED");return}try{let a=await new ge(AM).withTimeout("forge:undo-sweep",async()=>{let d=await q(i,this.deps.orgRegistry,this.deps.orgManager),c=await this.sweepInputOf(n,d);return"gone"in c?c:Ho(nn(d,"forge:undo-sweep"),c,n.removalSpans??[])});if("gone"in a){r(a.gone,ds);return}this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:a}))}catch(a){let d=a instanceof Sr;E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,a,{code:d?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){E(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=it(eM,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;Je(this.deps,o,"forge","Generating execution plan");try{ne.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new ge(XA).withTimeout("forge:plan",()=>Promise.resolve(this.planGenerator.generate(i))),d=A(this.deps,e,"forge:plan:response",i===r?{plan:a}:{plan:a,graph:i});this.deps.broker.postToWebview(d),pe(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof Sr;E(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new ge(XA).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return ne.warn(`Forge personal fields not read: ${I(n)}`),e}}async handleComplianceRequest(e){if(!this.complianceService){E(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=it(tM,e,"forge:compliance:error",this.deps);if(!t)return;let{framework:r,graph:n,config:o,anonymizationRules:i}=t,a=`forge-compliance-${this.deps.nextId()}`;Je(this.deps,a,"forge","Generating compliance report");try{ne.info("Forge compliance report generation started");let d=await new ge(OM).withTimeout("forge:compliance",()=>Promise.resolve(this.complianceService.generate(r,n,o,i))),c=A(this.deps,e,"forge:compliance:response",{report:d});this.deps.broker.postToWebview(c),pe(this.deps,a,{framework:r})}catch(d){let c=d instanceof Sr;E(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),pe(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=it(rM,e,"forge:metadata-diff:error",this.deps);if(!t)return;let{sourceOrgId:r,targetOrgId:n,objectApiNames:o}=t,i=`forge-metadata-diff-${this.deps.nextId()}`;Je(this.deps,i,"forge","Comparing metadata schemas");try{ne.info("Forge metadata diff started");let a=await new ge(IM).withTimeout("forge:metadata-diff",()=>this.metadataDiff.compare(r,n,o)),d=A(this.deps,e,"forge:metadata-diff:response",{diffs:a});this.deps.broker.postToWebview(d),ne.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),pe(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof Sr;E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(v,b,C=!1)=>E(this.deps,"forge:rehearse","forge:rehearse:error",e,v,{code:b,retryable:C});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=it(nM,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(jj),Nj);return}let d=(v,b,C={})=>Q(this.deps,{action:"forge_rehearse",module:"forge",operationId:v,orgId:i.targetOrgId,outcome:b,...C}),c=(v,b,C=!1)=>{d(e.id,"stopped",{code:b}),r(v,b,C)},u=this.deps.infraServices?.productionGuard;if(!u){c(new Error(Re.message),Re.code);return}let l=this.deps.orgManager.getOrg(i.targetOrgId),g=Pe(l),p=ye(l,i.targetOrgId);if(g==="production"){c(new Error(`${p} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: a rehearsal creates records in those only. Nothing was read or sent.`),"PRODUCTION_TARGET");return}if(this.rehearseOperationId!==null){c(new Error("A rehearsal is already under way in this window: rehearse once it has ended."),"REHEARSAL_RUNNING",!0);return}if(this.executeOperationId!==null){c(new Error("A Forge run is under way in this window: rehearse once it has ended."),Bg,!0);return}let f=`forge-rehearse-${this.deps.nextId()}`,h="Rehearsing a forge run";this.rehearseOperationId=f,Je(this.deps,f,"forge",h);let m=new AbortController,y=this.trackRun(f,h,m);this.liveTracker?.register(f,"forge",h);let R,S=!1,w=v=>this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:progress",{...v})),O=v=>{if(v.phase!=="rehearsing"||!v.call||!v.calls)return;let b=Math.min(100,Math.round((v.call-1)/v.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(f,b),this.liveTracker?.updateProgress(f,b,v.call-1,v.calls,`call ${v.call} of ${v.calls}`)},P=Jc(w,100);try{let v=await this.automationBeforeTheRun(i.targetOrgId,o),b="automation"in v?v.automation:void 0,C=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),k=await t.rehearse(o,i,{recordTypeMappings:C,anonymizationRules:a,signal:m.signal,onProgress:T=>{if(T.phase==="reading"){P(T);return}P.flush(),w(T),O(T)},confirm:async T=>{let x=await u.confirmRun({stage:"rehearsal",org:p,orgTier:g,rows:T.rows,sampled:T.sampled,updates:T.updates.reduce((J,U)=>J+U.updates,0),calls:T.calls,maxCalls:T.maxCalls,fired:b?Ll(b):[],firedOnUpdate:b?Fl(b,T.updates.map(J=>J.objectApiName)):[],unread:b?Ul(b):[{part:"automation",reason:"unread"in v?v.unread:""}]});if(x==="confirmed"){S=!0;return}throw new Kc(x==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",x==="declined"?"The rehearsal was cancelled at its confirmation. Nothing was sent to the target.":"The rehearsal needed a confirmation, and there was no one to ask. Nothing was sent to the target.")}});this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:response",{rehearsal:k})),this.trials.note("rehearsal",Xl(o,i)),ne.info("Forge rehearsal",{rows:k.rows,sampled:k.sampled,judged:k.judged,passed:k.passed,notJudged:k.notJudged,calls:k.calls,plannedCalls:k.plannedCalls,codes:[...new Set(k.gaps.flatMap(T=>typeof T.detail?.statusCode=="string"?[T.detail.statusCode]:[]))]}),d(f,"success",{guard:S?"confirmed":"allowed",details:JM(k)}),pe(this.deps,f,{status:"success"}),this.liveTracker?.complete(f)}catch(v){let b=v instanceof Kc?v:void 0,C=v instanceof hv?v:void 0,k=v instanceof fv?v:void 0,T=I(v);if(r(v instanceof Error?v:new Error(T),b?.code??(C?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),b||C){let x=b?.code==="REHEARSAL_DECLINED"?"declined":S?"confirmed":void 0;d(f,"stopped",{code:b?.code??"REHEARSAL_CANCELLED",...x?{guard:x}:{},...C?{details:{calls:C.calls}}:{}}),pe(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f)}else R=v,d(f,"failure",{...S?{guard:"confirmed"}:{},...k?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:k.ids.length},objects:k.objects.map(({objectApiName:x,created:J})=>({objectApiName:x,created:J,updated:0,deleted:0,failed:0}))}:{}}),je(this.deps,f,T,!0),this.liveTracker?.fail(f,T)}finally{P.flush(),y(R),this.rehearseOperationId===f&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){E(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=it(oM,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;Je(this.deps,o,"forge","Reading the target org's automation");try{let i=new ge(Oi).withTimeout("forge:automation",()=>this.targetAutomation.readForGraph(r,n));this.keepAutomationRead(r,n,i);let a=await this.withDeliverability(r,n,await i);this.deps.broker.postToWebview(A(this.deps,e,"forge:automation:response",{automation:a})),ne.info("Forge target automation read",{objects:a.objectsRead.length,objectsWithAutomation:a.objects.length,flows:a.objects.reduce((d,c)=>d+c.flows.length,0),triggers:a.objects.reduce((d,c)=>d+c.triggers.length,0),conditionsNotRead:a.conditionsNotRead,unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof Sr;E(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(Un)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new ge(bb).withTimeout("forge:deliverability",async()=>Gt(await q(e,this.deps.orgRegistry,this.deps.orgManager))),n])}finally{t?.removeEventListener("abort",r)}}async withDeliverability(e,t,r){let n=this.deps.orgManager.getOrg(e),o=_l(t,{leftOut:new Set(t.nodes.filter(Ji).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await dr({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Pe(n)==="production"?Promise.resolve(zt):this.readDeliverability(e),accepted:!1,target:ye(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=it(Jj,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(c,u)=>E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),cs);return}let i=o.journalId?this.journalBusy(o.journalId,"remove"):void 0;if(i){r(new Error(i),Si);return}let a=(t.again===!0?qf(o):wn(o)).map(c=>c.objectApiName),d=o.targetOrgId;try{let c=await this.otherPartObjectsOf(t.forgeId,d),u=[...new Set([...Oa(a,c,{userKept:o.runUserId!==void 0}),...a.length===0&&tT(o)?[ka]:[],...t.sweptObjects??[]])],l=await new ge(Oi).withTimeout("forge:undo-automation",()=>n.read(d,u));this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:l,drafted:ir(a)}))}catch(c){let u=c instanceof Sr;E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u?"TIMEOUT":"AUTOMATION_ERROR",retryable:u})}}async handleGapsRequest(e){if(!this.targetGaps){E(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=it(sM,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;Je(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new ge(TM).withTimeout("forge:gaps",()=>o.read(n.sourceOrgId,n.targetOrgId,r,n));this.deps.broker.postToWebview(A(this.deps,e,"forge:gaps:response",{gaps:a})),ne.info("Forge target gaps read",{gaps:a.gaps.length,blocking:a.gaps.filter(d=>d.severity==="blocking").length,kinds:[...new Set(a.gaps.map(d=>d.kind))],unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof Sr;E(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=it(iM,e,"forge:users:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.query(FA);xe(r.limitInfo,"forge:users query");let{users:o,truncated:i}=_A(n.records,n.done===!1);this.deps.broker.postToWebview(A(this.deps,e,"forge:users:response",{orgId:t.orgId,users:o,truncated:i}))}catch(r){E(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=it(aM,e,"forge:target-records:error",this.deps);if(t)try{let r=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await new ge(us).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=_b(n);if(!o)throw new Error("The target org answered its record counts in no form known.");let i=[...new Set(t.objectApiNames)].map(a=>({objectApiName:a,records:o.get(a)??0})).filter(({records:a})=>a>0).sort((a,d)=>d.records-a.records||a.objectApiName.localeCompare(d.objectApiName));this.deps.broker.postToWebview(A(this.deps,e,"forge:target-records:response",{targetOrgId:t.targetOrgId,objects:i}))}catch(r){E(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=it(dM,e,"forge:sample-budget:error",this.deps);if(!t)return;let{graph:r,config:n}=t;try{let[o,i]=await Promise.all([this.readTargetDataStorage(n.targetOrgId),this.readSourceApiBudget(n,{requests:0})]),a=ov({graph:r,options:n.sample,...n.excludedObjects?{excludedObjects:n.excludedObjects}:{},storage:o,source:i,maxRecordsPerObject:this.maxRecordsPerObject()});this.deps.broker.postToWebview(A(this.deps,e,"forge:sample-budget:response",{targetOrgId:n.targetOrgId,budget:a}))}catch(o){E(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}async handlePreviewRoots(e){let t=it(cM,e,"forge:previewRoots:error",this.deps);if(!t)return;let{sourceOrgId:r,soqlQuery:n}=t,o=t.maxRoots??this.maxRoots(),i=$b(n);if("issue"in i){let c=jb(i.issue,void 0);this.deps.broker.postToWebview(A(this.deps,e,"forge:previewRoots:error",{code:c.code,message:c.message,retryable:!1,soqlQuery:n}));return}let{objectApiName:a,query:d}=i;try{let c=await q(r,this.deps.orgRegistry,this.deps.orgManager),u=d.limit!==void 0&&d.limit<=o?d.limit:o+1,{records:l,pages:g}=await new ge(kM).withTimeout("forge:previewRoots",()=>or({query:async p=>c.query(p),queryMore:async p=>c.queryMore(p)},xb(a,d,void 0,o),u));xe(c.limitInfo,`forge:previewRoots ${a}`),this.deps.broker.postToWebview(A(this.deps,e,"forge:previewRoots:response",{sourceOrgId:r,soqlQuery:n,objectApiName:a,cap:o,chosen:Math.min(l.length,o),more:l.length>o,...d.limit!==void 0?{limit:d.limit}:{},...d.orderBy!==void 0?{orderBy:d.orderBy}:{},requests:g}))}catch(c){E(this.deps,"forge:previewRoots","forge:previewRoots:error",e,c,{code:"ROOTS_PREVIEW_ERROR",retryable:!0,extraPayload:{soqlQuery:n}})}}maxRoots(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRoots",Bu);return Cb(typeof e=="number"?e:void 0,Bu)}withMaxRoots(e){return e.inputMode!=="soql"||e.queryScope!=="records"||e.maxRoots!==void 0?e:{...e,maxRoots:this.maxRoots()}}async rootsOfTheRun(e){let{config:t}=e;if(!qu(t)||t.inputMode!=="soql")return;let r=await this.readSourceApiBudget(t,e.lookup),n="unread"in r?void 0:r.remaining,o=n!==void 0?{sourceRequestsLeft:n}:{};if(e.retried&&!e.resumes){let{objectApiName:l,ids:g,sha256:p,readAt:f,query:h}=e.retried;return{...o,plan:{version:1,sourceOrgId:t.sourceOrgId,fingerprint:"",objectApiName:l,...h?{query:h}:{},from:"query",readAt:f,ids:g,sha256:p},planOfTheRunRetried:!0}}let i=this.runJournal?.storagePath;if(i===void 0||e.resumes)return o;await Vl(i,new Date).catch(l=>{ne.warn(`Forge roots: the roots of past simulations were not swept (${I(l)})`)});let d=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),c;try{c=JR(i,d)}catch(l){if(l instanceof Jl)return o;throw l}if(e.dryRun)return{...o,keepAt:c,fingerprint:d};let u;try{u=await VR(c)}catch(l){if(!(l instanceof Jl))throw l;l.fault==="changed"&&ne.warn(`Forge roots: the simulation's roots no longer read whole (${l.message})`)}return{...o,fingerprint:d,...u?{plan:u}:{}}}};import{randomUUID as VM}from"node:crypto";import*as lT from"node:os";import*as _r from"node:path";var cT=50*1024*1024,KM=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),XM="Saved from the SandForge SFDMU Import page",YM=new Set([".json"]);function QM(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!_r.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=_r.resolve(s),n=_r.extname(r).toLowerCase();if(!e.has(n))throw new Error(`Invalid import path: "${n||"(none)"}" is not a supported extension (expected ${[...e].join(", ")}).`);if(!t.some(i=>{let a=_r.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+_r.sep)}return r===a||r.startsWith(a+_r.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function uT(s,e){let t=await s.statSize(e);if(t>cT){let r=(t/1048576).toFixed(1),n=cT/(1024*1024);throw new Error(`Import file is too large: ${r} MB exceeds the ${n} MB limit. Split the file into smaller chunks and retry.`)}}var Yc=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!KM.has(e.type))return!1;switch(e.type){case"migration:pick-file":return await this.handlePickFile(e),!0;case"migration:import-sfdmu":return await this.handleImportSfdmu(e),!0;case"migration:save-sync-config":return this.handleSaveSyncConfig(e),!0;default:return!1}}handleSaveSyncConfig(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Fy,e,"migration:error",this.deps);if(!t)return;let r=n=>{this.deps.broker.postToWebview(A(this.deps,e,"migration:save-sync-config:response",n))};try{let n=t.name.trim();if(n===""){r({success:!1,code:"NAME_REQUIRED"});return}let o=new It(this.deps.configStore);if(ih(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(l=>typeof l=="object"&&l!==null?l.objectApiName:void 0).filter(l=>typeof l=="string").filter(l=>da(l));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=sm.safeParse({...t.config,id:VM(),name:n,description:XM,createdAt:d,updatedAt:d});if(!c.success){let[l]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:l?`${l.path.join(".")}: ${l.message}`:c.error.message});return}let u=c.data;o.save(u),this.deps.log(`[TX] migration:save-sync-config:response saved ${u.id}`),r({success:!0,id:u.id,name:u.name})}catch(n){E(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],lT.homedir()]}async handlePickFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.fileReader;if(!t?.pickExportFile)throw new Error("Migration services not available.");let r=await t.pickExportFile();this.deps.broker.postToWebview(A(this.deps,e,"migration:pick-file:response",r===void 0?{}:{filePath:r}))}catch(t){E(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ly,e,"migration:error",this.deps);if(!t)return;let{filePath:r}=t;try{let n=this.fileReader;if(!n)throw new Error("Migration services not available.");let o=QM(r,YM,this.getAllowedBaseDirs());await uT(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-LNXBCE7E.mjs"),d=new i({readFile:async c=>(c!==o&&await uT(n,c),n.readFile(c))});try{let{config:c,notes:u}=await d.import(o),l=A(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:u});this.deps.broker.postToWebview(l)}catch(c){if(!(c instanceof a))throw c;this.deps.log(`[ERR] migration:import-sfdmu: ${c.message}`),this.deps.broker.postToWebview(A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:c.message,code:c.code,objects:[...c.objects]}))}}catch(n){this.deps.log(`[ERR] migration:import-sfdmu: ${I(n)}`);let o=A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};import*as ls from"node:fs/promises";var hT="settings",pT=V({version:j(),exportedAt:j(),exportedBy:j().optional(),categories:ve(We(["syncMappings","forgePlans","pipelines","anonymizationTemplates",hT])),data:Li(j(),mn())});function gT(s){return s!==hT}var Wg={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},fT={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},Ii="forge:templates";function ZM(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var Qc=class{constructor(e,t){this.configStore=e;this.workspace=t}configStore;workspace;async exportProfile(e,t){try{let r={},n=0;for(let i of e){if(i==="forgePlans"){let u=await this.heldTemplates();r[i]=u.length>0?{[Ii]:u}:{},n+=u.length;continue}let a=Wg[i],d=this.configStore.getKeysByPrefix(a),c={};for(let u of d){let l=this.configStore.get(u);l!==void 0&&(c[u]=l,n++)}r[i]=c}let o={version:"1.0.0",exportedAt:new Date().toISOString(),exportedBy:t,categories:e,data:r};return{success:!0,json:JSON.stringify(o,null,2),categoriesExported:e.length,entriesExported:n}}catch(r){return{success:!1,categoriesExported:0,entriesExported:0,error:r instanceof Error?r.message:String(r)}}}async importProfile(e,t=!0){let r=[];try{let n=JSON.parse(e),o=pT.safeParse(n);if(!o.success)return{success:!1,categoriesImported:0,entriesImported:0,warnings:[],error:`Invalid profile format: ${o.error.issues.map(c=>c.message).join(", ")}`};let i=o.data,a=i.categories.filter(gT),d=0;for(let c of a){let u=i.data[c];if(!u||typeof u!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(u,t,r);continue}let l=Wg[c];for(let[g,p]of Object.entries(u)){if(!g.startsWith(l)){r.push(`Key "${g}" does not match expected prefix "${l}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(g)){r.push(`Key "${g}" already exists, skipped.`);continue}if(this.configStore.set(g,p,fT[c]),d++,c==="pipelines"){let f=vS(this.configStore,g.slice(l.length));f.length>0&&r.push(`Pipeline "${g}" was written over: confirm its Rewind ${f.length===1?"step":"steps"} again.`)}}}return{success:!0,categoriesImported:a.length,entriesImported:d,warnings:r}}catch(n){return{success:!1,categoriesImported:0,entriesImported:0,warnings:r,error:n instanceof Error?n.message:String(n)}}}validateProfile(e){try{let t=JSON.parse(e),r=pT.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(gT)}:{valid:!1,error:r.error.issues.map(n=>n.message).join(", ")}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async listCategories(){let e=[];for(let[t,r]of Object.entries(Wg)){let n=t==="forgePlans"?(await this.heldTemplates()).length:this.configStore.getKeysByPrefix(r).length;e.push({category:t,entryCount:n})}return e}async heldTemplates(){if(!this.workspace){let r=this.configStore.get(Ii);return Array.isArray(r)?r.filter(gn):[]}let e=await this.workspace.readTemplates(),t=Gc(this.configStore,this.workspace.folder);return t?vi(e,t.templates,new Set(t.replacing)):[...e]}async importTemplates(e,t,r){let n=await this.heldTemplates(),o=new Set(n.map(c=>c.id)),i=new Set,a=[],d=[];for(let[c,u]of Object.entries(e)){if(c!==Ii){r.push(`Key "${c}" does not match expected prefix "${Ii}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(u)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let l of u){if(!gn(l)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(l.id)){if(i.add(l.id),o.has(l.id)){if(!t){r.push(`Forge template "${ZM(l)}" already exists, skipped.`);continue}d.push(l.id)}a.push(l)}}}return this.workspace?jA(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(Ii,vi(n,a,new Set(d)),fT.forgePlans),a.length}};import*as zg from"node:path";var Zc=class{deps;filePath;constructor(e){this.deps=e,this.filePath=zg.join(e.workspacePath,".sandforge","forge-templates.json")}async list(){let e;try{e=JSON.parse(await this.deps.readFile(this.filePath))}catch{return[]}return Array.isArray(e)?e.filter(gn):[]}async save(e){let t=await this.list(),r=t.findIndex(n=>n.id===e.id);r>=0?t[r]=e:t.push(e),await this.write(t)}get workspacePath(){return this.deps.workspacePath}async merge(e,t=new Set){let r=await this.list(),n=vi(r,e.filter(gn),t);return JSON.stringify(n)===JSON.stringify(r)?r:(await this.write(n),n)}async delete(e){let r=(await this.list()).filter(n=>n.id!==e);await this.write(r)}async write(e){let t=zg.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var e0=new Set(["config:export","config:import","config:categories","config:validate"]);function t0(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new Zc({workspacePath:e,readFile:r=>ls.readFile(r,"utf-8"),writeFile:(r,n)=>ls.writeFile(r,n,"utf-8"),mkdir:r=>ls.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var eu=class{constructor(e){this.deps=e;this.profileManager=new Qc(e.configStore,t0(e))}deps;profileManager;async handle(e){if(!e0.has(e.type))return!1;switch(e.type){case"config:export":return await this.handleExport(e),!0;case"config:import":return await this.handleImport(e),!0;case"config:categories":return await this.handleCategories(e),!0;case"config:validate":return this.handleValidate(e),!0;default:return!1}}async handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(zy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.exportProfile(r.categories),o=A(this.deps,e,"config:export:response",{success:n.success,json:n.json,categoriesExported:n.categoriesExported,entriesExported:n.entriesExported,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:export:response (${n.entriesExported} entries)`)}catch(n){E(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Gy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.importProfile(r.json,r.overwrite),o=A(this.deps,e,"config:import:response",{success:n.success,categoriesImported:n.categoriesImported,entriesImported:n.entriesImported,warnings:n.warnings,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:import:response (${n.entriesImported} entries)`)}catch(n){E(this.deps,"config:import","config:error",e,n)}}async handleCategories(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=await this.profileManager.listCategories(),r=A(this.deps,e,"config:categories:response",{categories:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] config:categories:response")}catch(t){E(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=this.profileManager.validateProfile(r.json),o=A(this.deps,e,"config:validate:response",{valid:n.valid,categories:n.categories,error:n.error});this.deps.broker.postToWebview(o),this.deps.log("[TX] config:validate:response")}catch(n){E(this.deps,"config:validate","config:error",e,n)}}};var r0=V({metric:j(),operator:We(["gt","gte","lt","lte","eq","neq"]),threshold:Te(),warningThreshold:Te().optional()}),n0=V({id:j(),name:j(),description:j(),category:We(["security","performance","compliance","custom"]),condition:r0,remediation:j(),enabled:Ke()}),Ai=V({id:j(),name:j(),description:j(),rules:ve(n0),createdAt:j(),updatedAt:j()});function mT(s,e,t){switch(e){case"gt":return s>t;case"gte":return s>=t;case"lt":return s<t;case"lte":return s<=t;case"eq":return s===t;case"neq":return s!==t}}var tu=class s{evaluateRule(e,t){let{metric:r,operator:n,threshold:o,warningThreshold:i}=e.condition;if(!Object.prototype.hasOwnProperty.call(t,r))return{ruleId:e.id,ruleName:e.name,category:e.category,status:"unknown",actualValue:null,threshold:o,message:`${e.name}: not measured \u2014 SandForge reads no ${r} value for this org`,remediation:""};let a=t[r],d="pass";mT(a,n,o)?d="fail":i!==void 0&&mT(a,n,i)&&(d="warning");let c=d==="pass"?`${e.name}: compliant (${a})`:`${e.name}: ${d} \u2014 actual ${a} ${n} ${d==="fail"?o:i??o}`;return{ruleId:e.id,ruleName:e.name,category:e.category,status:d,actualValue:a,threshold:o,message:c,remediation:d==="pass"?"":e.remediation}}evaluatePolicy(e,t){let n=e.rules.filter(a=>a.enabled).map(a=>this.evaluateRule(a,t)),o=s.computeComplianceScore(n),i=n.filter(a=>(a.status==="fail"||a.status==="warning")&&a.remediation).map(a=>a.remediation);return{policyId:e.id,policyName:e.name,evaluatedAt:new Date().toISOString(),complianceScore:o,ruleResults:n,remediations:i}}static computeComplianceScore(e){let t=e.filter(o=>o.status!=="unknown");if(t.length===0)return null;let r={pass:100,warning:50,fail:0},n=t.reduce((o,i)=>o+r[i.status],0);return Math.round(n/t.length)}};var ru="governance:policy:",o0="governance",Ti=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(ru),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=Ai.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${ru}${e}`);if(!t)return;let r=Ai.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${ru}${e.id}`,e,o0)}delete(e){return this.configStore.delete(`${ru}${e}`)}static getDefaultTemplates(){let e=new Date().toISOString();return[{id:"template-security",name:"Security Policy",description:"Default security governance rules",rules:[{id:"sec-mfa",name:"MFA Enabled",description:"Multi-factor authentication should be enabled for all users",category:"security",condition:{metric:"mfaEnabledPercent",operator:"lt",threshold:100,warningThreshold:90},remediation:"Enable MFA for all user profiles in Setup > Identity Verification",enabled:!0},{id:"sec-password",name:"Password Policy Strength",description:"Password policy should enforce minimum complexity",category:"security",condition:{metric:"passwordPolicyScore",operator:"lt",threshold:60,warningThreshold:80},remediation:"Strengthen password policy in Setup > Password Policies",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-performance",name:"Performance Policy",description:"Default performance governance rules",rules:[{id:"perf-api",name:"API Usage Limit",description:"API usage should stay below critical thresholds",category:"performance",condition:{metric:"apiUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Optimize API-heavy integrations or request a limit increase",enabled:!0},{id:"perf-storage",name:"Storage Usage",description:"Data storage should not exceed safe limits",category:"performance",condition:{metric:"storageUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Archive old records or increase storage allocation",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-compliance",name:"Compliance Policy",description:"Default compliance governance rules",rules:[{id:"comp-coverage",name:"Code Coverage",description:"Apex code coverage must meet minimum threshold",category:"compliance",condition:{metric:"codeCoveragePercent",operator:"lt",threshold:75,warningThreshold:85},remediation:"Write additional unit tests to increase code coverage",enabled:!0}],createdAt:e,updatedAt:e}]}};var s0={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},i0=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),nu=class{constructor(e,t){this.deps=e;this.store=new Ti(e.configStore),this.engine=new tu,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!i0.has(e.type))return!1;switch(e.type){case"governance:policies:list":return this.handlePoliciesList(e),!0;case"governance:policy:save":return this.handlePolicySave(e),!0;case"governance:policy:delete":return this.handlePolicyDelete(e),!0;case"governance:evaluate":return await this.handleEvaluate(e),!0;case"governance:templates":return this.handleTemplates(e),!0;default:return!1}}handlePoliciesList(e){try{let r=this.store.getAll().map(o=>({id:o.id,name:o.name,description:o.description,ruleCount:o.rules.length,createdAt:o.createdAt,updatedAt:o.updatedAt})),n=A(this.deps,e,"governance:policies:result",{policies:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policies:result")}catch(t){E(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=$(Hy,e,"governance:error",this.deps);if(t)try{let r=Ai.safeParse(t.policy);if(!r.success){E(this.deps,"governance:policy:save","governance:error",e,new Error(`Validation failed: ${r.error.message}`),{code:"VALIDATION_ERROR"});return}this.store.save(r.data);let n=A(this.deps,e,"governance:policy:save:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:save:response")}catch(r){E(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=$(Uy,e,"governance:error",this.deps);if(t)try{let r=this.store.delete(t.policyId),n=A(this.deps,e,"governance:policy:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:delete:response")}catch(r){E(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=$(By,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){E(this.deps,"governance:evaluate","governance:error",e,new Error(`Policy not found: ${r.policyId}`),{code:"NOT_FOUND"});return}let i=await(await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager)).request(`/services/data/${Ro}/limits`),a={};for(let[u,{Max:l,Remaining:g}]of Object.entries(i))a[u]=l>0?Math.round((l-g)/l*100):0;for(let[u,l]of Object.entries(s0))l in a&&(a[u]=a[l]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let u of d.ruleResults)u.status==="fail"&&u.actualValue!==null&&this.alertEngine.evaluate(`governance:${u.ruleId}`,u.actualValue,r.orgId);let c=A(this.deps,e,"governance:evaluate:response",{success:!0,result:d});this.deps.broker.postToWebview(c),this.deps.log("[TX] governance:evaluate:response")}catch(n){E(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=Ti.getDefaultTemplates(),r=A(this.deps,e,"governance:templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] governance:templates:response")}catch(t){E(this.deps,"governance:templates","governance:error",e,t)}}};var ou=class s{static COMMON_OBJECTS=[{apiName:"Account",label:"Account"},{apiName:"Contact",label:"Contact"},{apiName:"Opportunity",label:"Opportunity"},{apiName:"Case",label:"Case"},{apiName:"Lead",label:"Lead"}];suggest(e,t){let r=new Set(e),n=new Set(t);return s.COMMON_OBJECTS.map(o=>({objectApiName:o.apiName,label:o.label,isAvailable:r.has(o.apiName),isAlreadySelected:n.has(o.apiName)}))}};var a0=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),su=class{detect(e,t,r,n){let o=new Set(r),i=new Set(n),a=[];for(let d of t)if(d.type==="reference"&&d.referenceTo.length!==0)for(let c of d.referenceTo){if(c===e||o.has(c)||!i.has(c)||$h(c))continue;let u=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:u,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return a0.has(e)?"masterDetail":"lookup"}};var iu=class{estimate(e,t=new Set,r=200){let n=r>0?r:200,o=e.map(c=>({objectApiName:c.objectApiName,recordCount:c.count,...c.heldInSource!==void 0?{heldInSource:c.heldInSource}:{},estimatedApiCalls:c.count>0?Math.ceil(c.count/n):0,isParentDependency:t.has(c.objectApiName)})),i=o.reduce((c,u)=>c+u.recordCount,0),a=o.reduce((c,u)=>c+u.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var au=class{minConfidence;constructor(e=.4){this.minConfidence=e}suggest(e,t){let r=[],n=new Set,o=[...e];for(let i of o){let a;for(let d of t){if(n.has(d.apiName))continue;let c=this.computeScore(i,d);c.confidence>(a?.confidence??0)&&(a=c)}a&&a.confidence>=this.minConfidence&&(r.push(a),n.add(a.targetField))}return r.sort((i,a)=>a.confidence-i.confidence)}toMappings(e){return e.map(t=>({sourceField:t.sourceField,targetField:t.targetField,type:t.type}))}computeScore(e,t){if(e.apiName===t.apiName)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:1,reason:"exact_name"};let r=this.normalize(e.apiName),n=this.normalize(t.apiName);if(r===n&&r.length>0)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:.9,reason:"normalized_name"};let o=this.stringSimilarity(e.label.toLowerCase(),t.label.toLowerCase());if(o>=.8&&this.isTypeCompatible(e.type,t.type))return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:Math.min(.85,o),reason:"label_match"};let i=this.stringSimilarity(r,n),a=this.isTypeCompatible(e.type,t.type);return i>=.6&&a?{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:i*.7,reason:"partial_match"}:{sourceField:e.apiName,targetField:t.apiName,type:"direct",confidence:0,reason:"no_match"}}normalize(e){return e.replace(/__c$/i,"").replace(/__r$/i,"").replace(/_/g,"").toLowerCase()}stringSimilarity(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let r=this.bigrams(e),n=this.bigrams(t),o=0,i=[...n];for(let a of r){let d=i.indexOf(a);d>=0&&(o++,i.splice(d,1))}return 2*o/(r.length+n.length)}bigrams(e){let t=[];for(let r=0;r<e.length-1;r++)t.push(e.slice(r,r+2));return t}isTypeCompatible(e,t){return tg(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var d0=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),Ei={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},du=class{constructor(e){this.deps=e}deps;suggester=new ou;relationshipDetector=new su;previewEstimator=new iu;autoFieldMapper=new au;async handle(e){if(!d0.has(e.type))return!1;switch(e.type){case"quicksync:suggest-objects":return await this.handleSuggestObjects(e),!0;case"quicksync:detect-relationships":return await this.handleDetectRelationships(e),!0;case"quicksync:preview":return await this.handlePreview(e),!0;case"quicksync:execute":return await this.handleExecute(e),!0;default:return!1}}async handleSuggestObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Oy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let i=(await(await q(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.filter(c=>c.createable&&c.queryable).map(c=>c.name),a=this.suggester.suggest(i,r.alreadySelected??[]),d=A(this.deps,e,"quicksync:suggest-objects:response",{suggestions:a,availableObjects:[...i].sort((c,u)=>c.localeCompare(u))});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Iy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager),i=(await n.describe(r.objectApiName??"")).fields.map(u=>({name:u.name,type:u.type,referenceTo:u.referenceTo??[],relationshipName:u.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(u=>u.createable&&u.queryable).map(u=>u.name),d=this.relationshipDetector.detect(r.objectApiName??"",i,r.alreadySelected??[],a),c=A(this.deps,e,"quicksync:detect-relationships:response",{suggestions:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){E(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ay,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=[...new Set([...r.selectedObjects,...r.parentObjects??[]])],i=[],a=dd(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0));for(let l of o){let p=(await n.query(`SELECT COUNT() FROM ${l}`)).totalSize??0;i.push({objectApiName:l,count:Math.min(p,a),...p>a?{heldInSource:p}:{}})}let d=new Set(r.parentObjects??[]),c={...this.previewEstimator.estimate(i,d),readCap:a},u=A(this.deps,e,"quicksync:preview:response",{preview:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){E(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ty,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=kf.parse(r.config),o=await q(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=[...new Set([...n.selectedObjects,...n.parentObjects])],d=[];for(let l=0;l<a.length;l++){let g=a[l],p=n.parentObjects.includes(g),[f,h]=await Promise.all([Qt(n.sourceOrgId,g,()=>o.describe(g)),Qt(n.targetOrgId,g,()=>i.describe(g))]),m=f.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),y=h.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),R=this.autoFieldMapper.suggest(m,y),S=this.autoFieldMapper.toMappings(R);d.push({objectApiName:g,operation:Ei.operation,fieldMappings:S,transformRules:[],excludedFields:[],batchSize:Ei.batchSize,insertOrder:p?0:l+1})}let c={id:e.id,name:`Quick Sync ${new Date().toISOString()}`,description:"Auto-generated by Quick Sync",sourceOrgId:n.sourceOrgId,targetOrgId:n.targetOrgId,direction:Ei.direction,mode:Ei.mode,objects:d,conflictStrategy:Ei.conflictStrategy,enableRollback:!1};Ie(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let u=A(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){E(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var yT=6e4,c0=2880*6e4,u0=60*6e4,cu=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??ss()}start(){if(this.checkInterval)return;let e=this.deps.scheduleStore.loadAll(),t=this.now();for(let r of e)this.schedules.set(r.id,this.withPlausibleNextRun(r,t));this.lastTickTime=this.now(),this.checkInterval=setInterval(()=>{this.tick()},yT),this.deps.log("[SyncScheduleExecutor] started")}withPlausibleNextRun(e,t){if(!e.nextRunAt)return e;let r=new Date(e.nextRunAt).getTime(),n=Number.isNaN(r);if(!n&&r<=t+gS)return e;let o={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone)};return this.deps.scheduleStore.save(o),this.deps.log(`[SyncScheduleExecutor] ${e.id}: next run ${n?`"${e.nextRunAt}" cannot be read,`:e.nextRunAt} replaced by ${o.nextRunAt||"none"}`),o}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=void 0,this.deps.log("[SyncScheduleExecutor] stopped"))}async tick(){let e=this.now(),t=e-this.lastTickTime;t>2*yT&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=u0&&(this.lastPrune=e,this.claims.prune(c0));for(let r of this.schedules.values()){if(!r.enabled||!r.nextRunAt)continue;let n=new Date(r.nextRunAt).getTime();if(Number.isNaN(n)){let i=r.nextRunAt;r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] ${r.id}: next run "${i}" cannot be read, replaced by ${r.nextRunAt||"none"}`);continue}if(n>e||this.running.has(r.id))continue;if(!this.claims.claim(`sync-schedule:${r.id}:${n}`)){this.deps.log(`[SyncScheduleExecutor] ${r.id} due at ${r.nextRunAt} is run by another window`),r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone);continue}let o=this.deps.configStore.load(r.configId);if(!o){this.deps.log(`[SyncScheduleExecutor] config not found for schedule ${r.id} (configId=${r.configId})`),r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure&&this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: sync configuration "${r.configId}" no longer exists. Save the configuration again, or delete the schedule.`);continue}r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule started",r.name),this.running.add(r.id);try{let i=await this.deps.onExecute(o);if(r.lastRunAt=new Date(e).toISOString(),r.lastResult=i.cancelled?"cancelled":i.status,r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),i.cancelled)r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule cancelled",`${r.name}: ${i.error??"the run was cancelled."} Its entry in the sync history has what it wrote.`);else if(i.status==="failure"){if(r.notifyOnFailure){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a??"the run failed; its entry in the sync history has the details."}`)}}else if(i.status==="partial"&&r.notifyOnComplete){let a=i.objectResults.flatMap(u=>u.errors)[0],d=cd(i),c=[a,d].filter(u=>u!==void 0);this.deps.notificationCenter.notify("warning",a===void 0&&d!==void 0?"Sync schedule copied part of the source":"Sync schedule completed with errors",`${r.name}: ${c.length>0?c.join("; "):"some records failed; its entry in the sync history has the details."}`)}else r.notifyOnComplete&&this.deps.notificationCenter.notify("success","Sync schedule completed",r.name)}catch(i){if(r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure){let a=i instanceof Error?i.message:String(i);this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a}`)}}finally{this.running.delete(r.id)}}}upsert(e){let t=this.schedules.get(e.id),r={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone),lastRunAt:t?.lastRunAt,lastResult:t?.lastResult};return this.schedules.set(r.id,r),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] upserted schedule ${r.id}`),r}delete(e){let t=this.schedules.delete(e);return t&&(this.deps.scheduleStore.delete(e),this.deps.log(`[SyncScheduleExecutor] deleted schedule ${e}`)),t}toggle(e,t){let r=this.schedules.get(e);if(r)return r.enabled=t,t&&(r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone)),r.updatedAt=new Date(this.now()).toISOString(),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] toggled ${e} -> ${t?"enabled":"disabled"}`),r}getSchedules(){return Array.from(this.schedules.values())}getSchedule(e){return this.schedules.get(e)}computeNextRunAt(e,t){let r=fd(e,t,this.now());return typeof r=="number"?new Date(r).toISOString():(this.deps.log(`[SyncScheduleExecutor] no next run for cron "${e}": ${r.reason}`),"")}now(){return this.deps.now?this.deps.now():Date.now()}};var Gg="schedule:sync:",wT="syncSchedules",uu=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Gg}${e.id}`,e,wT)}load(e){return this.configStore.get(`${Gg}${e}`)}list(){let e=this.configStore.getByCategory(wT);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${Gg}${e}`)}loadAll(){return this.list()}};var l0=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),lu=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=ss();async handle(e){if(!l0.has(e.type))return!1;switch(e.type){case"sync:schedule:list":return this.handleList(e),!0;case"sync:schedule:upsert":return this.handleUpsert(e),!0;case"sync:schedule:toggle":return this.handleToggle(e),!0;case"sync:schedule:delete":return this.handleDelete(e),!0;default:return!1}}getExecutor(){if(!this.executor){let e=new cu({scheduleStore:new uu(this.deps.configStore),configStore:new It(this.deps.configStore),onExecute:t=>this.executeDue(t),notificationCenter:{notify:(t,r,n)=>{this.deps.log(`[SyncSchedule] ${t}: ${r} \u2014 ${n}`),Ie(this.deps,t,r,n)}},log:this.deps.log,claims:{claim:t=>this.claims.claim(t),prune:t=>this.claims.prune(t)}});e.start(),e.stop(),this.executor=e}return this.executor}async executeDue(e){if(!this.executeBridge)throw new Error("Scheduled sync execution is not wired to the sync engine yet");let t=this.deps.services?.getSandforgeSetting?.("sync.maxConcurrentOps",3)??3;if(this.inFlight>=t)throw new Error(`Scheduled sync skipped: ${this.inFlight} execution(s) already in flight (max ${t})`);this.inFlight++;try{return await this.executeBridge(e)}finally{this.inFlight--}}startScheduler(e,t){this.executeBridge=e,t&&(this.claims=t),this.getExecutor().start(),this.deps.log("[SyncScheduleHandler] scheduler started (tick loop running)")}stopScheduler(){this.executor?.stop()}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.getExecutor().getSchedules(),r=A(this.deps,e,"sync:schedule:list:response",{schedules:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(t){E(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Im,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new It(this.deps.configStore).load(r)){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(`Sync configuration not found: ${r}. Save it from the Sync tab first.`),{code:"NOT_FOUND"});return}let{cron:n,timezone:o}=t.schedule,i=fd(n,o,Date.now());if(typeof i!="number"){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(i.refused==="unreadable"?`The schedule was not saved: SandForge cannot read the cron expression "${n}" (${i.reason}).`:`The schedule was not saved. ${i.reason}`),{code:"INVALID_SCHEDULE"});return}try{let a=this.getExecutor().upsert(t.schedule),d=A(this.deps,e,"sync:schedule:upsert:response",{success:!0,schedule:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(a){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Am,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){E(this.deps,"sync:schedule:toggle","sync:schedule:error",e,new Error(`Schedule not found: ${t.scheduleId}`),{code:"NOT_FOUND"});return}let n=A(this.deps,e,"sync:schedule:toggle:response",{success:!0,schedule:r,scheduleId:t.scheduleId,enabled:t.enabled});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Tm,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().delete(t.scheduleId),n=A(this.deps,e,"sync:schedule:delete:response",{success:r,scheduleId:t.scheduleId});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var p0=new Set(["direct","rename"]);function bT(s,e,t,r={}){let n={objectApiName:s.objectApiName,fieldMappings:[],addOnFields:[],transformRules:[],applyDeletes:s.applyDeletes},o=r.keepContactPoints===!0?{keepContactPoints:!0}:{};switch(s.match.kind){case"id":return{...n,keyField:"Id",keySource:"Id",...o};case"externalId":return{...n,keyField:s.match.field,keySource:s.match.field,...o};case"syncConfig":{let i=e(s.match.configId);if(!i)throw new Error(`${s.objectApiName}: the saved Sync configuration picked no longer exists.`);if(i.sourceOrgId!==t.sourceOrgId||i.targetOrgId!==t.targetOrgId)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" runs between two other orgs.`);let a=i.objects.find(g=>g.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=So([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${ko(d)}`);let c=Uf([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${Hf(c)}`);let u=a.externalIdField?.trim()||"Id",l=a.fieldMappings.find(g=>g.targetField===u&&p0.has(g.type));return{...n,keyField:u,keySource:u==="Id"?"Id":l?.sourceField??u,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var g0=V({entityName:j().min(1),changeType:j().min(1),recordIds:ve(j()),commitTimestamp:Te(),commitUser:j().optional(),transactionKey:j().optional(),changeOrigin:j().optional(),changedFields:ve(j()).optional(),nulledFields:ve(j()).optional()}).loose(),f0=V({event:V({replayId:Te()}).loose(),payload:V({ChangeEventHeader:g0}).loose()}).loose(),pu="ChangeEvent";function vT(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${pu}`}function ST(s){if(!s.endsWith(pu)||s===pu)return null;let e=s.slice(0,-pu.length);return e.endsWith("__")?`${e}c`:e}function kT(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function RT(s){let e=s.indexOf(".");return e<0?s:kT(s.slice(0,e),s.slice(e+1))}function h0(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function OT(s,e){let t=f0.safeParse(e);if(!t.success){let i=t.error.issues[0];throw new Error(`A message on ${s} is not a change event (${i.path.join(".")||"message"}: ${i.message}).`)}let{ChangeEventHeader:r,...n}=t.data.payload,o={};for(let[i,a]of Object.entries(n))if(h0(a))for(let[d,c]of Object.entries(a))o[kT(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[RT(i)]=null;return{channel:s,replayId:t.data.event.replayId,objectApiName:r.entityName,changeType:r.changeType,recordIds:r.recordIds,commitTimestamp:r.commitTimestamp,commitUser:r.commitUser??"",transactionKey:r.transactionKey??"",changeOrigin:r.changeOrigin??"",changedFieldNames:(r.changedFields??[]).map(RT),values:o}}var Jg="SandForgeRealtime";function IT(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${Jg}`)}var ps=class extends Error{constructor(t,r){super(`${t}: ${r}`);this.channel=t;this.answer=r;this.name="SubscriptionRefused"}channel;answer;get replayIdRefused(){return/replay ?id/i.test(this.answer)}};function m0(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function AT(s){let e=new Map,t=new Map,r=[],n=!1,o={added(a){a.disable("websocket")},outgoing(a,d){if(a.channel==="/meta/subscribe"&&a.subscription){let c=e.get(a.subscription);c!==void 0&&(a.ext={...a.ext??{},replay:{[a.subscription]:c}})}d(a)},incoming(a,d){if(a.channel==="/meta/subscribe"&&a.successful===!1)t.set(a.subscription??"",a.error??"refused without a reason");else if((a.channel==="/meta/handshake"||a.channel==="/meta/connect")&&a.successful===!1&&a.advice?.reconnect==="none"){if(!n){n=!0;let c=a.error??`${a.channel} refused`;for(let u of r)u(c)}}else if(!a.channel.startsWith("/meta/")){let c=a.data?.event?.replayId;typeof c=="number"&&e.has(a.channel)&&e.set(a.channel,c)}d(a)}},i=s.createClient([o]);return{subscribe(a,d,c){return e.set(a,d),t.delete(a),new Promise((u,l)=>{i.subscribe(a,c).then(()=>u(),g=>{e.delete(a),l(new ps(a,t.get(a)??m0(g)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var TT="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function ET(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=ST(r);if(!n||e.has(n))continue;let o=typeof t.EventChannel=="string"?t.EventChannel:"";e.set(n,{objectApiName:n,channel:o})}return[...e.values()].sort((t,r)=>t.objectApiName.localeCompare(r.objectApiName))}async function PT(s,e,t,r,n=()=>{}){let o=t.filter(i=>i.sourceOrgId===r.sourceOrgId&&i.targetOrgId===r.targetOrgId);return Promise.all(s.map(async({objectApiName:i,channel:a})=>{let d=!0,c=[];try{c=(await e(i)).fields.filter(l=>l.externalId===!0).map(l=>l.name).sort()}catch(u){d=!1,n(`[realtime] ${i} could not be described in the target: ${I(u)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(u=>u.objects.some(l=>l.objectApiName===i)).map(u=>({id:u.id,name:u.name}))}}))}var fu=class{constructor(e=1e4){this.capacity=e}capacity;stamps=new Map;record(e,t){if(this.stamps.delete(e),this.stamps.set(e,t),this.stamps.size>this.capacity){let r=this.stamps.keys().next().value;r!==void 0&&this.stamps.delete(r)}}wrote(e,t){return this.stamps.get(e)===t}},qn=200,CT=new Set(["int","double","currency","percent","long"]),y0="The org sent an overflow notice instead of this change: one transaction changed more records than change events carry. A Sync run brings the target up to date.";function w0(s){return s==="DELETE"||s==="GAP_DELETE"}function $T(s){return s==="CREATE"||s==="UNDELETE"}function gu(s){if(typeof s!="string"||s==="")return null;let e=s.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"),t=Date.parse(e);return Number.isNaN(t)?null:t}function xT(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function DT(s){return s==null||s===""}function Vg(s){return String(s).toLowerCase()}var hu=class{constructor(e,t){this.plan=e;this.deps=t;this.objectConfig={objectApiName:e.objectApiName,operation:e.keyField==="Id"?"update":"upsert",externalIdField:e.keyField,fieldMappings:[],transformRules:e.transformRules,excludedFields:[],addOnFields:[],batchSize:qn,insertOrder:0}}plan;deps;mapping=new Qh;transforms=new Yh;objectConfig;masked=new Set;get contactPoints(){return this.plan.keepContactPoints===!0?void 0:this.deps.contactPoints}async apply(e){let t=e.map(()=>[]),r=[],n=this.deps.maskedSourceFields;n&&(this.masked=new Set(await n(this.plan.objectApiName).catch(()=>[])));let o=[];e.forEach((i,a)=>{if(i.changeType==="GAP_OVERFLOW"){t[a].push({outcome:"failed",error:y0});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=w0(i.changeType)?"delete":"upsert";if(d==="delete"&&!this.plan.applyDeletes){t[a].push({outcome:"deletes-off"});return}let c=o[o.length-1];(!c||c.kind!==d)&&(c={kind:d,changes:new Map},o.push(c));for(let u of i.recordIds){let l=c.changes.get(u);l?(l.eventIndexes.push(a),l.values={...l.values,...i.values},l.full=l.full||$T(i.changeType),l.needsRead=l.needsRead||i.changeType.startsWith("GAP_"),l.commitTimestamp=Math.min(l.commitTimestamp,i.commitTimestamp),l.replayId=Math.max(l.replayId,i.replayId)):c.changes.set(u,{recordId:u,eventIndexes:[a],changeType:i.changeType,full:$T(i.changeType),needsRead:i.changeType.startsWith("GAP_")&&d==="upsert",values:{...i.values},commitTimestamp:i.commitTimestamp,replayId:i.replayId})}});for(let i of o){let a=[...i.changes.values()],d=(c,u)=>{for(let l of c.eventIndexes)t[l].push(u)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let u=I(c);for(let l of a)d(l,{outcome:"failed",error:u})}}return{results:t.map(b0),held:r}}async resolve(e,t,r){let n=e.record[this.plan.keyField],o;if(e.kind==="delete"?o=t==="source_wins"?{}:null:o=this.resolvedValues(e,t,r),o===null)return{success:!0,resolvedValues:{}};try{if(e.kind==="delete"){let d=await this.writeOne("delete",{Id:e.targetId});return d.success?{success:!0,resolvedValues:{Id:e.targetId}}:{success:!1,resolvedValues:{},error:d.errors[0]??"Delete refused."}}let i=await this.coerced({...o,[this.plan.keyField]:n}),a=await this.writeOne(this.objectConfig.operation,i);return a.success?(await this.rememberWrites([a.id??e.targetId]),{success:!0,resolvedValues:i}):{success:!1,resolvedValues:{},error:a.errors[0]??"Write refused."}}catch(i){return{success:!1,resolvedValues:{},error:I(i)}}}resolvedValues(e,t,r){let n=Object.fromEntries(Object.entries(e.record).filter(([o])=>o!==this.plan.keyField));switch(t){case"source_wins":return n;case"merge":{let o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==null));return Object.keys(o).length>0?o:null}case"manual":{let o=Object.fromEntries(Object.entries(r??{}).filter(([i])=>i in n).map(([i,a])=>[i,a.value]));return Object.keys(o).length>0?o:null}case"target_wins":case"newest_wins":return null}}async coerced(e){let t=await this.deps.target.describe(this.plan.objectApiName),r=new Map(t.fields.map(o=>[o.name,o.type??""])),n={};for(let[o,i]of Object.entries(e)){let a=r.get(o)??"";if(typeof i=="string"&&a==="boolean")n[o]=i.trim().toLowerCase()==="true";else if(typeof i=="string"&&CT.has(a)&&i.trim()!==""){let d=Number(i);n[o]=Number.isNaN(d)?i:d}else n[o]=i}return n}async writeOne(e,t){let{outcomes:r}=await this.deps.write({...this.objectConfig,operation:e,batchSize:1},[t],this.contactPoints);return r[0]??{success:!1,errors:["The target answered nothing."]}}async applyUpserts(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(p=>[p.name,p]));if(this.plan.keyField!=="Id"&&!o.has(this.plan.keyField))throw new Error(`${n} has no field ${this.plan.keyField} in the target org.`);await this.readWhole(e.filter(p=>p.needsRead),t);let i=e.filter(p=>!p.needsRead||p.full),a=await this.keysOf(i,t,!1);i=i.filter(p=>a.has(p.recordId));let d=await this.readTarget([...new Set([...a.values()])],o,this.writtenFieldsOf(i,a)),c=[],u=[];for(let p of i){let f=a.get(p.recordId),h=d.get(Vg(f))??[];if(h.length>1){t(p,{outcome:"failed",error:`${h.length} records of ${n} in the target have ${this.plan.keyField} = ${String(f)}.`});continue}let m=h[0];if(!m){this.plan.keyField==="Id"?t(p,{outcome:"failed",error:"No record in the target has this Id: it was made after the two orgs were copied. Match on an external id to copy records made since."}):p.full?c.push({change:p,record:this.recordFor(p,f,o,!1)}):u.push(p);continue}let y=String(m.Id),R=this.recordFor(p,f,o,!0),S=gu(m.LastModifiedDate);if(!(S!==null&&S>p.commitTimestamp&&!this.deps.ownWrites.wrote(y,S))){c.push({change:p,record:R,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:p,record:R,targetId:y});break;case"merge":{let O=Object.fromEntries(Object.entries(R).filter(([P,v])=>v!==null||P===this.plan.keyField));Object.keys(O).length>1?c.push({change:p,record:O,targetId:y}):t(p,{outcome:"kept-target"});break}case"manual":r.push(this.held(p,"upsert",R,m)),t(p,{outcome:"held"});break;case"target_wins":case"newest_wins":t(p,{outcome:"kept-target"});break}}if(u.length>0){for(let p of u)p.needsRead=!0;await this.readWhole(u,t);for(let p of u.filter(f=>f.full))c.push({change:p,record:this.recordFor(p,a.get(p.recordId),o,!1)})}if(c.length===0)return;let{outcomes:l}=await this.deps.write(this.objectConfig,c.map(p=>p.record),this.contactPoints),g=[];c.forEach((p,f)=>{let h=l[f];if(h?.success){t(p.change,{outcome:"applied"});let m=h.id??p.targetId;m&&g.push(m)}else t(p.change,{outcome:"failed",error:h?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(g)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(l=>[l.name,l])),i=await this.keysOf(e,t,!0),a=e.filter(l=>i.has(l.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let l of a){let g=i.get(l.recordId),p=d.get(Vg(g))??[];if(p.length>1){t(l,{outcome:"failed",error:`${p.length} records of ${n} in the target have ${this.plan.keyField} = ${String(g)}.`});continue}let f=p[0];if(!f){t(l,{outcome:"applied"});continue}let h=String(f.Id),m=gu(f.LastModifiedDate);!(m!==null&&m>l.commitTimestamp&&!this.deps.ownWrites.wrote(h,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:l,targetId:h}):this.deps.conflictStrategy==="manual"?(r.push(this.held(l,"delete",{[this.plan.keyField]:g},f)),t(l,{outcome:"held"})):t(l,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:u}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(l=>({Id:l.targetId})));c.forEach((l,g)=>{let p=u[g];t(l.change,p?.success?{outcome:"applied"}:{outcome:"failed",error:p?.errors[0]??"The target answered nothing for this record."})})}held(e,t,r,n){let o=Object.keys(r).filter(i=>i!==this.plan.keyField);return{conflictId:`${this.plan.objectApiName}:${e.recordId}:${e.replayId}`,objectApiName:this.plan.objectApiName,recordId:e.recordId,replayId:e.replayId,changeType:e.changeType,kind:t,record:r,targetId:String(n.Id),targetValues:Object.fromEntries(o.map(i=>[i,n[i]??null])),targetLastModified:new Date(gu(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&DT(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${ze(n)}`,r);for(let d of o){let c=a.get(d.recordId);c&&(d.values={...d.values,[n]:c[n]??null})}}let i=new Map;for(let a of e){if(n!=="Id"&&!(n in a.values)){t(a,{outcome:"failed",error:r?"The deleted record can no longer be read in the source (it left the recycle bin), so the record to delete in the target cannot be found.":"The source record could not be read back, so its record in the target cannot be found."});continue}let d=this.plan.keyField==="Id"?a.recordId:this.mapped(a)[this.plan.keyField];if(DT(d)){t(a,{outcome:"failed",error:`The source record has no ${n}, so its record in the target cannot be found.`});continue}i.set(a.recordId,d)}return i}mapped(e){let r={...this.masked.size>0?Object.fromEntries(Object.entries(e.values).filter(([o])=>!this.masked.has(o))):e.values,Id:e.recordId},n=this.mapping.apply(r,this.plan.fieldMappings,this.plan.excludedFields);return this.plan.keySource!=="Id"&&n[this.plan.keyField]===void 0&&(n[this.plan.keyField]=r[this.plan.keySource]),n=this.transforms.transformRecord(n,this.objectConfig),this.mapping.applyAddOns(n,this.plan.addOnFields)}recordFor(e,t,r,n){let o=this.mapped(e),i=n?[]:na(this.plan.objectApiName,o),a={};for(let[d,c]of Object.entries(o)){if(c===void 0||d==="Id"||d===this.plan.keyField||i.includes(d))continue;let u=r.get(d);u&&((n?u.updateable!==!0:u.createable!==!0)||(a[d]=c))}return a[this.plan.keyField]=t,a}writtenFieldsOf(e,t){let r=new Set;for(let n of e)if(t.has(n.recordId))for(let[o,i]of Object.entries(this.mapped(n)))i!==void 0&&r.add(o);return[...r]}async readWhole(e,t){if(e.length===0)return;let r=await this.readSource(e.map(n=>n.recordId),"FIELDS(ALL)",!1);for(let n of e){let o=r.get(n.recordId);if(!o){t(n,{outcome:"failed",error:"The source record could not be read back: it was deleted since."});continue}n.values={...xT(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=wt(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=qn){let d=e.slice(i,i+qn).map(l=>`'${rr(l)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${qn}`:"",u=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let l of u)o.set(String(l.Id),l)}return o}async readTarget(e,t,r){let n=wt(this.plan.objectApiName),o=ze(this.plan.keyField),i=CT.has(t.get(this.plan.keyField)?.type??""),a=r.filter(u=>u!=="Id"&&u!==this.plan.keyField&&u!=="LastModifiedDate"&&t.has(u)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let u=0;u<e.length;u+=qn){let g=e.slice(u,u+qn).map(h=>i?String(Number(h)):`'${rr(String(h))}'`).join(", "),p=`WHERE ${o} IN (${g})`,f;try{f=await this.deps.target.query(`SELECT ${d.map(ze).join(", ")} FROM ${n} ${p}`)}catch{f=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${p}`)}for(let h of f){let m=Vg(h[this.plan.keyField]);c.set(m,[...c.get(m)??[],xT(h)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=wt(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=qn){let n=e.slice(r,r+qn).map(i=>`'${rr(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=gu(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function b0(s){let e=s.find(t=>t.outcome==="failed");return e||(s.some(t=>t.outcome==="held")?{outcome:"held"}:s.length>0&&s.every(t=>t.outcome==="kept-target")?{outcome:"kept-target"}:s.length>0&&s.every(t=>t.outcome==="deletes-off")?{outcome:"deletes-off"}:{outcome:"applied"})}var mu=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=vT(r),o=a=>{let d;try{d=OT(n,a)}catch(c){this.deps.onUnreadable(n,I(c));return}this.deps.onEvent(d)},i=this.deps.replayStore.get(n);try{await this.deps.transport.subscribe(n,i??-1,o),t.subscribed.push(r)}catch(a){if(i!==void 0&&a instanceof ps&&a.replayIdRefused)try{await this.deps.transport.subscribe(n,-2,o),t.subscribed.push(r),t.notes.push(`${r}: the org no longer holds the point the last session stopped at (replay id ${i}), so every change it still holds \u2014 up to three days \u2014 is replayed instead. Changes older than that were not received; a Sync run brings the target up to date.`)}catch(d){t.refused.push({objectApiName:r,reason:NT(d)})}else t.refused.push({objectApiName:r,reason:NT(a)})}}return t}close(){this.deps.transport.disconnect()}};function NT(s){return s instanceof ps?s.answer:I(s)}var S0=[2e3,1e4,3e4],k0=6e4,yu=class{constructor(e,t){this.config=e;this.deps=t}config;deps;state="disconnected";subscription;watched=[];refused=[];notes=[];error;stopped=!1;buffer=[];flushTimer;flushing=Promise.resolve();held=new Map;startedAt=0;lastEventAt;received=0;applied=0;failed=0;lagTotal=0;lagCount=0;currentLag=0;recentReceipts=[];now(){return(this.deps.now??Date.now)()}get sessionId(){return this.config.sessionId}get running(){return this.state==="syncing"||this.state==="connecting"}async start(){this.state="connecting",this.startedAt=this.now();let e;try{e=await this.open(this.config.watchedObjects)}catch(t){throw this.state="error",this.error=I(t),t}return this.watched=e.subscribed,this.refused=e.refused,this.notes=e.notes,e.subscribed.length===0?(this.state="error",this.error="The source org refused a subscription to every watched object.",this.closeSubscription()):this.state="syncing",e}async stop(){this.stopped=!0,this.state="disconnected",this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.closeSubscription(),this.buffer=[],await this.flushing;let e=this.held.size;return this.held.clear(),e}snapshot(){return{status:this.state,sessionId:this.config.sessionId,watchedObjects:this.watched,refused:this.refused,notes:this.notes,...this.error?{error:this.error}:{}}}metrics(){let e=this.now();this.recentReceipts=this.recentReceipts.filter(r=>e-r<k0);let t=this.applied+this.failed;return{eventsReceived:this.received,eventsApplied:this.applied,eventsFailed:this.failed,eventsPerMinute:this.recentReceipts.length,averageLagMs:this.lagCount>0?this.lagTotal/this.lagCount:0,currentLagMs:this.currentLag,errorRate:t>0?this.failed/t*100:0,startedAt:new Date(this.startedAt).toISOString(),...this.lastEventAt!==void 0?{lastEventAt:new Date(this.lastEventAt).toISOString()}:{}}}async resolveConflict(e,t,r){let n=this.held.get(e);if(!n)return{success:!1,resolvedValues:{},error:"This change is no longer held: the session that held it has stopped, or it was already decided."};let o=await n.applier.resolve(n.change,t,r);return o.success&&this.held.delete(e),o}closeSubscription(){this.subscription?.close(),this.subscription=void 0}async open(e){let t=await this.deps.openTransport();return t.onDown(r=>{this.reconnect(r)}),this.subscription=new mu({transport:t,replayStore:this.deps.replayStore,onEvent:r=>this.receive(r),onUnreadable:(r,n)=>this.deps.log(`[WARN] realtime ${r}: ${n}`)}),this.subscription.open(e)}async reconnect(e){if(!(this.stopped||this.state!=="syncing")){this.state="connecting",this.error=`The connection to the source org was closed (${e}); reconnecting.`,this.deps.sink.status(this.snapshot()),this.closeSubscription(),this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,await this.flushing,this.buffer=[];for(let t of S0){if(await new Promise(r=>setTimeout(r,t)),this.stopped)return;try{let r=await this.open(this.watched);if(r.subscribed.length>0){this.watched=r.subscribed,this.notes=[...this.notes,...r.notes],this.state="syncing",this.error=void 0,this.deps.sink.status(this.snapshot());return}this.closeSubscription()}catch(r){this.deps.log(`[WARN] realtime reconnect failed: ${I(r)}`)}}this.stopped||(this.state="error",this.error=`The connection to the source org was closed (${e}) and could not be reopened.`,this.deps.sink.status(this.snapshot()))}}receive(e){if(this.stopped)return;let t=this.now();this.received++,this.lastEventAt=t,this.recentReceipts.push(t),this.buffer.push(e),this.scheduleFlush(this.buffer.length>=this.config.maxBatchSize?0:this.config.flushIntervalMs)}scheduleFlush(e){if(this.flushTimer!==void 0){if(e>0)return;clearTimeout(this.flushTimer)}this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushing=this.flushing.then(()=>this.flush())},e)}async flush(){for(;this.buffer.length>0&&!this.stopped;){let e=this.buffer.splice(0,this.config.maxBatchSize);try{await this.process(e)}catch(t){this.deps.log(`[ERR] realtime batch: ${I(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{IT(i)?t[a]={outcome:"own-write"}:this.config.appliers.has(i.objectApiName)&&r.set(i.objectApiName,[...r.get(i.objectApiName)??[],a])});for(let[i,a]of r){let d=this.config.appliers.get(i);if(d)try{let{results:c,held:u}=await d.apply(a.map(l=>e[l]));c.forEach((l,g)=>{t[a[g]]=l});for(let l of u)this.held.set(l.conflictId,{change:l,applier:d}),this.deps.sink.conflict(l)}catch(c){let u=I(c);for(let l of a)t[l]={outcome:"failed",error:u}}}let n=this.now(),o=new Map;e.forEach((i,a)=>{let d=t[a];d.outcome==="applied"&&this.applied++,d.outcome==="failed"&&this.failed++;let c=Math.max(0,n-i.commitTimestamp);this.lagTotal+=c,this.lagCount++,this.currentLag=c,o.set(i.channel,Math.max(o.get(i.channel)??0,i.replayId))}),this.deps.sink.events(e.map((i,a)=>O0(i,t[a]))),this.deps.replayStore.save(o)}};function O0(s,e){let t={};for(let r of s.changedFieldNames)r in s.values&&(t[r]=s.values[r]);return{replayId:s.replayId,objectApiName:s.objectApiName,changeType:s.changeType,recordIds:s.recordIds,commitTimestamp:new Date(s.commitTimestamp).toISOString(),changedFields:s.changedFieldNames.length>0?t:{...s.values},commitUser:s.commitUser,transactionKey:s.transactionKey,applied:e.outcome==="applied",outcome:e.outcome,...e.error?{error:e.error}:{}}}var I0="realtime:replay:",A0="realtime",Pi=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${I0}${this.sourceOrgId}`}read(){let e=this.configStore.get(this.key),t={};if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="number"&&Number.isFinite(n)&&(t[r]=n);return t}get(e){return this.read()[e]}save(e){e.size!==0&&this.configStore.set(this.key,{...this.read(),...Object.fromEntries(e)},A0)}forget(){this.configStore.delete(this.key)}};function Kg(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function jT(s){return s.slice(0,15)}function MT(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&Er(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?id({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?ad({query:r,backup:t,recorder:e,describe:async d=>Pr(await s.target.describe(d)),viewsEncrypted:vr(r)}):void 0,o=new Set,i=(d,c,u,l)=>{if(c==="insert"||c==="upsert"){for(let p of ud(c,l))o.add(jT(p));return}if(c!=="delete")return;let g=u.flatMap((p,f)=>{let h=p.Id;return l[f]?.success===!0&&typeof h=="string"&&!o.has(jT(h))?[h]:[]});g.length>0&&e.deleted?.(d,g)},a;return{runId:s.sessionId,calls:ld(e,n),write:d=>{let c=Promise.resolve();return(u,l,g)=>{let p=c.then(async()=>{let f=await d(u,l,g);return i(u.objectApiName,u.operation,l,f.outcomes),f});return c=p.catch(()=>{}),p}},get ended(){return a!==void 0},end:d=>(a??=(async()=>{await e.end({status:d.status,...d.cancelled?{cancelled:!0}:{}});try{t?.close()}catch(c){s.log(`[WARN] realtime ${s.sessionId}: the backup of what it wrote over could not be listed whole: ${c instanceof Error?c.message:String(c)}`)}return e.flush()})(),a)}}var T0=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function E0(s){let e=r=>q(r,s.orgRegistry,s.orgManager),t=lt(s);return{async openTransport(r){let{streaming:n}=await e(r);return AT({createClient(o){let i=n.createClient(o);return{subscribe:(a,d)=>i.subscribe(a,d),disconnect:()=>i.disconnect?.()}}})},async identity(r){return(await e(r)).identity()},reader(r){return{async query(n,o){let i=await e(r),a=o?.includeDeleted===!0,{records:d}=await or({query:async c=>i.query(c,{scanAll:a}),queryMore:async c=>i.queryMore(c)},n);return d},async describe(n){let o=await e(r);return{fields:(await Qt(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await yh(d,Jg),u=new Nn({connection:c,bulkExecutor:new On(t.bulk.threshold),bulkManager:Rr(s),retryConfig:t.retry,onProgress:()=>{},log:g=>s.log(g),...n?{calls:n}:{}});return new $v({upsert:(g,p,f,h)=>u.upsert(g,p,f,h),insert:(g,p,f)=>u.insert(g,p,f),update:(g,p,f)=>u.update(g,p,f),delete:(g,p,f)=>u.delete(g,p,f),describeTargetFields:async g=>Pr(await Qt(r,g,()=>d.describe(g))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await or({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var wu=class{constructor(e,t){this.deps=e;this.syncConfigs=new It(e.configStore),this.access=t??E0(e)}deps;current;lastMetrics=null;registry;liveTracker;syncConfigs;access;runCreations;backupRecords;openRuns=new Set;isWritingTo(e){let t=this.current;return t!==void 0&&t.guard!==void 0&&t.session.running&&t.targetOrgId===e}isRunning(e){return this.openRuns.has(e)}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}async handle(e){if(!T0.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"realtime:objects":return await this.handleObjects(e),!0;case"realtime:start":return await this.handleStart(e),!0;case"realtime:stop":return await this.handleStop(e),!0;case"realtime:status":return this.post(A(this.deps,e,"realtime:status:response",this.statusPayload())),!0;case"realtime:metrics":return this.post(A(this.deps,e,"realtime:metrics:response",{metrics:this.current?.session.metrics()??this.lastMetrics})),!0;case"realtime:resolve-conflict":return await this.handleResolve(e),!0;default:return!1}}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async dispose(){await this.stopCurrent()}forgetOrg(e){new Pi(this.deps.configStore,e).forget()}post(e){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id}`)}pushEvents(e){let t={id:this.deps.nextId(),type:"realtime:events-batch",timestamp:Date.now(),payload:{events:e}};this.deps.broker.postToWebview(t)}pushConflict(e){let t={id:this.deps.nextId(),type:"realtime:conflict",timestamp:Date.now(),payload:{replayId:e.replayId,objectApiName:e.objectApiName,recordIds:[e.recordId],changeType:e.changeType,sourceValues:Object.fromEntries(Object.entries(e.record).filter(([r])=>r in e.targetValues)),targetValues:e.targetValues,targetLastModified:e.targetLastModified}};this.deps.broker.postToWebview(t)}pushStatus(e){let t={id:this.deps.nextId(),type:"realtime:status:response",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}pushStopped(e,t){let r={id:this.deps.nextId(),type:"realtime:stopped",timestamp:Date.now(),payload:{sessionId:e,reason:t,success:!0}};this.deps.broker.postToWebview(r)}statusPayload(){if(!this.current)return{status:"disconnected",watchedObjects:[]};let e=this.current.encryptedLeftOut??[];return{...this.current.session.snapshot(),...e.length>0?{encryptedLeftOut:e}:{}}}async stopCurrent(){let e=this.current;if(!e)return;this.current=void 0,e.detach();let t=await e.session.stop();return this.lastMetrics=e.session.metrics(),e.finish(),await e.endRun(),e.guard&&Q(this.deps,{action:"realtime_sync",module:"sync",operationId:e.operationId,orgId:e.targetOrgId,outcome:Kg(this.lastMetrics),guard:e.guard,source:{origin:"org",orgId:e.sourceOrgId}}),t>0&&Ie(this.deps,"warning","Real-time sync",`${t} change(s) held for a decision were not applied: the session that held them has stopped.`),e.session.sessionId}async handleObjects(e){let t=$(gm,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,TT),n=this.access.reader(t.targetOrgId),o=await PT(ET(r),i=>n.describe(i),this.syncConfigs.list(),t,i=>this.deps.log(i));this.post(A(this.deps,e,"realtime:objects:response",{objects:o}))}catch(r){let n=ch(I(r));E(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=$(lm,e,"realtime:error",this.deps);if(!t)return;let r=n=>{this.post(A(this.deps,e,"realtime:started",{success:!1,watchedObjects:[],refused:[],notes:[],error:n}))};if(this.current?.session.running){r(`A real-time session is already running (${this.current.session.sessionId}). Stop it before starting another.`);return}try{let n=t.apply.map(k=>bT(k,T=>this.syncConfigs.load(T),t,{keepContactPoints:t.keepContactPoints===!0})),o=n.length>0?await this.passesProductionGuard(e,t.targetOrgId,n):void 0;if(n.length>0&&!o){r("The target org is protected by the Production Guard, which did not allow the writes.");return}let i=new AbortController,a=new fu,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),u=crypto.randomUUID(),l=o&&this.runCreations?MT({sessionId:u,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,store:this.runCreations,...this.backupRecords?{backups:this.backupRecords}:{},meta:this.deps.configStore,target:c,identity:async()=>await this.access.identity?.(t.targetOrgId)??{},log:k=>this.deps.log(k)}):void 0,g=l?l.write(this.access.writer(t.targetOrgId,l.calls)):this.access.writer(t.targetOrgId),p=new SR,f=Zn(vr(k=>d.query(k)),k=>d.describe(k)),h=new Map(n.map(k=>[k.objectApiName,new hu(k,{source:d,target:c,write:g,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:p,maskedSourceFields:f})])),m,y=()=>{},R=new Promise((k,T)=>{y=x=>{x?m?.fail(x):i.signal.aborted?m?.cancel():m?.complete(),x?T(new Error(x)):k()}});R.catch(()=>{});let S=async()=>{if(!l)return;let k=await l.end({status:Kg(w.metrics()),cancelled:i.signal.aborted}).catch(T=>I(T));this.openRuns.delete(l.runId),k!==void 0&&Ie(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${k}): removing it may leave some of it in the target.`)},w=new yu({sessionId:u,watchedObjects:t.watchedObjects,appliers:h,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new Pi(this.deps.configStore,t.sourceOrgId),sink:{events:k=>this.pushEvents(k),conflict:k=>this.pushConflict(k),status:k=>{if(k.status!=="error"){this.pushStatus(k);return}y(k.error),S().then(()=>this.pushStatus(k))}},log:k=>this.deps.log(k)}),O={session:w,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:k=>y(k),detach:()=>{},endRun:S};this.current=O,this.lastMetrics=null,l&&this.openRuns.add(l.runId);let P;try{P=await w.start()}catch(k){throw await S(),k}let v=w.snapshot();if(P.subscribed.length>0){let k=`Real-time sync of ${P.subscribed.length} object(s)`;this.registry?.register(w.sessionId,"sync",k,R,i),m=ar(this.liveTracker,w.sessionId,"realtime",k);let T=()=>{this.current?.session===w&&this.stopCurrent().then(x=>{x&&this.pushStopped(x,"cancelled")})};i.signal.addEventListener("abort",T,{once:!0}),O.detach=()=>i.signal.removeEventListener("abort",T)}else y(),await S();let b=new Set(P.subscribed),C=(await Promise.all(n.filter(k=>b.has(k.objectApiName)).map(async k=>({objectApiName:k.objectApiName,fields:[...await f(k.objectApiName)].sort()})))).filter(k=>k.fields.length>0);C.length>0&&(O.encryptedLeftOut=C),this.post(A(this.deps,e,"realtime:started",{success:P.subscribed.length>0,sessionId:w.sessionId,watchedObjects:P.subscribed,refused:P.refused,notes:P.notes,...C.length>0?{encryptedLeftOut:C}:{},...v.error?{error:v.error}:{}}))}catch(n){r(I(n))}}async passesProductionGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw Q(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",code:Re.code}),sa();let o={orgId:t,orgTier:Pe(this.deps.orgManager.getOrg(t)),operation:r.some(a=>a.applyDeletes)?"delete":"upsert",objectName:r.map(a=>a.objectApiName).join(", "),recordCount:"unknown",module:"sync"},{decision:i}=await et(n,o);if(i==="refused"||i==="declined"){Q(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=$(pm,e,"realtime:error",this.deps);if(!t)return;let r=this.current;if(!r||t.sessionId!==""&&t.sessionId!==r.session.sessionId){this.post(A(this.deps,e,"realtime:status:response",this.statusPayload()));return}let n=await this.stopCurrent();this.post(A(this.deps,e,"realtime:stopped",{sessionId:n??r.session.sessionId,reason:"stopped",success:!0}))}async handleResolve(e){let t=$(fm,e,"realtime:error",this.deps);if(!t)return;let r=this.current?await this.current.session.resolveConflict(t.conflictId,t.resolution,t.fieldResolutions&&Object.fromEntries(Object.entries(t.fieldResolutions).map(([n,o])=>[n,{value:o.value,source:o.source}]))):{success:!1,resolvedValues:{},error:"No real-time session is running: the change it held was dropped when it stopped."};r.success||Ie(this.deps,"warning","Real-time sync",`The decision on ${t.conflictId} was not applied: ${r.error??"refused"}`),this.post(A(this.deps,e,"realtime:conflict-resolved",{conflictId:t.conflictId,resolution:t.resolution,success:r.success,resolvedValues:r.resolvedValues,...r.error?{error:r.error}:{}}))}};var P0=new Set(["file:save"]),bu=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;async handle(e){return P0.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=im.safeParse(e.payload);if(!t.success){let i={status:"error",message:`Invalid payload \u2014 ${t.error.issues.slice(0,3).map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}`};this.deps.log(`[FileHandler] save ${i.status}: ${i.message}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",i));return}let r=t.data,n=await this.saveDialog.save(r.suggestedName,r.content,r.extensions);this.deps.log(`[FileHandler] save ${n.status}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",n))}};var C0=new Set(["reports:list","reports:audit","reports:lineage"]),$0="forge:history",x0="sync:history:all",LT=50;function D0(s){return s.readByObject?s.readByObject.reduce((t,r)=>t+r.read,0):(s.graph?.nodes??[]).reduce((t,r)=>t+(r.recordCount??0),0)}function N0(s){let e=s.graph?.nodes??[];return e.filter(t=>!Gf(t)).length+Jf(s,e).length}var Ru=class{constructor(e){this.deps=e}deps;async handle(e){if(!C0.has(e.type))return!1;switch(e.type){case"reports:list":return this.handleList(e),!0;case"reports:audit":return this.handleAudit(e),!0;case"reports:lineage":return this.handleLineage(e),!0;default:return!1}}handleAudit(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(qy,e,"reports:error",this.deps);if(t===null)return;let r=new To(this.deps.configStore).list(t??{});this.deps.log(`[ReportsHandler] audit trail: ${r.entries.length} of ${r.total} entries`),this.deps.broker.postToWebview(A(this.deps,e,"reports:audit:response",{...r}))}handleLineage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Wy,e,"reports:error",this.deps);if(t===null)return;let r=new Fh(this.deps.configStore);this.deps.broker.postToWebview(A(this.deps,e,"reports:lineage:response",{lineage:r.get(t?.operationId),runs:r.runs()}))}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.readLimit(e),r=this.build(t);this.deps.log(`[ReportsHandler] ${r.reports.length} report(s) from stored history (${r.summary.successRate}% success)`),this.deps.broker.postToWebview(A(this.deps,e,"reports:list:response",{...r}))}readLimit(e){let t=e.payload?.limit;return typeof t!="number"||!Number.isFinite(t)||t<=0?LT:Math.min(Math.floor(t),500)}build(e=LT){let t=this.deps.configStore.get($0)??[],r=this.deps.configStore.get(x0)??[],n=[...t.map(o=>this.forgeReport(o)),...r.map(o=>this.syncReport(o))].sort((o,i)=>i.generatedAt.localeCompare(o.generatedAt)).slice(0,e);return{reports:n,summary:M0(n)}}forgeReport(e){let t=N0(e),r=D0(e);return{id:`forge-${e.forgeId}`,definitionId:`forge-${e.forgeId}`,type:"forge_execution",title:`Forge clone \u2014 ${t} object(s)`,summary:`${e.status} \xB7 ${r} record(s) across ${t} object(s) \xB7 ${e.idRemapCount} id(s) remapped`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:e.status,objects:t,records:r,idRemapCount:e.idRemapCount,durationMs:e.duration}}],metadata:{module:"forge",operationId:e.forgeId,duration:e.duration,recordCount:r},generatedAt:e.timestamp}}syncReport(e){let t=e.result,r=t?.totalProcessed??0,n=t?.totalFailed??0;return{id:`sync-${e.id}`,definitionId:`sync-${e.id}`,type:"sync_execution",title:`Sync \u2014 ${e.configSnapshot?.name??"unnamed configuration"}`,summary:`${t?.status??"unknown"} \xB7 ${r} processed, ${t?.totalSuccess??0} succeeded, ${n} failed \xB7 triggered ${e.triggeredBy}`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:t?.status??"unknown",processed:r,succeeded:t?.totalSuccess??0,failed:n,skipped:t?.totalSkipped??0,triggeredBy:e.triggeredBy}}],metadata:{module:"sync",operationId:e.id,duration:t?.duration,recordCount:r},generatedAt:e.endTime??e.startTime}}};function j0(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function M0(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(j0).length,r=s.map(o=>o.metadata.duration??0),n=o=>Math.round(o*10)/10;return{totalOperations:e,successRate:n((e-t)/e*100),avgDuration:Math.round(r.reduce((o,i)=>o+i,0)/e),errorRate:n(t/e*100)}}function FT(s){return Object.values(s).every(e=>e<50)}var vu=class{deps;constructor(e){this.deps=e}async analyzeOrg(e,t){let r=await this.deps.getConnection(e),n=await this.queryRecordCounts(r),o;if(t){let i=await this.deps.getConnection(t);o=await this.queryRecordCounts(i)}return this.decide(e,n,t,o)}async queryRecordCounts(e){let t=await Promise.all(sf.map(async n=>{try{let o=await e.query(`SELECT COUNT() FROM ${n}`);return{objectName:n,count:o.totalSize}}catch{return{objectName:n,count:0}}})),r={};for(let{objectName:n,count:o}of t)r[n]=o;return r}decide(e,t,r,n){let o=Object.values(t).reduce((u,l)=>u+l,0),i=FT(t),a=n!==void 0&&!FT(n),d="none",c="";return i&&a&&r?(d="clone",c="home.smartAction.reasonClone"):i&&o===0?(d="quick-seed",c="home.smartAction.reasonEmpty"):i?(d="quick-seed",c="home.smartAction.reasonSampleOnly"):a&&r&&(d="sync",c="home.smartAction.reasonSync"),{action:d,reasonKey:c,details:{targetOrgId:e,sourceOrgId:r,recordCounts:t,...n?{sourceRecordCounts:n}:{}}}}};function F0(s,e){return`smart-action:${s}:${e??""}`}var _0=300*1e3,U0=new Set(["smart-action:analyze"]),Su=class{constructor(e){this.deps=e;this.analyzer=new vu({getConnection:t=>q(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return U0.has(e.type)&&e.type==="smart-action:analyze"?(await this.handleAnalyze(e),!0):!1}forgetOrg(e){for(let[t,r]of this.cache)r.orgIds.includes(e)&&this.cache.delete(t)}async handleAnalyze(e){let t=$(iw,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=F0(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<_0){this.deps.log(`[SmartAction] Cache hit for ${r}`);let c=A(this.deps,e,"smart-action:analyze:response",{recommendation:i.recommendation});this.deps.broker.postToWebview(c),this.deps.log("[TX] smart-action:analyze:response (cached)");return}this.deps.log(`[SmartAction] Analyzing org ${r}`);let a=await this.analyzer.analyzeOrg(r,n);this.cache.set(o,{recommendation:a,fetchedAt:Date.now(),orgIds:n?[r,n]:[r]});let d=A(this.deps,e,"smart-action:analyze:response",{recommendation:a});this.deps.broker.postToWebview(d),this.deps.log("[TX] smart-action:analyze:response")}catch(r){E(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var H0=new Set(["execution:abort"]),ku=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return H0.has(e.type)&&e.type==="execution:abort"?(await this.handleAbort(e),!0):!1}async handleAbort(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(_y,e,"execution:error",this.deps);if(!t)return;let r=t.operationId??t.executionId??"",n=this.registry.get(r);if(!n&&this.registry.cancelBeforeStart(r)){let i=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (before it started)`);return}if(!n){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:`Operation not found: ${r}`});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (not found)`);return}if(n.status!=="running"){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:"Operation already finished",status:n.status});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (already ${n.status})`);return}this.registry.abort(r);let o=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){E(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as B0}from"node:fs/promises";import{join as q0}from"node:path";var Xg=new Map;function _T(s,e){let t=q0(s,`${e}.json`),r=Xg.get(t);if(r)return r;let n=B0(t,"utf-8").then(o=>JSON.parse(o));return Xg.set(t,n),n.catch(()=>Xg.delete(t)),n}var W0=new Set(["i18n:locale"]),Ou=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return W0.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(sw,e,"i18n:locale:response",this.deps);if(!t)return;let{lng:r}=t;if(!this.localesDir){let n=A(this.deps,e,"i18n:locale:response",{lng:r,error:"Locale files are not available in this extension host."});this.deps.broker.replyToRequester(n);return}try{let n=await _T(this.localesDir,r),o=A(this.deps,e,"i18n:locale:response",{lng:r,bundle:n});this.deps.broker.replyToRequester(o),this.deps.log(`[TX] i18n:locale:response (${r})`)}catch(n){this.deps.log(`[ERR] i18n:locale (${r}): ${I(n)}`);let o=A(this.deps,e,"i18n:locale:response",{lng:r,error:I(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as z0}from"node:async_hooks";function HT(s,e){if(!s)return{decision:"refused",reason:"no Production Guard runs in this window"};let t=s.check(e);return t.allowed?t.requiresConfirmation?{decision:"asks"}:{decision:"allowed"}:{decision:"refused",reason:t.blockedReason??t.impactSummary}}var UT=new z0;async function BT(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,u)=>{c!=="started"||u.module!=="sync"||UT.getStore()!==n||(o=d,r?.aborted&&s.registry?.abort(d))}),a=()=>{o!==void 0&&s.registry?.abort(o)};r?.addEventListener("abort",a,{once:!0});try{let d=await UT.run(n,()=>Ca(t,()=>s.execute(e)));return o!==void 0?{...d,operationId:o}:d}finally{i?.(),r?.removeEventListener("abort",a)}}var G0=V({setting:j().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),Iu=class{handlerDeps;executeCommand;showLog;panelRouteListener;panelReloadListener;idCounter=0;orgHandler;settingsHandler;monitorHandler;seedHandler;seedCloneHandler;seedCsvHandler;syncHandler;syncHistoryHandler;syncRemovalHandler;seedRemovalHandler;compareHandler;dataOpsHandler;complianceHandler;cleanupHandler;emptyHandler;automationHandler;aiHandler;autopilotHandler;forgeHandler;frozenHandler;checkpointHandler;migrationHandler;configHandler;governanceHandler;quickSyncHandler;syncScheduleHandler;realtimeHandler;fileHandler;reportsHandler;smartActionHandler;i18nHandler;syncHistoryStore;executionHandler;backgroundRegistry;refreshDetector;recoveryProgressSource;recoveryHandler;checkpointStore;beforeRunCheckpoints;constructor(e){this.executeCommand=e.executeCommand??(()=>Promise.resolve()),this.showLog=e.showLog??(()=>{}),this.refreshDetector=new Td({configStore:e.configStore,orgManager:e.orgManager,log:e.log}),this.recoveryProgressSource=uS({refreshesOf:r=>this.refreshDetector.refreshesOf(r),organizationIdOf:r=>this.refreshDetector.organizationIdOf(r),orgOf:r=>e.orgManager.getOrg(r),configStore:e.configStore,statusOf:r=>this.recoveryHandler.progressCountOf(r),log:e.log}),this.handlerDeps={log:e.log,broker:e.broker,stateSync:e.stateSync,orgManager:e.orgManager,orgRegistry:e.orgRegistry,configStore:e.configStore,secretVault:e.secretVault,authProvider:e.authProvider,sfdxBridge:e.sfdxBridge,services:e.services,robustness:Gu,bulkManager:new Lh(Gu.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector,recoveryProgress:this.recoveryProgressSource},this.orgHandler=new $d(this.handlerDeps),this.recoveryHandler=new Ed(this.handlerDeps),this.settingsHandler=new xd(this.handlerDeps),this.monitorHandler=new zd(this.handlerDeps),this.seedHandler=new Kd(this.handlerDeps),this.seedCloneHandler=new Zd(this.handlerDeps),this.seedCsvHandler=new nc(this.handlerDeps),this.seedRemovalHandler=new uc(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new ic(this.handlerDeps),this.syncHistoryStore=new pc(e.configStore),this.syncHandler.setHistoryLogger(new gc(this.syncHistoryStore)),this.syncHistoryHandler=new ac(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new dc(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new fc(this.handlerDeps),this.dataOpsHandler=new Hb(this.handlerDeps),this.complianceHandler=new wc(this.handlerDeps),this.cleanupHandler=new bc(this.handlerDeps),this.emptyHandler=new Nc(this.handlerDeps),this.automationHandler=new Lc(this.handlerDeps),this.aiHandler=new Bc(this.handlerDeps),this.autopilotHandler=new Wc(this.handlerDeps),this.forgeHandler=new Xc(this.handlerDeps),this.frozenHandler=new yS(this.handlerDeps),this.frozenHandler.setSaltKeeper(mS(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new kd(this.handlerDeps,{isRunning:r=>this.syncHandler.isRunning(r)||this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r),writingTo:(r,n)=>t().some(o=>o.isWritingTo(r,n))}),this.beforeRunCheckpoints={scope:(r,n)=>this.checkpointHandler.scopeBeforeRun(r,n),take:(r,n,o)=>this.checkpointHandler.takeBeforeRun(r,n,o),settle:(r,n)=>this.checkpointHandler.settleBeforeRun(r,n)},this.forgeHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.autopilotHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.frozenHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.syncHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCsvHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCloneHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setRunWriting((r,n,o)=>this.checkpointHandler.writingTo(r,n,"empty it","Nothing was deleted.",{operationId:o})),this.forgeHandler.setOtherModuleRuns(this.otherModuleRuns("forge",t)),this.syncRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("sync",t)),this.seedRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("seed",t)),this.frozenHandler.setOtherModuleRuns(this.otherModuleRuns("frozen",t)),this.migrationHandler=new Yc(this.handlerDeps),this.configHandler=new eu(this.handlerDeps),this.governanceHandler=new nu(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new du(this.handlerDeps),this.syncScheduleHandler=new lu(this.handlerDeps),this.realtimeHandler=new wu(this.handlerDeps),this.fileHandler=new bu(this.handlerDeps),this.reportsHandler=new Ru(this.handlerDeps),this.smartActionHandler=new Su(this.handlerDeps),this.i18nHandler=new Ou(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?ye(n,n.id):void 0},newId:()=>crypto.randomUUID(),backup:(r,n)=>this.dataOpsHandler.backupForPipeline(r,n),compare:(r,n)=>this.compareHandler.compareOrgs(r,n),readOrgHealth:(r,n)=>this.monitorHandler.readOrgHealth(r,n),notify:e.services?.showNotification,savedSyncConfig:r=>new It(e.configStore).load(r),listSyncConfigs:()=>new It(e.configStore).list(),syncGuard:r=>HT(this.handlerDeps.infraServices?.productionGuard,sg(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>BT({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Pe(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new un(e.configStore).load(r),listSeedTemplates:()=>new un(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...Uh.map(r=>({...r,builtIn:!0})),...new Ta(e.configStore).list().map(r=>({...r,builtIn:!1}))],anonymize:(r,n)=>this.dataOpsHandler.anonymizeForPipeline(r,n),takeCheckpoint:(r,n)=>this.checkpointHandler.takeForPipeline(r,n),rewind:(r,n)=>this.checkpointHandler.rewindForPipeline(r,n),readCheckpoint:r=>this.readCheckpointForRewind(r),...e.services?.runsFrom?{ranFrom:e.services.runsFrom}:{},simulateSync:(r,n)=>this.syncHandler.simulateForPipeline(r,n),previewSeed:(r,n)=>this.seedHandler.previewForPipeline(r,n),previewMasking:(r,n)=>this.dataOpsHandler.previewMaskingForPipeline(r,n),estimateTake:(r,n)=>this.checkpointHandler.estimateTakeForPipeline(r,n),previewRewind:(r,n)=>this.checkpointHandler.previewRewindForPipeline(r,n)}),this.automationHandler.setDryRunApplier(Tk),this.checkpointHandler.onCheckpointsChanged(()=>{this.automationHandler.revokeVoidGrants()}),this.recoveryHandler.onStatusChanged(r=>this.recoveryProgressSource.invalidate(r)),this.checkpointHandler.onCheckpointsChanged(()=>this.recoveryProgressSource.invalidate()),this.refreshDetector.onRefreshDetected(r=>this.forgetOrg(r.orgId)),this.refreshDetector.onRefreshDetected(r=>{let n=r.previousOrganizationId??this.refreshDetector.organizationIdOf(r.orgId)??r.detectedAt;Promise.resolve().then(()=>this.automationHandler.noticeSandboxRefresh({orgId:r.orgId,key:n}))}),this.refreshDetector.onRefreshDetected(r=>this.recoveryProgressSource.invalidate(r.orgId))}get sandboxRefreshes(){return this.refreshDetector}get recoveryProgress(){return this.recoveryProgressSource}postSettings(){this.settingsHandler.postSettings()}forgetOrg(e){Io().remove(e),Pk(e),this.monitorHandler.forgetOrg(e),this.forgeHandler.forgetOrg(e),this.frozenHandler.forgetOrg(e),this.aiHandler.forgetOrg(e),this.smartActionHandler.forgetOrg(e),this.realtimeHandler.forgetOrg(e),this.handlerDeps.log(`[sandbox-refresh] dropped what was cached about ${e}`)}setLiveOperationTracker(e){this.monitorHandler.setLiveOperationTracker(e),this.seedHandler.setLiveOperationTracker(e),this.syncHandler.setLiveOperationTracker(e),this.syncRemovalHandler.setLiveOperationTracker(e),this.seedRemovalHandler.setLiveOperationTracker(e),this.forgeHandler.setLiveOperationTracker(e),this.seedCloneHandler.setLiveOperationTracker(e),this.seedCsvHandler.setLiveOperationTracker(e),this.frozenHandler.setLiveOperationTracker(e),this.autopilotHandler.setLiveOperationTracker(e),this.checkpointHandler.setLiveOperationTracker(e),this.dataOpsHandler.setLiveOperationTracker(e),this.cleanupHandler.setLiveOperationTracker(e),this.emptyHandler.setLiveOperationTracker(e),this.complianceHandler.setLiveOperationTracker(e),this.automationHandler.setLiveOperationTracker(e),this.realtimeHandler.setLiveOperationTracker(e)}setBackupRecordStore(e){this.dataOpsHandler.setBackupRecordStore(e),this.dataOpsHandler.setRunKeyStore(Pb(this.handlerDeps.secretVault)),this.syncHandler.setBackupRecordStore(e),this.syncRemovalHandler.setBackupRecordStore(e),this.realtimeHandler.setBackupRecordStore(e)}otherModuleRuns(e,t){return async(r,n)=>{let o=e==="forge"?this.forgeHandler:e==="frozen"?this.frozenHandler:void 0,i=new To(this.handlerDeps.configStore).list({orgId:r,limit:hf}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...Av(i,e==="frozen"?"frozen_load":void 0)];if(t().some(d=>d!==o&&d.isWritingTo(r))){let d=Date.now();a.push({ids:[],idsUntold:!0,from:d,to:d})}return a}}setSyncRunCreations(e){this.syncHandler.setRunCreations(e),this.syncRemovalHandler.setRunCreations(e),this.realtimeHandler.setRunCreations(e),this.dataOpsHandler.setSyncRuns(e),this.checkpointHandler.setRunFiles("sync",e)}setSeedRunCreations(e){this.seedHandler.setRunCreations(e),this.seedCsvHandler.setRunCreations(e),this.seedCloneHandler.setRunCreations(e),this.seedRemovalHandler.setRunCreations(e),this.checkpointHandler.setRunFiles("seed",e)}sweepCheckpoints(){return this.checkpointHandler.sweep()}setCheckpointStore(e){this.checkpointStore=e,this.checkpointHandler.setStore(e),this.recoveryHandler.setCheckpointStore(e)}async readCheckpointForRewind(e){let{openCheckpointStore:t,defaultCheckpointStoreRoot:r}=await import("./chunk-SBDF4AE5.mjs"),n=this.checkpointStore;if(!n){let d=t({root:r()});if(!("store"in d))throw new Error(`The checkpoints of this machine cannot be read: ${d.refusal.reason}`);n=d.store}let o=await n.read(e);if(o===void 0)return{kept:!1};if(o.checkpoint===void 0)return{kept:!0,valid:!1,why:"damaged"};let{organizationId:i}=o.checkpoint.org,a=(await n.list({organizationId:i,refreshedAt:d=>this.refreshedAtOf(d)})).find(d=>d.checkpointId===e);return{kept:!0,organizationId:i,name:o.checkpoint.name,valid:a?.valid??!1,...a?.why!==void 0?{why:a.why}:{}}}refreshedAtOf(e){let t=r=>r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15);for(let r of this.handlerDeps.orgManager.getAllOrgs())for(let n of this.refreshDetector.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?this.refreshDetector.organizationIdOf(r.id):void 0);if(t(o))return n.detectedAt}}setEmptyStores(e){this.emptyHandler.setStores(e)}rewindCheckpointsFromPreviewsAnswered(){this.checkpointHandler.rewindFromPreviewsAnswered()}exportCheckpoint(e){return this.checkpointHandler.exportCheckpoint(e)}readCheckpointImport(e){return this.checkpointHandler.readImport(e)}importCheckpoint(e){return this.checkpointHandler.importCheckpoint(e)}checkpointsKeptBefore(e){return this.checkpointHandler.keptBefore(e)}latestCheckpointOf(e){return this.checkpointHandler.latestUsableOf(e)}onCheckpointsChanged(e){return this.checkpointHandler.onCheckpointsChanged(e)}setPanelRouteListener(e){this.panelRouteListener=e}setPanelReloadListener(e){this.panelReloadListener=e}setAIAssistant(e){this.aiHandler.setAIAssistant(e)}setInfraServices(e){this.handlerDeps.infraServices=e}setOrgSelectionCallback(e){this.handlerDeps.onOrgSelected=e}setBackgroundRegistry(e){this.backgroundRegistry=e,this.syncHandler.setRegistry(e),this.syncRemovalHandler.setRegistry(e),this.seedRemovalHandler.setRegistry(e),this.seedHandler.setRegistry(e),this.seedCloneHandler.setRegistry(e),this.seedCsvHandler.setRegistry(e),this.frozenHandler.setRegistry(e),this.realtimeHandler.setRegistry(e),this.autopilotHandler.setRegistry(e),this.executionHandler=new ku(this.handlerDeps,e)}async replayQueuedOperation(e){let t=vn("offline-replay",e.id,`${e.type}:execute`);switch(e.type){case"sync":await this.syncHandler.rerunFromSnapshot(t,e.payload.config);return;case"seed":{let r={...t,payload:e.payload};await this.seedHandler.handle(r);return}default:throw new Error(`Unsupported queued operation type: ${e.type}`)}}startSyncScheduler(e){this.syncScheduleHandler.startScheduler(t=>this.syncHandler.executeScheduled(t),e)}stopSyncScheduler(){this.syncScheduleHandler.stopScheduler()}stopLiveOperationsPush(){this.monitorHandler.dispose()}async stopRealtime(){await this.realtimeHandler.dispose()}startPipelineTriggers(e){this.automationHandler.startTriggers(e)}stopPipelineTriggers(){this.automationHandler.stopTriggers()}setAIModules(e){this.aiHandler.setAIModules(e),this.handlerDeps.errorResolver=e?.errorResolver}setRuleModules(e){this.aiHandler.setRuleModules(e)}setMigrationServices(e){this.migrationHandler.setFileReader(e)}setPipelineMarketplace(e){this.automationHandler.setPipelineMarketplace(e)}setAutopilotOrchestrator(e){this.autopilotHandler.setOrchestrator(e)}sweepForgePlans(){return this.forgeHandler.sweepSimulationPlans()}setForgeOrchestrator(e,t){this.forgeHandler.setForgeOrchestrator(e,t)}registerAll(e){let t=(r,n)=>{for(let o of r)e.route(o,async i=>{await n.handle(i)})};t(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status","org:assign-right"],this.orgHandler),t(["settings:get","settings:update","telemetry:status","telemetry:toggle"],this.settingsHandler),t(["i18n:locale"],this.i18nHandler),t(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"],this.seedHandler),t(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"],this.seedCloneHandler),t(["seed:csv:validate","seed:csv:execute"],this.seedCsvHandler),t(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"],this.syncHandler),t(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"],this.syncHistoryHandler),t(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"],this.syncRemovalHandler),t(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"],this.seedRemovalHandler),t(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"],this.syncScheduleHandler),t(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"],this.quickSyncHandler),t(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"],this.monitorHandler),t(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"],this.governanceHandler),t(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"],this.compareHandler),t(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"],this.dataOpsHandler),t(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"],this.complianceHandler),t(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"],this.cleanupHandler),t(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"],this.emptyHandler),t(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","pipeline:export","marketplace:list","marketplace:install"],this.automationHandler),t(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"],this.aiHandler),t(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"],this.autopilotHandler),t(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request","forge:previewRoots"],this.forgeHandler),t(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"],this.frozenHandler),t(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"],this.checkpointHandler),t(["recovery:status","recovery:users:list","recovery:users:plan","recovery:users:apply","recovery:users:cancel","recovery:users:config:save","recovery:users:config:export","recovery:users:config:import","recovery:audit","recovery:handoff","recovery:handoff:open","recovery:ack"],this.recoveryHandler),t(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"],this.migrationHandler),t(["config:export","config:import","config:categories","config:validate"],this.configHandler),t(["smart-action:analyze"],this.smartActionHandler),t(["file:save"],this.fileHandler),t(["reports:list","reports:audit","reports:lineage"],this.reportsHandler),this.executionHandler&&t(["execution:abort"],this.executionHandler),t(["realtime:objects","realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:resolve-conflict"],this.realtimeHandler),e.route("panel:route",r=>{this.panelRouteListener?.(r)}),e.route("panel:reload",r=>{this.panelReloadListener?.(r)}),e.route("workbench:reload",()=>{this.executeCommand("workbench.action.reloadWindow")}),e.route("workbench:open-setting",r=>{let n=G0.safeParse(r.payload);if(!n.success){this.handlerDeps.log("[WARN] workbench:open-setting: not a SandForge setting id");return}this.executeCommand("workbench.action.openSettings",n.data.setting)}),e.route("workbench:open-log",()=>{this.showLog()}),e.route("error:boundary",r=>{let{payload:n}=r;this.handlerDeps.log(`[ERR] Webview crash (error:boundary): ${n?.message??"unknown error"}`+(n?.stack?`
|
|
20
|
-
${n.stack}`:""))})}nextId(){return`ext-${++this.idCounter}`}};var Au=class{maxActions;windowMs;nowFn;timestamps=[];constructor(e,t,r=Date.now){this.maxActions=Math.max(1,e),this.windowMs=Math.max(100,t),this.nowFn=r}tryAcquire(){let e=this.nowFn();return this.pruneExpired(e),this.timestamps.length>=this.maxActions?!1:(this.timestamps.push(e),!0)}get remaining(){return this.pruneExpired(this.nowFn()),Math.max(0,this.maxActions-this.timestamps.length)}reset(){this.timestamps=[]}pruneExpired(e){let t=e-this.windowMs,r=0;for(;r<this.timestamps.length&&this.timestamps[r]<=t;)r++;r>0&&(this.timestamps=this.timestamps.slice(r))}};var J0=100,V0=1e3,K0=3,X0=1e3;function Y0(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var qT=500;function Q0(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=qT?e:`${e.slice(0,qT)}\u2026(+${s.length} issues)`}var Eu=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new Au(e?.rateLimitMax??J0,e?.rateLimitWindowMs??V0),this.telemetry=e?.telemetry,this.fixSuggestionNotifier=e?.showFixSuggestion}registerPanel(e,{inbound:t=!0}={}){this.panels.add(e);let r=t?e.webview.onDidReceiveMessage(n=>{this.dispatch(n,e)}):void 0;if(!this.webviewSeen){this.webviewSeen=!0;for(let n of this.firstWebviewCallbacks.splice(0))this.runFirstWebview(n)}return{dispose:()=>{this.panels.delete(e),r?.dispose();for(let[n,o]of this.senders)o===e&&this.senders.delete(n)}}}onFirstWebview(e){if(this.webviewSeen){this.runFirstWebview(e);return}this.firstWebviewCallbacks.push(e)}runFirstWebview(e){try{e()}catch(t){this.logError("first webview",t)}}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>{this.handlers.get(e)?.delete(t)}}postToWebview(e){for(let t of this.panels)t.webview.postMessage(e)}replyToRequester(e){let t=typeof e.correlationId=="string"?this.senders.get(e.correlationId):void 0;if(t&&this.panels.has(t)){t.webview.postMessage(e);return}this.postToWebview(e)}get panelCount(){return this.panels.size}showFixSuggestion(e){this.fixSuggestionNotifier?.(e)}dispose(){this.handlers.clear(),this.panels.clear(),this.firstWebviewCallbacks=[],this.senders.clear()}logFn;setLogFunction(e){this.logFn=e}logError(e,t){let r=I(t);this.logFn?.(`[MessageBroker] Handler error for "${e}": ${r}`)}warn(e,t){try{this.telemetry?.addBreadcrumb(e,"bridge","warning"),this.telemetry?.getLogger?.()?.warn?.(t??{},e)}catch{}}dispatch(e,t){if(!Y0(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=pf.safeParse(e);if(!r.success){let o=Q0(r.error.issues);this.logFn?.(`[MessageBroker] Invalid enveloped payload: ${o}`),this.warn("bridge invalid payload",{issues:o});let i=e.payload,a=typeof i?.id=="string"?i.id:void 0;this.postBridgeError("invalid-payload",o,a);return}let n=r.data;af(n.protocolVersion)?this.mismatchCount=0:(this.mismatchCount++,this.warn("bridge protocol mismatch",{serverVersion:1,clientVersion:n.protocolVersion,count:this.mismatchCount}),this.postBridgeMismatch(n.protocolVersion),this.mismatchCount>=K0&&this.postBridgeReloadBanner()),t&&this.rememberSender(n.payload.id,t),this.continueDispatch(n.payload)}rememberSender(e,t){if(this.senders.delete(e),this.senders.set(e,t),this.senders.size>X0){let r=this.senders.keys().next().value;r!==void 0&&this.senders.delete(r)}}continueDispatch(e){if(!this.rateLimiter.tryAcquire()){this.logFn?.(`[MessageBroker] Rate limited: dropping message of type "${e.type}"`),this.postBridgeError("rate-limited",`"${e.type}" was dropped`,e.id);return}let t=this.handlers.get(e.type);if(!t){this.logFn?.(`[MessageBroker] Unhandled message type: "${e.type}"`),this.postBridgeError("unhandled-type",`no handler for "${e.type}"`,e.id);return}for(let r of t)try{let n=r(e);n&&typeof n.catch=="function"&&n.catch(o=>{this.logError(e.type,o)})}catch(n){this.logError(e.type,n)}}nextControlId(){return`bridge-${globalThis.crypto.randomUUID()}`}postBridgeError(e,t,r){this.postToWebview({id:this.nextControlId(),type:"bridge:error",timestamp:Date.now(),...r?{correlationId:r}:{},payload:{reason:e,details:t}})}postBridgeMismatch(e){this.postToWebview({id:this.nextControlId(),type:"bridge:protocol-mismatch",timestamp:Date.now(),payload:{serverVersion:1,clientVersion:e}})}postBridgeReloadBanner(){this.postToWebview({id:this.nextControlId(),type:"bridge:reload-banner",timestamp:Date.now(),payload:{reason:"protocol-mismatch"}})}};var Pu=class{constructor(e){this.broker=e}broker;disposers=[];route(e,t){let r=this.broker.on(e,n=>t(Object.freeze(n)));this.disposers.push(r)}routePrefix(e,t,r){for(let n of t)n.startsWith(e)&&this.route(n,r)}routeAll(e){for(let[t,r]of Object.entries(e))this.route(t,r)}get routeCount(){return this.disposers.length}dispose(){for(let e of this.disposers)e();this.disposers=[]}};var Cu=class{constructor(e){this.broker=e}broker;state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null};idCounter=0;pushTimer;disposed=!1;updateState(e){this.state={...this.state,...e},!this.pushTimer&&!this.disposed&&(this.pushTimer=setTimeout(()=>{this.pushTimer=void 0,this.pushState()},16))}setActiveOperations(e){this.updateState({activeOperations:e})}getState(){return this.state}pushState(){let e={id:`state-sync-${++this.idCounter}`,type:"state:sync",timestamp:Date.now(),payload:{...this.state}};this.broker.postToWebview(e)}dispose(){this.disposed=!0,this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0)}reset(){this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0),this.state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null}}};var $u=class{storage;prefix;logWarning;constructor(e,t="sandforge",r){this.storage=e,this.prefix=t,this.logWarning=r}async storeSecret(e,t){await this.storage.store(this.prefixKey(e),t)}async getSecret(e){return this.storage.get(this.prefixKey(e))}async deleteSecret(e){await this.storage.delete(this.prefixKey(e))}async storeObject(e,t){await this.storeSecret(e,JSON.stringify(t))}async getObject(e){let t=await this.getSecret(e);if(t)try{return JSON.parse(t)}catch(r){let n=I(r);this.logWarning?.(`[SecretVault] Failed to parse JSON for key "${e}": ${n}`);return}}async hasSecret(e){return await this.storage.get(this.prefixKey(e))!==void 0}prefixKey(e){return`${this.prefix}.${e}`}};var xu=class{orgs=new Map;listeners=new Set;onOrgChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}offOrgChange(e){this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){ne.warn("OrgManager listener threw",{error:I(r)})}}addOrg(e){let t=this.orgs.has(e.id);this.orgs.set(e.id,e),this.emit({type:t?"updated":"added",orgId:e.id,org:e})}removeOrg(e){let t=this.orgs.delete(e);return t&&this.emit({type:"removed",orgId:e}),t}getOrg(e){return this.orgs.get(e)}getAllOrgs(){return Array.from(this.orgs.values())}updateStatus(e,t){let r=this.orgs.get(e);if(!r)return!1;let n={...r,status:t};return this.orgs.set(e,n),this.emit({type:"statusChanged",orgId:e,org:n}),!0}findByTag(e){return this.getAllOrgs().filter(t=>t.tags.includes(e))}get connectedCount(){return this.getAllOrgs().filter(e=>e.status==="connected").length}clear(){let e=Array.from(this.orgs.keys());this.orgs.clear();for(let t of e)this.emit({type:"removed",orgId:t})}dispose(){this.listeners.clear(),this.orgs.clear()}};var gs="org.",Du="org-cred.",Yg="orgs",WT=1e4;function Z0(s){let e={...s,tags:Array.isArray(s.tags)?s.tags:[],appearance:{color:s.appearance?.color??"#4a9eff",icon:s.appearance?.icon??"cloud",position:s.appearance?.position??0}};return eL(e)}function eL(s){if(s.orgType===Wi(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=Wr("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Qu?t:s.appearance.color}}}var Nu=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(Yg),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(gs))continue;let i=Z0(o),a=i.orgId??i.id,d=n.slice(gs.length),c=t.get(a);if(!c){t.set(a,{key:n,org:i});continue}d===a?(r.push(c.key),t.set(a,{key:n,org:i})):r.push(n)}for(let n of r){this.configStore.delete(n);let o=n.slice(gs.length);this.secretVault.deleteSecret(`${Du}${o}`).catch(()=>{}),this.orgManager.removeOrg(o),ne.warn("Pruned duplicate org entry (same orgId as a canonical entry)",{key:n})}for(let{org:n}of t.values())this.orgManager.addOrg(n)}async saveOrg(e,t){let r=`${gs}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Pe(n)==="production"&&vo(e)&&n.appearance?.color===Qu?void 0:n?.appearance?.color,a=n?{...e,alias:n.alias??e.alias,appearance:{...e.appearance,color:i??e.appearance.color,icon:n.appearance?.icon??e.appearance.icon},tags:n.tags??e.tags,...n.staging!==void 0?{staging:n.staging}:{},...e.organizationName===void 0&&n.organizationName!==void 0?{organizationName:n.organizationName}:{}}:e;this.configStore.set(r,a,Yg),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${Du}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${gs}${e}`),await this.secretVault.deleteSecret(`${Du}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${Du}${e}`);t.catch(()=>{});let r;try{return await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{o(new Error(`Secret storage did not answer within ${WT} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},WT)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${gs}${e.id}`,e,Yg),this.orgManager.addOrg(e)}};import{mkdtemp as tL,readFile as rL,rm as nL}from"node:fs/promises";import{tmpdir as oL}from"node:os";import{join as Qg}from"node:path";async function zT(s){let e=await tL(Qg(oL(),"sandforge-sf-"));try{let t={stdout:Qg(e,"stdout.json"),stderr:Qg(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>rL(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await nL(e,{recursive:!0,force:!0}).catch(()=>{})}}var KT=10*1024*1024,sL=3e4,ju=3e4,rf=6e4,GT=12e4,JT=3e4,iL=4,aL=2e3,dL=/["%!\u0000-\u001f\u007f]/,VT=/^[A-Za-z0-9._-]+={0,2}$/;async function nf(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:KT,windowsHide:!0,env:dl(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function XT(s,e){if(dL.test(s))throw new Error(`The ${e} cannot contain ", %, ! or control characters on Windows: the command prompt that runs sf would act on them.`);return`"${s}"`}async function Mu(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:KT,windowsHide:!0,timeout:e.timeoutMs,env:dl()},i={},a=!1,d=l=>{a||(a=!0,clearTimeout(i.timer),n(l))},c=(l,g,p)=>{d({stdout:String(g),stderr:String(p),...l?{failure:{message:l.message,killed:l.killed}}:{}})},u=process.platform==="win32"?t(["sf",...s.map(l=>XT(l.value,l.role))].join(" "),o,c):r("sf",s.map(l=>l.value),o,c);i.timer=setTimeout(()=>{d({stdout:"",stderr:"",failure:{message:`sf did not finish within ${Math.round(e.timeoutMs/1e3)} s`,killed:!0}}),process.platform==="win32"&&u.pid!==void 0&&r("taskkill",["/pid",String(u.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+aL),u.stdin?.once("error",()=>{}),u.stdin?.end(e.input??"")})}var cL=V({status:Te().optional(),result:mn().optional(),message:j().optional(),name:j().optional()}).loose();function YT(s){try{let e=cL.safeParse(JSON.parse(ZT(s.stdout)));return e.success?e.data:void 0}catch{return}}function QT(s,e,t,r){let n=e?.message?.trim();if(n)return new Error(n);if(s.failure?.killed)return new Error(`${t} did not finish within ${r/1e3} s.`);let o=s.stderr.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);return new Error(o??s.failure?.message??`${t} failed without saying why.`)}var uL=V({id:j().min(1),username:j().min(1),instanceUrl:j().min(1),accessToken:j().nullish(),alias:j().nullish(),connectedStatus:j().nullish(),apiVersion:j().nullish(),devHubId:j().nullish(),status:j().nullish(),expirationDate:j().nullish(),edition:j().nullish()}).loose(),lL=V({username:j().min(1),orgId:j().min(1),instanceUrl:j().min(1)}).loose();function Zg(s,e,t=rf){let r=YT(s);if(s.failure||r?.status!==0)throw QT(s,r,e,t);let n=lL.safeParse(r.result);if(!n.success)throw new Error(`${e} succeeded but did not say which org it signed in to.`);return{username:n.data.username,orgId:n.data.orgId,instanceUrl:n.data.instanceUrl}}function ef(s){let e=Yi(s);if(!e.ok)throw new Error(`Invalid instanceUrl: "${s}" \u2014 expected an https:// Salesforce login host with no path (${e.reason})`);return e.origin}function ZT(s){let e=s.replace(/\u001b\[[0-9;]*m/g,""),t=e.search(/[{[]/);if(t===-1)throw new Error(`No JSON found in output (${s.length} chars): ${s.slice(0,200)}`);return e.slice(t)}function pL(s){if(/['\u0000-\u001f\u007f]/.test(s))throw new Error("The temporary folder path cannot contain a quote or control characters: the shell that runs sf would act on them.");return`'${s}'`}function gL(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:cl(I(s))??"an error that says nothing"}async function fL(s,e){let t=Date.now(),r=o=>process.platform==="win32"?XT(o,"temporary folder path"):pL(o),n=!1;try{let o=await zT(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await nf(d,{timeout:e})}),i=o.failure===void 0?void 0:n?gL(o.failure,e):I(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Is(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Is(I(o))}}}function eE(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Fu(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${of(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Fu(s){let e=cl(s);return e===void 0?void 0:Is(e).slice(0,200)}function of(s){return(s/1e3).toFixed(1)}function tE(s,e){return s.ms>=e-500}function hL(s,e,t,r,n){let o=Fu(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${of(s.ms)} s of the ${n/1e3} s allowed`+(tE(s,n)?" (it reached the limit)":"")+`, exit code 0, stdout ${s.stdout.length} chars, stderr ${s.stderr.length} chars`+(o?` ("${o}")`:""),`run with its output sent to files: ${eE(e)}`,t.failure?`the search for sf could not run: ${t.failure}`:`sf found: ${i(t.sf)}; node found: ${i(t.node)}`,`sf --version: ${r===void 0?"not run":r===""?"printed nothing":`"${r}"`}`,`sf runs from: ${Is(process.cwd())}`,`variables ${lh()}`].join("; ")}function mL(s,e,t,r,n){let o=Fu(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(u=>u.replace(/[\\/][^\\/]*$/,""))).size,d=t.runs?`This window runs ${t.runs}${a>1?` (sf is found in ${a} folders of its PATH)`:""}`:t.failure?`${i} could not run in this window (${t.failure.slice(0,200)})`:`${i} finds no sf this window can run`,c=r===void 0?"":r===""?", and its sf --version printed nothing either":`, and its sf --version says ${r}`;return`sf org list --json ended without an error and printed nothing${o?` (it said: ${o})`:""}, so there are no orgs to read. It ran ${of(s.ms)} s${tE(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${eE(e)}. ${d}${c}. In a terminal of this window, run sf org list --json and ${i}: another first line there means VS Code runs another sf than the terminal. Details in View > Output > SandForge.`}function tf(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function yL(s){return s.connectedStatus!==void 0?`the CLI reports ${s.connectedStatus}`:s.isScratch===!0&&(s.isExpired===!0||s.status==="Expired")?s.expirationDate?`a scratch org that expired on ${s.expirationDate}`:"a scratch org that expired":s.isScratch===!0?`a scratch org its Dev Hub reports ${s.status??"without a status"}`:"the CLI did not say it is connected"}async function wL(s){let e=await gh({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return Qi(e)}async function bL(s,e){let t=new Array(s.length),r=0,n=async()=>{for(;r<s.length;){let o=r++;t[o]=await s[o]()}};return await Promise.all(Array.from({length:Math.min(e,s.length)},n)),t}var Lu=class{constructor(e=mh,t=wL){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await nf("sf --version",{timeout:sL});return this.versionAnswer=Fu(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>tf(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!tf(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:yL(a),why:"notConnected"});let o=await bL(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:I(d)}}}),iL),i=[];for(let{entry:a,reason:d}of o)d===void 0?i.push(this.mapToSalesforceOrg(a)):e?.({username:a.username,alias:a.alias,orgId:a.orgId,reason:d});return i}async findOrg(e){let t=await this.displayOrg(e);if(!t||!tf(t))return;let r;try{r=await this.withUsableToken(t)}catch(n){throw new Error(`The Salesforce CLI gave no access token for ${t.username}: ${I(n)}`)}return this.mapToSalesforceOrg(await this.typedByTheOrg(r))}async displayOrg(e){if(!/^[\w.@+-]+$/.test(e)||e.startsWith("-"))throw new Error(`Invalid username format: "${e}"`);let t=await Mu([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:JT}),r=YT(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw QT(t,r,"sf org display",JT);let n=uL.safeParse(r.result);if(!n.success)throw new Error("sf org display succeeded but did not say which org it shows.");let o=n.data,i=typeof o.devHubId=="string"&&o.devHubId!=="";return{orgId:o.id,username:o.username,instanceUrl:o.instanceUrl,...o.alias?{alias:o.alias}:{},...o.accessToken?{accessToken:o.accessToken}:{},...o.connectedStatus?{connectedStatus:o.connectedStatus}:{},...o.apiVersion?{instanceApiVersion:o.apiVersion}:{},...i?{isScratch:!0}:{},...i&&o.status?{status:o.status}:{},...i&&o.expirationDate?{expirationDate:o.expirationDate}:{},...i&&o.edition?{orgEdition:o.edition}:{}}}async typedByTheOrg(e){if(e.isScratch===!0||e.accessToken===void 0)return e;try{let t=await this.readKind({instanceUrl:e.instanceUrl,accessToken:e.accessToken,...e.instanceApiVersion?{apiVersion:e.instanceApiVersion}:{}});return{...e,isSandbox:t.sandbox,...t.edition?{orgEdition:t.edition}:{}}}catch{return e}}async loginJwt(e){let t=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"jwt",role:"command"},{value:"--username",role:"flag"},{value:e.username,role:"username"},{value:"--jwt-key-file",role:"flag"},{value:e.keyFile,role:"private key file path"},{value:"--client-id",role:"flag"},{value:e.clientId,role:"consumer key"},{value:"--instance-url",role:"flag"},{value:ef(e.loginUrl),role:"login URL"}];return e.alias&&t.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),t.push({value:"--json",role:"flag"}),Zg(await Mu(t,{timeoutMs:rf}),"sf org login jwt")}async loginWithRefreshToken(e){if(!VT.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!VT.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(ef(e.instanceUrl)).host,r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"sfdx-url",role:"command"}];e.alias&&r.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),r.push({value:"--json",role:"flag"},{value:"--sfdx-url-stdin",role:"flag"});let n=`force://${e.clientId}::${e.refreshToken}@${t}
|
|
21
|
-
`;return Zg(await Mu(r,{timeoutMs:rf,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await nf(e,{timeout:ju});r=a.stdout,n=a.stderr}catch(a){let d=a;if(r=String(d.stdout??""),!r)throw new Error(`SF CLI failed with no output: ${d.message}`)}r.trim()===""&&(r=await this.rereadBlankOrgList(e,{ms:Date.now()-t,stdout:r,stderr:n}));let o=ZT(r),i;try{i=JSON.parse(o)}catch(a){throw new Error(`Failed to parse SF CLI JSON: ${a instanceof Error?a.message:a}. Output starts with: ${r.slice(0,300)}`)}return[...i.result?.nonScratchOrgs??[],...i.result?.scratchOrgs??[],...i.result?.sandboxes??[],...i.result?.other??[],...i.result?.devHubs??[]]}async rereadBlankOrgList(e,t){let r=await fL(e,ju),n=await ph(),o=hL(t,r,n,this.versionAnswer,ju);if(r.stdout.trim()!=="")return ne.warn(`${e} printed nothing on its pipe; what it wrote to a file was read instead. ${o}`),r.stdout;throw ne.warn(`${e} printed nothing, on its pipe or to a file. ${o}`),new Error(mL(t,r,n,this.versionAnswer,ju))}async loginWeb(e,t){if(e&&!/^[\w.-]+$/.test(e))throw new Error(`Invalid alias format: "${e}"`);let r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"web",role:"command"},{value:"--instance-url",role:"flag"},{value:ef(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),Zg(await Mu(r,{timeoutMs:GT}),"sf org login web",GT)}dedupeByOrgId(e){let t=new Map;for(let r of e)r.orgId&&!t.has(r.orgId)&&t.set(r.orgId,r);return Array.from(t.values())}async withUsableToken(e){if(ul(e.accessToken))return e;let t=await this.readToken(e.username);if(!ul(t.accessToken))throw new Error("the Salesforce CLI showed no usable access token");return{...e,accessToken:t.accessToken,instanceUrl:t.instanceUrl??e.instanceUrl}}mapToSalesforceOrg(e){let t=Xn({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=Wr(t),o={id:e.orgId,alias:e.alias||e.username,username:e.username,...typeof e.name=="string"&&e.name.trim()!==""?{organizationName:e.name.trim()}:{},instanceUrl:e.instanceUrl,orgId:e.orgId,orgType:t,authMethod:"sfdx_import",safetyTier:r,appearance:{color:n,icon:"cloud",position:0},metadata:{apiVersion:e.instanceApiVersion??bo.DEFAULT_API_VERSION,edition:e.orgEdition??"",features:[],...t==="Scratch"&&e.expirationDate?{expirationDate:e.expirationDate}:{}},status:"connected",lastConnected:new Date().toISOString(),tags:[]},i={loginUrl:e.instanceUrl,accessToken:e.accessToken,instanceUrl:e.instanceUrl,username:e.username};return{org:o,credentials:i}}};function RL(s,e){return e?new Promise((t,r)=>{let n=()=>r(e.reason);e.aborted?n():e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})}):s}var _u=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await RL(this.deps.metadataCompare.compare(e.sourceOrgId,e.targetOrgId,e.componentTypes,{includeManaged:e.includeManaged},t),t),i=this.deps.diffEngine.computeSummary(n),a=this.deps.diffEngine.computeCoverage(n,this.deps.metadataCompare.budget,o),d=Date.now()-r,c={configId:e.id,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:e.mode,summary:i,content:a,diffs:n,timestamp:new Date().toISOString(),duration:d};return this.results.set(e.id,c),c}getLastResult(e){return this.results.get(e)}};function vL(){return globalThis.crypto.randomUUID()}function rE(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function SL(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function kL(s){if(s.status!=="completed")return{};let e=s.output?.variables;return typeof e!="object"||e===null||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}function nE(s){return`Validation failed: ${s.join(", ")}`}function OL(s,e,t){let r=[["success",s.onSuccess],["failure",s.onFailure]];for(let[n,o]of r){if(!o)continue;let i=t.findIndex(d=>d.id===o);if(i>e)continue;let a=i===-1?`"${o}", which is not a step of this pipeline`:`"${t[i].name}", which does not come after it`;return`Step "${s.name}" routes on ${n} to ${a}: a route can only skip ahead.`}}var Uu=class{deps;activeRuns=new Map;handlers=new Map;cancelledRuns=new Set;aborters=new Map;constructor(e){this.deps=e}async execute(e,t,r,n){let o=this.deps.builder.validate(e);if(o.length>0){let h=this.createRun(e,t,r);return h.status="failed",h.error=nE(o),h.endTime=new Date().toISOString(),this.emit("failed",{runId:h.id,error:h.error}),h}let i=this.refuseUnrunnable(e,t,r);if(i)return i;let a=this.createRun(e,t,r);a.status="running",this.activeRuns.set(a.id,a);let d=new AbortController,c=()=>d.abort();n?.aborted&&d.abort(),n?.addEventListener("abort",c,{once:!0}),this.aborters.set(a.id,d),this.emit("started",{runId:a.id,pipelineId:e.id});let u=SL(e,t),{steps:l}=e,g=this.deps.conditionalRouter,p=!1,f=0;for(;f<l.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let h=l[f],m=await this.runStep(h,a,u,d.signal);if(a.stepResults.push(m),m.status==="skipped"){this.emit("stepSkipped",{runId:a.id,stepResult:m}),f+=1;continue}if(this.emit("stepCompleted",{runId:a.id,stepResult:m}),Object.assign(u,kL(m)),u[Xf]=m.status==="completed"?"succeeded":"failed",d.signal.aborted||m.status==="stopped"){a.status="cancelled";break}if(m.status==="failed"&&(p=!0,!h.continueOnError)){a.status="failed",a.error=m.error;break}let y=f+1;if(g.endsRun(h,m))y=l.length;else{let R=g.getNextStep(h,m),S=R?l.findIndex((w,O)=>O>f&&w.id===R):-1;S!==-1&&(y=S)}for(let R of l.slice(f+1,y)){let S=rE(R);a.stepResults.push(S),this.emit("stepSkipped",{runId:a.id,stepResult:S})}f=y}return a.status==="running"&&(a.status=p?"completed_with_warnings":"completed"),a.endTime=new Date().toISOString(),a.duration=new Date(a.endTime).getTime()-new Date(a.startTime).getTime(),n?.removeEventListener("abort",c),this.aborters.delete(a.id),this.activeRuns.delete(a.id),this.cancelledRuns.delete(a.id),this.deps.history.record(a),a.status==="failed"?this.emit("failed",{runId:a.id,error:a.error}):this.emit("completed",{runId:a.id,status:a.status}),a}cancel(e){if(this.activeRuns.has(e)){this.cancelledRuns.add(e),this.aborters.get(e)?.abort();let t=this.activeRuns.get(e);t&&(t.status="cancelled")}}getRun(e){return this.activeRuns.get(e)??this.deps.history.getRun(e)}getActiveRuns(){return[...this.activeRuns.values()]}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r)),r.add(t)}off(e,t){let r=this.handlers.get(e);r&&r.delete(t)}async runStep(e,t,r,n){if(e.condition&&e.type!=="condition"){let o;try{o=this.deps.conditionalRouter.evaluate(e.condition,r)}catch(i){return{stepId:e.id,stepName:e.name,stepType:e.type,status:"failed",error:`Step "${e.name}" did not run: its condition could not be evaluated, as ${I(i)}.`}}if(!o)return rE(e)}return this.emit("stepStarted",{runId:t.id,stepId:e.id}),this.deps.stepExecutor.execute(e,{variables:r,previousResults:t.stepResults,pipelineId:t.pipelineId,pipelineName:t.pipelineName,runId:t.id,signal:n})}refuseUnrunnable(e,t,r){let n=this.refusals(e);if(n.length===0)return;let o=this.createRun(e,t,r);return o.status="failed",o.stepResults=n.map(({step:i,reason:a})=>({stepId:i.id,stepName:i.name,stepType:i.type,status:"failed",error:a})),o.error=`Pipeline did not start: ${n.map(({reason:i})=>i).join(" ")}`,o.endTime=new Date().toISOString(),o.duration=new Date(o.endTime).getTime()-new Date(o.startTime).getTime(),this.deps.history.record(o),this.emit("failed",{runId:o.id,error:o.error}),o}check(e){let t=this.deps.builder.validate(e);return t.length>0?[nE(t)]:this.refusals(e).map(({reason:r})=>r)}refusals(e){let t=new Set(e.variables.map(r=>r.name));return e.steps.flatMap((r,n)=>{let o=this.deps.stepExecutor.check(r,{steps:e.steps,index:n,declared:t})??this.conditionProblem(r)??OL(r,n,e.steps);return o===void 0?[]:[{step:r,reason:o}]})}conditionProblem(e){if(!e.condition||e.type==="condition")return;let t=this.deps.conditionalRouter.check(e.condition);return t===void 0?void 0:`Step "${e.name}" runs only when its condition holds, and the condition ${t}.`}emit(e,t){let r=this.handlers.get(e);if(r)for(let n of r)n(e,t)}createRun(e,t,r){return{id:vL(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var Hu=class{operations=new Map;changeHandlers=new Set;cleanupTimers=new Map;register(e,t,r,n=0,o={}){let i={operationId:e,module:t,description:r,status:"running",percentage:0,processedRecords:0,totalRecords:n,currentStep:r,startedAt:new Date().toISOString(),elapsedMs:0,recordsPerSecond:0,...o.pausable?{pausable:!0}:{}};this.operations.set(e,i),this.notifyChange()}updateProgress(e,t,r,n,o){let i=this.operations.get(e);if(!i)return;let a=Date.now()-new Date(i.startedAt).getTime(),d=a/1e3,c=d>0?Math.round(r/d):0;i.percentage=Math.min(100,Math.max(0,t)),i.processedRecords=r,i.totalRecords=n,i.currentStep=o,i.elapsedMs=a,i.recordsPerSecond=c,this.notifyChange()}complete(e){let t=this.operations.get(e);t&&(t.status="completed",t.percentage=100,t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}partial(e){let t=this.operations.get(e);t&&(t.status="partial",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}fail(e,t){let r=this.operations.get(e);r&&(r.status="failed",r.error=t,r.elapsedMs=Date.now()-new Date(r.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}pause(e){let t=this.operations.get(e);t?.status==="running"&&(t.status="paused",this.notifyChange())}resume(e){let t=this.operations.get(e);t?.status==="paused"&&(t.status="running",this.notifyChange())}cancel(e){let t=this.operations.get(e);t&&(t.status="cancelled",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}offerResume(e,t){let r=this.operations.get(e);!r||r.status!=="cancelled"&&r.status!=="failed"||(r.resumeRun=t,this.notifyChange())}getAll(){return Array.from(this.operations.values())}getActive(){return this.getAll().filter(e=>e.status==="running"||e.status==="paused")}get(e){return this.operations.get(e)}onChange(e){this.changeHandlers.add(e)}offChange(e){this.changeHandlers.delete(e)}get activeCount(){return this.getActive().length}dispose(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),this.changeHandlers.clear()}scheduleRemoval(e,t){let r=this.cleanupTimers.get(e);r&&clearTimeout(r);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),this.notifyChange()},t);this.cleanupTimers.set(e,n)}notifyChange(){let e=this.getAll();for(let t of this.changeHandlers)t(e)}};var TL=3e4;function EL(s,e,t={}){let r=Xn({isSandbox:e.isSandbox,edition:e.orgType,...t.typeScratch===!0&&s.scratch===!0?{isScratch:!0}:{}}),{safetyTier:n,color:o}=Wr(r);return{id:e.orgId,alias:s.alias,username:e.username||s.username,instanceUrl:s.instanceUrl,orgId:e.orgId,orgType:r,authMethod:"sfdx_import",safetyTier:n,appearance:{color:o,icon:"cloud",position:0},metadata:{apiVersion:bo.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function PL(s,e,t){if(s.correlationId===e){if(s.type===t)return"answered";if(s.type==="bridge:error")return"refused";if(s.type.endsWith(":error"))return"failed"}}function CL(s){let e=s.payload??{};if(s.type.endsWith(":error")||s.type==="operation:failed"){let t=e.message??e.error??e.details??JSON.stringify(e);return`! ${s.type}: ${String(t)}`}if(s.type==="notification")return`! notification (${String(e.level)}): ${String(e.title)} \u2014 ${String(e.message)}`}function $L(s,e,t={}){return{compareOrchestrator:n=>new _u(n),automationOrchestrator:n=>new Uu(n),seedOrchestrator:n=>new _v(n),syncOrchestrator:n=>new Fv(n),getSandforgeSetting:(n,o)=>o,isAIEnabled:()=>!1,configStore:s,showNotification:n=>e(` notification: ${n}`),runsFrom:"commandLine",...t}}function xQ(s){let{log:e}=s,t=s.waitMs??5*6e4,r=al();hh("command line");let n=NR(AL(s.storeDir,"configStore.json")),o=new Map,i=new $u({get:S=>Promise.resolve(o.get(S)),store:(S,w)=>(o.set(S,w),Promise.resolve()),delete:S=>(o.delete(S),Promise.resolve())}),a=new xu,d=new Nu(n,i,a),c=new Lu,u=new cS;u.setSfdxBridge(c);let l=new Eu;l.setLogFunction(e);let g=new Pu(l),p=$L(n,e,s.services),f=new Iu({log:e,broker:l,stateSync:new Cu(l),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:u,sfdxBridge:c,services:p});f.setLiveOperationTracker(new Hu),s.compose?.({handlers:f,configStore:n,orgRegistry:d,orgManager:a,services:p,log:e}),f.registerAll(g);let h=[],m=new Set,y,R={webview:{postMessage:S=>{h.push(S);let w=CL(S);w&&e(` ${w}`),s.onPost?.(S);for(let O of[...m])O(S);return Promise.resolve(!0)},onDidReceiveMessage:S=>(y=S,{dispose:()=>{y=void 0}})}};return l.registerPanel(R),{posted:h,async connect(S){let w=await bh(S),O=await u.validateConnection(w.accessToken,w.instanceUrl),P=EL(w,O,{typeScratch:s.typeScratchOrgs===!0});return await d.saveOrg(P,{loginUrl:w.instanceUrl,instanceUrl:w.instanceUrl,accessToken:w.accessToken,username:w.username}),P},connectingRequests:()=>al()-r,request(S){let w=y;if(!w)return Promise.reject(new Error("No panel is registered with the broker."));let O=S.responseType??`${S.type}:response`,P=S.timeoutMs??TL,v={id:S.id??`wv-${IL()}`,type:S.type,timestamp:Date.now(),...S.payload!==void 0?{payload:S.payload}:{}},b=Date.now();return new Promise(C=>{let k=J=>{m.delete(T),clearTimeout(x),C(J)},T=J=>{let U=PL(J,v.id,O);if(!U)return;let K=Date.now()-b;k({outcome:U,message:J,elapsedMs:K,late:K>P})},x=setTimeout(()=>k({outcome:"unanswered",elapsedMs:Date.now()-b,late:!0}),Math.max(t,P));m.add(T),w({protocolVersion:1,payload:v})})}}}export{jn as a,oE as b,un as c,cp as d,lp as e,yd as f,DS as g,bd as h,jS as i,YL as j,fp as k,LS as l,nF as m,BS as n,oF as o,KE as p,xQ as q};
|