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-WQO7RXEB.mjs
DELETED
|
@@ -1,926 +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{b as Ka,c as dp,d as cp}from"./chunk-RY7WUJXH.mjs";import{b as fh}from"./chunk-UX4AOSMU.mjs";import{d as ha,k as sf,o as af,q as ga,r as df}from"./chunk-UZMLPKW6.mjs";import{a as kt,d as Ua,e as Kt,f as Tn,i as ys,j as St,k as at}from"./chunk-2METQHGG.mjs";import{a as yo,b as Ai,c as Ot,d as Nn,e as ji,f as nn,g as bo,h as $i,j as vi}from"./chunk-6FARZYMJ.mjs";import{a as Yf}from"./chunk-4BQPAVMP.mjs";import{b as vr,e as Xn}from"./chunk-RKTFFCNS.mjs";import{$ as Cp,$a as uh,A as sp,Aa as td,B as ip,Ba as Kp,C as ap,D as or,Da as Vp,E as Rs,Ea as Jp,F as An,Fa as Qp,G as up,H as lp,I as fp,J as Va,Ja as Yp,K as pp,Ka as Xp,L as hp,La as nd,M as gp,N as mp,Na as Zp,O as wp,P as Ja,Pa as eh,Q as Os,Qa as th,R as yp,Ra as nh,S as bp,Sa as rh,T as Rp,Ta as oh,U as vp,Ua as rd,V as Ep,Va as sh,W as Ip,Wa as ih,X as ir,Xa as od,Y as xp,Ya as ah,Z as Pp,Za as dh,_ as Fp,_a as ch,aa as Np,ba as Mp,ca as Bp,da as Ss,db as lh,ea as Ts,fa as As,ga as Lp,ha as Ya,hb as ph,i as hs,ia as Pt,ib as js,ja as Wp,jb as hh,kb as sd,la as Dp,lb as id,mb as ad,n as Ga,na as _p,nb as gh,o as Xf,oa as Xa,ob as mh,p as rr,q as De,qb as dd,r as Zf,ra as qp,rb as cd,s as bs,sa as Za,sb as wh,t as za,ta as Up,tb as yh,u as Ha,ub as bh,v as ep,vb as Rh,w as tp,wa as ed,x as np,xa as Gp,y as rp,ya as zp,z as op,za as Hp}from"./chunk-SAHGDSZQ.mjs";import{a as _r,b as ws,c as Jf,d as Qf,e as La,f as Wa,g as Da,h as _a,j as qa}from"./chunk-32ZB5ICW.mjs";import{a as Yi,b as nl,c as rl,d as ol,g as Cr,h as Uo,i as Xi,o as fl}from"./chunk-TG52WNGV.mjs";import{B as Ji,G as _o,M as Zn,N as tl,O as Fr,P as qo,a as fu,l as Vi}from"./chunk-CSSOLHE3.mjs";import{f as Df,g as Na,h as _f,i as Gf,j as zf,k as Hf,l as Kf,m as Vf,n as Ba,o as nr}from"./chunk-TEIBWMJM.mjs";import{c as Ma,e as gs,f as qf,g as Uf,h as ms}from"./chunk-BWWQXU2B.mjs";import{b as cl,c as ul,d as ll}from"./chunk-T63U4OZJ.mjs";import{a as pf,e as hf,h as gf,j as mf}from"./chunk-5EESNYE3.mjs";import{a as nf}from"./chunk-QAXKUEJT.mjs";import{a as Jl,b as Dr,c as Ql,d as is,f as Yl,g as Xl,h as fa,i as Zl,j as ef,k as tf}from"./chunk-JKFCGYJE.mjs";import{a as pl}from"./chunk-YYZL7UGV.mjs";import{a as Hu,c as Hi,g as Ku,h as Vu,i as Ju}from"./chunk-YDXMTWAT.mjs";import{b as rf,c as pa,e as of}from"./chunk-M6P5ZZLE.mjs";import{h as Vl,i as la,j as ss}from"./chunk-EINEGS6E.mjs";import{h as Zi}from"./chunk-RM5G4IP6.mjs";import{a as Qi}from"./chunk-QSRAEUGZ.mjs";import{a as Op,b as ks,d as kp,e as Qa,f as sr,g as Sp,h as Tp,i as Ap,m as jp,n as $p}from"./chunk-B5A4JHNN.mjs";import{c as al,d as dl,h as yl,j as bl}from"./chunk-YGE4AUXG.mjs";import{c as zo,n as Rl}from"./chunk-RFD6NPWJ.mjs";import{a as Ut}from"./chunk-AL4C3GFT.mjs";import{d as On}from"./chunk-P6A22FMQ.mjs";import{a as Zc,b as Cn,c as bn}from"./chunk-XZRON54U.mjs";import{b as hl,c as gl,g as ml}from"./chunk-AIUAEBHR.mjs";import{$ as Ln,A as Tl,B as Vo,Bc as Mf,C as Jo,D as Al,Dc as Bf,E as ra,Ec as ps,F as oa,Fb as jf,G as jl,Gb as $f,Hb as ba,I as $l,Ib as Ra,Ic as Pe,J as vl,Jb as ds,Jc as Ia,K as El,Kb as Oa,L as Qo,Lb as cs,Lc as xa,M as Il,Ma as lf,Mb as ka,Mc as Pa,N as xl,Nb as vf,Oc as Lf,P as sa,Pb as us,Q as ia,Qa as ff,Qc as Wf,R as Pl,Rb as Ef,Rc as Fa,S as Fl,Sa as Wn,Sc as Ca,T as Yo,U as Xo,V as Br,Vb as ls,W as Lr,Wb as If,X as Cl,Xa as bf,Xb as xf,Y as Nl,Yb as Pf,Z as Ml,Zb as fs,_ as Bl,_a as Rf,_b as Sa,a as $o,c as mu,d as Di,e as _i,ec as Ta,f as wu,fb as Of,g as qi,gc as Aa,h as Ui,hb as as,hc as ja,i as ea,ib as Dn,j as Nr,lc as $a,mc as va,n as wl,nb as kf,nc as Ff,o as Go,ob as Sf,pa as cf,q as ta,qb as Sn,qc as Ea,r as na,ra as uf,t as er,ta as ma,tb as Tf,tc as Cf,u as Ol,ub as Af,uc as Nf,v as Ho,w as tr,x as kl,xc as Wt,y as Sl,z as Ko}from"./chunk-O3ZQSWDN.mjs";import{f as Wi,h as pu,i as hu,j as gu}from"./chunk-DNE7JI3A.mjs";import{f as wo}from"./chunk-CI2O7WBH.mjs";import{i as wa,q as ya,r as wf,s as yf}from"./chunk-5T3LFDJ5.mjs";import{a as Xe}from"./chunk-4TLYUZD5.mjs";import{a as aa,b as kn,c as Ll,d as Zo,e as Wl,f as He,g as Dl,h as _l,i as es,k as ql,l as Ul,m as Gl,n as ts,o as da,p as zl,q as Ht,r as ns,s as on,t as ca,u as Hl,v as Wr,w as Kl,x as rs}from"./chunk-AX3YF7SC.mjs";import{a as Pr,c as yu,d as Gi,e as bu,f as Ru,g as Ou,h as ku,j as Su}from"./chunk-INIT2UKJ.mjs";import{b as Yc}from"./chunk-Q7TLC3I2.mjs";import{a as os,b as ua}from"./chunk-HF6LAK3G.mjs";import{l as Zu}from"./chunk-JBOGAUGH.mjs";import{b as el}from"./chunk-4N425UJC.mjs";import{a as Au,b as ju,c as Rn,d as Wu,e as Du,h as _u,i as qu,j as Uu,k as Gu,l as zu,m as zi}from"./chunk-TWYNQ2OO.mjs";import{b as Xc,d as eu,h as Oh}from"./chunk-LCDPCUXS.mjs";import{a as it,b as Mr}from"./chunk-TQ2TQHTT.mjs";import{b as Cu,c as Bo,d as Nu,e as Mu,f as Bu,g as Lo,i as Lu,l as Wo,m as Do}from"./chunk-HFSBDM7B.mjs";import{a as No,b as Mo}from"./chunk-OHEOJISY.mjs";import{a as vo,c as Tu}from"./chunk-EADHKH3A.mjs";import{a as Ao,b as jo,c as xr,e as lu}from"./chunk-FG4Y4ZVL.mjs";import{C as Pi,D as So,E as Bn,F as Ge,G as We,H as Fi,I as Ir,L as Ci,M as Ni,N as au,Q as Mi,X as Bi,a as Mn,aa as Li,b as $e,ba as du,c as ct,da as cu,f as tu,g as nu,h as ru,i as ou,ja as uu,ka as To,m as su,n as Ei,o as Oo,p as Ii,q as Se,r as ie,s as Er,t as rn,u as ko,w as xi,z as iu}from"./chunk-Z354SAEF.mjs";import{a as Ro,h as Le}from"./chunk-TZE3Y7IQ.mjs";import{b as V}from"./chunk-CA5NAXSU.mjs";import{c as Qu,f as Yu,j as Ki,k as Xu}from"./chunk-THYQOG24.mjs";import{a as ze,i as $u,j as vu,l as Eo,o as Io,p as Eu,q as xo,r as Iu,s as Po,t as xu,u as Pu,v as Fo,w as Fu,x as Co}from"./chunk-ICIYL45C.mjs";import{a as sl,d as il}from"./chunk-TUACWKIH.mjs";import{Ac as Tr,Ad as go,Cc as Ar,Da as Wc,Ec as et,Fc as Gt,Gc as tn,H as Pn,Hc as Oi,Hd as $r,I as uo,Ic as mt,Id as Kc,Kc as _c,Kd as Vc,Lc as Fn,Mc as Jn,Nc as jr,Oc as zt,P as vc,Pc as wt,Qd as Si,Rc as ki,Sc as qc,T as Ec,Vc as Uc,Vd as Ti,W as lo,Wc as Gc,X as fo,Y as mi,Yd as Jc,Z as kr,_ as wn,be as Qc,ca as Ic,da as xc,fd as Qn,fe as Yn,ge as mo,ha as Pc,ia as Fc,id as ho,ja as Cc,ka as Nc,na as po,oa as wi,pa as yi,qa as Mc,ra as bi,sa as Bc,ua as yn,uc as Sr,va as Lc,vd as zc,wc as Dc,wd as Hc,ya as Ri,zc as Ye}from"./chunk-CRPLDXJU.mjs";import{A as M}from"./chunk-WZQEK4WT.mjs";import{createHash as $y,randomUUID as Hs}from"node:crypto";import{existsSync as Yt,readFileSync as pn,readdirSync as vy,renameSync as am,rmSync as qs,statSync as dm,writeFileSync as cm}from"node:fs";import{basename as lc,dirname as Ey,join as Ks,resolve as Dt,sep as Iy}from"node:path";import{createReadStream as Vm,existsSync as Jm}from"node:fs";import{createInterface as Qm}from"node:readline";var kh=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Ym(r){let e=[],t=Qm({input:Vm(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:f}=JSON.parse(o),p=typeof f?.startedAt=="string"?f.startedAt:void 0;e.push({...p?{startedAt:p}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=Rl(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,u,l]=a;d==="x"?n(s,l):d==="p"&&typeof c=="string"&&kh.test(c)?s.wrote.push(c):d==="g"&&typeof u=="string"&&kh.test(u)&&s.wrote.push(u)}return e}async function Sh(r,e){if(!Jm(r))return[];let t;try{t=await Ym(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function _n(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function ar(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=_n(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function qn(r){return r.flatMap(e=>e.ids)}function sn(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function Fe(r,e=Date.now()){return Math.max(0,e-r)}var ud=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){Xe.warn("Event listener threw an error",{eventType:String(e),error:V(s)})}}removeAllListeners(){this.listenerMap.clear()}};var qr=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var Zm={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},$s=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??Zm[e]??"Name",i=Le(e),a=Le(s),d=new Map;for(let k of t){let O=k.Id,R=k[s];typeof O=="string"&&typeof R=="string"&&R&&d.set(O,R)}if(d.size===0)return{mappings:[],unmatched:t.map(k=>({sourceId:typeof k.Id=="string"?k.Id:"",matchValue:typeof k[s]=="string"?k[s]:null})).filter(k=>k.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,u=Pr(`${c})`),l=Pr(", "),f=new Map,p=[],h=u,g=async()=>{if(p.length===0)return;let k=`${c}${p.join(", ")})`;p=[],h=u;for(let O of await this.query(n,k)){let R=O.Id,w=O[s];typeof R=="string"&&typeof w=="string"&&f.set(w,R)}};for(let k of new Set(d.values())){let O=`'${Ro(k)}'`,R=(p.length>0?l:0)+Pr(O);p.length>=Ll||p.length>0&&h+R>14e3?(await g(),h+=Pr(O)):h+=R,p.push(O)}await g();let m=[],y=[];for(let[k,O]of d){let R=f.get(O);R?m.push({sourceId:k,targetId:R,matchedBy:s,matchValue:O}):y.push({sourceId:k,matchValue:O})}return{mappings:m,unmatched:y}}};function ld(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:Ol(r,e),fields:r}}async function an(r,e,t){return ld(await r(e,t),t)}function fd(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function dr(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var ew=new Map;function Th(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:u,targetLacks:l,inactiveOwners:f,excludedFields:p,fieldRename:h,creatableFields:g,updatableFields:m,picklistValuesByField:y,picklistFields:k,recordTypeValues:O,businessAccounts:R,contactPoints:w,decide:A,currencies:S,currencyFields:v=ew,parentCurrencies:j,pricedIn:P,outsideTheSample:B,heldByTheRun:I}=r,z=n.filter(K=>K.isReference).map(K=>K.name),Z=new Set(z),H=w?.forObject(e,n,h),U=K=>g.has(K.name)||h[K.name]!==void 0,J=new Set(n.filter(K=>K.isReference&&(K.referenceTo??[]).some(X=>i?.has(X))).map(K=>K.name)),je=new Set(n.filter(K=>{let X=K.referenceTo??[];return K.isReference&&X.length===1&&a?.has(X[0])===!0}).map(K=>K.name)),pe=lu(n.filter(K=>K.isReference),d),ae=k??new Map;return t.map(K=>{let X=[],ce=[],Te=[],we=[],de=u?.get(K);for(let G of n){if(!G.isReference||p.has(G.name)||de?.[G.name]!==void 0)continue;let Oe=U(G),ye=fd(G,m,h[G.name]);if(!Oe&&!ye)continue;let ue=K[G.name];if(B&&G.name!=="RecordTypeId"&&typeof ue=="string"&&ue!==""&&!o.get(ue)&&B(G,ue)){ce.push(G.name),Te.push(h[G.name]??G.name);continue}if(I&&G.name!=="RecordTypeId"&&typeof ue=="string"&&ue!==""&&!o.get(ue)&&I(ue)){ce.push(G.name),we.push(h[G.name]??G.name);continue}if(s!=="nullify"&&!J.has(G.name)&&!je.has(G.name)||G.name==="RecordTypeId"||pe.has(G.name))continue;let Ct=K[G.name];typeof Ct!="string"||!Ct||Oe&&o.get(Ct)||(ce.push(G.name),X.push({field:h[G.name]??G.name,sourceRefId:Ct,targetObjects:G.referenceTo??[],...ye?{}:{insertOnly:!0}}))}let _=z.filter(G=>G!=="RecordTypeId"),L=o.remapRecord(K,_);for(let G of ce)L[G]=null;for(let[G,Oe]of Object.entries(de??{}))L[G]=Oe;let Re=L.OwnerId,Ie=!1;typeof Re=="string"&&c[Re]&&(L.OwnerId=c[Re],Ie=!0);let Ne=ko(L,R?.has(K)===!0),he={},Ke=new Set,ve=[],E=[],W;for(let G of Object.keys(L)){if(p.has(G))continue;let Oe=h[G];if(Oe){L[G]!==null&&(he[Oe]=L[G]),Ke.add(Oe);continue}if(!g.has(G))continue;if(de?.[G]!==void 0){he[G]=de[G];continue}if(G!=="RecordTypeId"&&pe.has(G)&&!(G==="OwnerId"&&Ie)){if(s!=="keep")continue;let ue=L[G];if(typeof ue=="string"&&l?.has(ue)){ve.push(G);continue}if(G==="OwnerId"&&typeof ue=="string"&&f?.has(ue)){W=ue;continue}}else if(s==="keep"&&G!=="RecordTypeId"&&Z.has(G)){let ue=L[G];if(typeof ue=="string"&&l?.has(ue)){E.push(G);continue}}if(ho(e,G,Ne))continue;let ye=L[G];ye!==null&&(he[G]=ye)}let q=he.RecordTypeId;A?.(he,typeof q=="string"?q:void 0);for(let G of qc(e,he))delete he[G];let ge;S&&!Ke.has(ze)?ge=xo(he,{read:K[ze],currencyFields:v,recordTypeDefault:tr(O,q)?.picklists.get(ze)?.defaultValue,ratesOn:Eo(e,K),pricedIn:P?.(K)},S):j&&(ge=Pu(he,{read:K[ze],parent:xu(e,K,z,j.changeOf),currencyFields:v},j.currencies));let ee=Ho(he,y,ae,tr(O,q),Ke),te=su(e,he);for(let G of te)delete he[G];return H?.(he),{source:K,cleaned:he,nullifiedFks:X.filter(G=>!te.includes(G.field)),picklistChanges:ee,...ge?{currencyChange:ge}:{},...ve.length>0?{lookupsNotCarried:ve}:{},...E.length>0?{lookupsOutsideTheRun:E}:{},...Te.length>0?{lookupsOutsideTheSample:Te}:{},...we.length>0?{lookupsHeldBack:we}:{},...W!==void 0?{ownerInactive:W}:{}}})}var tw=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,Ah=Symbol("left to the platform"),vs=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];pastTheCap=new Map;cap=0;async expandForNode(e){if(!e.enabled)return;this.cap=e.maxExpansions;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(l=>l.isReference&&l.nillable===!1&&l.name!=="RecordTypeId");for(let l of n)for(let f of a){let p=l[f.name];if(typeof p!="string"||!p||o.get(p)||e.leftToThePlatform?.has(p))continue;let h=await this.parentObjectOf(e,f,p);if(!h)continue;let g=`${h}::${p}`;i.has(g)||i.set(g,{object:h,sourceId:p})}let d=4,c=[];for(let[,l]of i){let f=`${l.object}::${l.sourceId}`;if(!this.failedOrphans.has(f)&&!o.get(l.sourceId)){if(this.expansionsUsed+c.length>=e.maxExpansions){this.pastTheCap.set(f,l.object);continue}c.push({...l,cacheKey:f})}}let u=[c.filter(l=>l.object!==ie),c.filter(l=>l.object===ie)];for(let l of u){let f=[];for(let p=0;p<l.length;p+=d){let h=l.slice(p,p+d).filter(g=>!o.get(g.sourceId));await Promise.all(h.map(async g=>{try{let m=await this.expandSingleOrphanParent(e,g.object,g.sourceId);if(m===Ah)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(g.cacheKey),m.existing?o.addExisting(g.sourceId,m.id,g.object):(o.add(g.sourceId,m.id,g.object),m.owedStatus&&e.oweStatus?.(g.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(g.object,[g.sourceId]),g.object===Se&&rn(m.source)&&f.push(m.source)):(this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:[V(m)]})}}))}f.length>0&&await e.linkPersonContacts?.(f)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!Ao(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}capReport(){return this.pastTheCap.size===0?null:{cap:this.cap,notCopied:this.pastTheCap.size,objects:[...new Set(this.pastTheCap.values())]}}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:u,leftToThePlatform:l}=e;if(!tw.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let f=Le(t),p=await this.deps.describeFields(o,f),h=c?c(f,p):p,g=Ht(h,e.fieldExclusions?.[f]);g.length===0&&g.push("Id");let m=`SELECT ${g.join(", ")} FROM ${f} WHERE Id = '${Ro(n)}'`,y=await this.deps.queryRecords(o,m);if(y.length===0)return null;if(l&&l.keep(f,y).length===0)return Ah;let k=y[0],O=rn(k),R=O?await e.personAccountsInTarget?.():void 0;if(f===ie&&O&&R!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let w=null;try{w=ld(await this.deps.describeFields(s,f),f)}catch(_){Xe.warn(`[forge] orphan-parent target describe failed for ${t}: ${_ instanceof Error?_.message:String(_)}. Falling back to source createable.`)}let A=new Set(h.filter(_=>_.createable).map(_=>_.name)),S=w?dr(A,w.creatable):A,v=new Set(e.fieldExclusions?.[f]??[]),j=e.fieldMappings?.[f]??{},P=new Set,B=new Set(await e.maskedFieldsOf?.(f).catch(()=>[])??[]),I=[],z=S.has("RecordTypeId")&&!v.has("RecordTypeId")&&j.RecordTypeId===void 0,Z=f===Se&&O&&(e.businessAccountsAmong?(await e.businessAccountsAmong([k],z)).has(k):R===!1),H=ko(k,Z),U={};for(let _ of h){let L=_.name;if(v.has(L))continue;let Re=k[L];if(Re==null)continue;if(B.has(L)){(j[L]!==void 0||S.has(L))&&I.push(L);continue}if(_.isReference&&typeof Re=="string"&&L!=="RecordTypeId")continue;let Ie=j[L];if(Ie){U[Ie]=Re,P.add(Ie);continue}S.has(L)&&(ho(f,L,H)||(U[L]=Re))}if(e.contactPoints?.forObject(f,h,j)?.(U),w){let _=new Set([...S].filter(L=>!v.has(L)&&!j[L]));await this.checkPicklists(e,f,k,U,w,_,P)}let J=a&&i?a.apply([U],i,_=>gs(f,_))[0]:U,je=d?d(f,J,n,h):J,pe=u?await u(f,je):void 0,ae=await this.insertParent(e,f,n,je),K=ae.written,X=ae.callId;if(!K)return null;let ce=K.success?void 0:Xl(K,je,void 0),Te=K.errors;if(ce){let _=await this.insertParent(e,f,n,Vl(je,ce));if(!_.written)return{refused:["No result returned for record",fa(ce,Te)]};K=_.written,X=_.callId}if(K.success)return I.length>0&&e.onMaskedLeftOut?.(f,I),ce&&e.onWrittenWithoutFields?.(f,{rows:1,fields:ce.map(_=>({..._,rows:1}))}),{id:K.id,existing:!1,owedStatus:pe,source:k,...X!==void 0?{callId:X}:{}};let we=this.deps.describeObject?await this.deps.describeObject(s,f).then(_=>_.keyPrefix,()=>null):null,de=Xu(K,we);return de.kind==="linked"?{id:de.id,existing:!0,source:k}:{refused:ce?[...K.errors,fa(ce,Te)]:K.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&pl(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:p=>i.has(p),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(p=>p.name==="RecordTypeId")}):void 0;for(let p of d?.notes??[])e.onRecordTypeNote?.(t,p);let c=o.RecordTypeId,u=n[ze],l=e.currencies&&i.has(ze)&&typeof u=="string"&&u!==""?await e.currencies():void 0;if(l){let p=xo(o,{read:u,currencyFields:Io(s.fields),recordTypeDefault:tr(d?.byRecordType,c)?.picklists.get(ze)?.defaultValue,ratesOn:Eo(t,n)},l);e.currencyChanges?.add(t,p);let h=n.Id;p&&typeof h=="string"&&e.currencyChangesById?.set(h,p)}let f=Ho(o,s.picklistValuesByField,s.picklistFields,tr(d?.byRecordType,c),a);e.picklistChanges?.add(t,f)}};async function*Es(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function Vt(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return Es(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return Es((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function $h(r){let e=async(...n)=>{let[o,s,...i]=n,a=Gi(s),d=bu(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),u=l=>r.queryRecords(o,l);return a===void 0?Ou(c,d,u):ku(c,d,u,a)},t=(n,o,s)=>Su(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??jh(),s?.all?i=>nw(r.queryPages?.(n,i,s)??jh()):i=>r.queryRecords(n,i),Gi(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function nw(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*jh(){}var be=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},Wd=Dr;function ow(r){let e=r.from!=="plan"?r.from:r.fromTheJournal?"resumed":r.ofTheRunRetried?"retried":"simulation";return{objectApiName:r.objectApiName,count:r.ids.size,from:e,readAt:r.readAt}}var sw={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Ft=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Eh=2e3;function iw(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,linkedByThePlatform:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Ko,currencies:new Fo,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,ownersInactive:0}}function Ih(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function xh(r){return[Li(r.flagsNotKept),Sg(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function pd(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function hd(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var aw=5e3,dw=2e3,Ph="afterTask",gd=3,Fh=1e3,Gn=2e3;function Ur(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function cw(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(et))}function yg(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Ye(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!He.has(s)&&t.push(s)}return t}function uw(r,e,t){return yg(r,e).find(n=>t.has(n))}function lw(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!He.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var fw=3,pw=10,hw=5;function gw(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function Ch(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function Nh(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Gr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function Mh(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function Cs(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var mw={storage:{past:"past the data storage the target has left",more:", or free data storage in the target"},within:{past:"past the MB it may take (--fit-within)",more:", or let it take more (--fit-within)"},maxTotal:{past:"past the records it may write (--max-total)",more:", or raise --max-total"},targetRequests:{past:"past the API requests the target has left today",more:", or run it once the target has more to spare"},bulkBatches:{past:"past the Bulk API batches the target has left today",more:", or run it once the target has more to spare"},sourceRequests:{past:"past the API requests the source has left today",more:", or run it once the source has more to spare"},heavyRoots:{past:"past what the sample may take",more:""},whole:{past:"past what the sample may take",more:""},draw:{past:"past what the sample may take",more:""}};function Bh(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var Pd=class extends ir{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},Fd=class extends ir{constructor(t,n){super("SAMPLE_TOO_LARGE",t);this.sample=n}sample},Lh=3;function ww(r,e){let t=e.slice(0,Lh).map(({sourceId:i,matchValue:a})=>({recordSummary:`Id=${i} matchValue=${a??"null"}`,messages:[a===null?`This ${r} has no name to find it by in the target org: the records that point at it are not linked to one.`:`No ${r} of the target org is named "${a}": the records that point at it are not linked to one. Create a ${r} of that name in the target\u2019s Setup, or rename one of the target\u2019s to it, then run again.`]})),n=e.slice(Lh);if(n.length===0)return t;let o=n.map(({matchValue:i})=>i===null?"no name":`"${i}"`),s=o.length===1?o[0]:`${o.slice(0,-1).join(", ")} or ${o.at(-1)}`;return[...t,{recordSummary:`${n.length} more`,messages:[`No ${r} of the target org is named ${s} either.`]}]}function yw(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function Wh(r){let e=Cs(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function bw(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function Rw(r,e,t){let n=t.filter(d=>d.isReference),o=d=>n.filter(c=>(c.referenceTo??[]).includes(d)),s=d=>{let c=o(d);return c.length>0&&c.every(u=>(u.referenceTo??[]).length>1)},i=d=>{let c=o(d);return c.length>0&&c.every(u=>u.nillable===!0)},a=new Set(ts(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&Gl(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!Tr(d)||!Ye(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function Ow(r,e){return Cd(Hr(r.values()),e)}function Hr(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function Cd(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[Do({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var kw=3,Dh=5e4;function Sw(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Gn):0),0)}var md={field:"",parentObject:"",reason:"the source does not hold it"};function wd(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}var _h={field:"",parentObject:"",reason:"the source holds it outside its object's filter"};function yd(r,e){return`${r} may not be left empty, and names a ${e} record outside the ${e} filter`}function Tw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function Aw(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function qh(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function jw(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Ye(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var $w="held back for a record type closed to the user the run writes as",vw="held back for a record type the target has none of";function Uh(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:$w}]:[],...t>0?[{count:t,why:vw}]:[],...n>0?[{count:n,why:Nd}]:[]]}function Gh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function zh(r,e){return zi(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,Tg(e))}function Ew(r,e,t){let n=r.leftAside.get(e)??new Map;Hr(t,n),r.leftAside.set(e,n)}function Iw(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function xw(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function Ns(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${nu(n,t)}`).join("")+Iw(r,e)}function Pw(r){return[...Fw(r),...xw(r)]}function Fw(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:ru(o,n),messages:[ou(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Kr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function Cw(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Kr(t)}`).join("; ")}function Nw({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Kr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Kr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===zt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var Nd="held back for want of their parent",Hh=" \u2014 the records that cannot be written without one of those not written are held back",Kh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function Ms(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Kr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Qt(r,e){return Ms(r.heldForExclusions.get(e)?.values()??[])}function zn(r){return r.reduce((e,t)=>e+t.count,0)}function cn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function Bs(r,e=!1){let t=zn(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+cn(r)}function Vh(r,e){return Ns(r,e)+Bs(Qt(r,e))}function Mw(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[Nw(o)]}})}})}function Bw(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function Jh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=Bw(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function jn(r,e,t=[]){let n=e+zn(t);return`Held back ${r}, nothing written, ${n} failed${cn(t)}`}function Qh(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function bg(r,e=0){let t=r+e;if(t<=0)return"";let n=e>0?` (${e} of them outside the sample, with an account the run wrote)`:"";return`, ${t} written by the platform with their person account${n}`}function bd(r,e){if(e!==ie)return 0;let t=r.personContactsOutsideTheSample;return r.personContactsOutsideTheSample=0,t}function Un(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function Md(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function Rg(r,e,t,n){let o=Math.min(e,Math.max(0,t)),s=Math.min(e-o,Math.max(0,n?.rows??0)),i=e-o-s,a=r.dryRun?"the run would create (the target would refuse them as copies of those)":"the run created (the target refused them as copies of those)";return(i>0?`, ${i} linked to records already in the target`:"")+(o>0?`, ${o} linked to records ${a}`:"")+(n&&s>0?`, ${s} written by the platform with ${Bn(n.objectApiName)}`:"")}var Lw=3;function Rd(r,e,t,n,o=0){let s=r.dryRun?"would be inserted":"succeeded",i=t.updated>0?`, ${t.updated} updated through their external id`:"",a=Rg(r,t.linked,t.linkedToCreated,{objectApiName:e,rows:t.linkedByThePlatform}),d=bg(t.withTheirAccount,o),c=t.withTheirEmail>0?`, ${t.withTheirEmail} written by the platform with their email`:"",u=Og(t.teamOwners,t.teamOthers)+kg(t.rolesOfTheirOpportunity,t.rolesGiven),l=t.writtenBefore>0?`, ${Md(r,t.writtenBefore)}`:"",f=t.unidentified>0?` (${t.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${t.succeeded} ${s}${i}${a}${c}${d}${u}${l}, ${t.failed+zn(n)} failed${f}${cn(n)}`}function Og(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function kg(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function Ww(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[We];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function Dw(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function Sg(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function zr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):Cw(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${jn(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Yh(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(l=>l.isReference),c=He.has(s),u=r.scopeCache?.reachedOf(s);for(let l of i){let f=l.Id,p={row:l,lookups:d};c&&typeof f=="string"&&f!==r.config.rootRecordId&&r.roots?.ids.has(f)!==!0&&u?.has(f)!==!0?t.set(f,p):n.push(p)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function Xh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&r.roots?.ids.has(t)!==!0&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function Zh(r){for(let[e,t]of Object.entries(Ar))if(t.object===r)return{parent:e,lookup:t.lookup}}function _w(r,e){return e.filter(t=>t.isReference&&Ye(r,t.name,t.nillable)).map(t=>t.name)}function qw(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function Od(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function eg(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function kd(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function Sd(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Uw(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}function Td(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the record it names is held back by the run`}function Ad(r,e){for(let{lookupsHeldBack:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Gw(r){return[...r.lookupsHeldBack].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the record it names is one the run holds back or leaves aside, never written.`]}))}))}var tg=10;function jd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function ng(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function zw(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function Hw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,tg).join(", "),i=o.length-tg;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function Is(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function $d(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function Kw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function cr(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function Vw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function rg(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var Ls=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},og="files",vd=200,Jw=Gn,Ed=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function sg(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function Qw(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function ig(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||V(r).includes("INVALID_QUERY_LOCATOR")}function ag(r){if(Yc(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:V(r).includes("SERVER_UNAVAILABLE")}function dg(r){return new Promise(e=>setTimeout(e,r))}function Yw(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function xs(r,e){return jo(e)?xr(e)?!0:!r.writtenObjects.has(e):!1}function dn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function cg(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function Xw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Nu)}function Tg(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var ug=200,lg=200,Bd=/[\u0000-\u001f]/;function Id(r,e){if(!mt(e))return"";let t=[...qa(r.pricesSwappedSaid),...Zw(r)];return t.length===0?"":`, ${t.join("; ")}`}function Zw(r){let e=[...r.pricesKeptAsRead].filter(([s])=>!r.prices.standsFor.has(s)).map(([,s])=>s);if(e.length===0)return[];let t=s=>{let i=new Map;for(let a of s)i.set(a,(i.get(a)??0)+1);return[...i].map(([a,d])=>`${d} ${a}`).join(", ")},n=e.filter(s=>s.to!==void 0&&s.from!==s.to);if(n.length>0)return[`${t(n.map(({from:s,to:i})=>`${s} \u2192 ${i}`))}: no price in the currency written in the source for the same product and price book, written in it at its amount as read, not converted`];let o=e.filter(s=>s.to===void 0).map(({from:s})=>s);return new Set(o).size<2?[]:[`prices written in the target's one currency, which it did not say: ${t(o)}, at their amount as read, not converted`]}var ey=/^012000000000000(AAA)?$/;function fg(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var ty=["insert","upsert"],ny=["insert","upsert","update"];function pg(r,e){let t="";for(let n of ty){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function ry(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[Ku(r),...r.notSplit>0?[Vu(r.notSplit,e,"run")]:[]]}]}}function oy(r){return ny.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>ry(t,Ju(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function Ps(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Cp(s),a=o===!0&&n===void 0?Mp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:u},l)=>d===void 0?[]:[{sourceId:d,fingerprint:Np(c,i),owes:u,...n!==void 0?{externalKey:Bp(c,n)}:{},...a[l]!==void 0?{jobKey:a[l]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function hg(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var sy=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],iy=new Set(["CreatedDate","LastModifiedDate"]),ay=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function dy(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Fs(r){return typeof r=="string"?Date.parse(r):Number.NaN}var gg="005",Ld=class{ids=new Set;issued=0;uniqueValues=new Map;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}holderOf(e,t,n){return this.uniqueValues.get(`${e}.${t}`)?.get(n)}hold(e,t,n,o){let s=`${e}.${t}`,i=this.uniqueValues.get(s)??new Map;i.has(n)||i.set(n,o),this.uniqueValues.set(s,i)}};function mg(r,e){return e.filter(t=>t.unique===!0&&t.createable&&!(r.upsertMode==="auto"&&t.externalId===!0))}function cy(r,e){let t=r[e];return typeof t=="string"&&t!==""&&!Bd.test(t)?t:void 0}function uy(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function ly(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&Ma(n)?"masterInSource":"notRead"}function fy(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function xd(r,e){return[r[Fn],e?r[Jn]:"",r[wt]].map(t=>String(t??"")).join("|")}function wg(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||ay.has(n.type)))}var py=200,hy="the standard price of its product, which it may not go without, changed since the sample";function gy(r){return r?{sample:r}:{}}function my(r){let e=r.options,t=Object.entries(e.rootWhere??{});return{seed:e.seed??yn.seed,draw:e.draw??yn.draw,parents:e.parents??yn.parents,children:e.children??yn.children,floor:e.floor??yn.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{},...e.window?{window:{...e.window}}:{},...t.length>0?{rootWhere:Object.fromEntries(t)}:{},...e.strata&&e.strata.length>0?{strata:[...e.strata]}:{}}}var ur=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=$h(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??ua;return Xe.info(`[forge] writing through the Bulk API: a job per ${Dr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...os,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...os,...o]),bulkUnsupported:new Set,manager:new fu(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new be("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new be("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(u=>[u.name,u]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(u=>{let l=c.get(u);return{name:i[u]??u,type:l?.type??"",...l?.length!==void 0?{length:l.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}async fieldExclusionsOfTheSource(e,t,n){let o=Object.keys(e);if(o.length===0)return{exclusions:{},unmatched:[]};let s=t.nodes.map(a=>a.objectApiName),i=new Map;for(let a of o){let d=s.find(c=>c.toLowerCase()===a.toLowerCase())??a;if(!i.has(d))try{let c=await this.deps.describeFields(n,d);i.set(d,c.map(u=>u.name))}catch(c){i.set(d,nr(c)?void 0:null)}}return ns(e,s,a=>i.has(a)?i.get(a):null)}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new yp;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=Bl(s);if(a.files){let j=uo(a.anonymization!==void 0,a.files.acceptedAsIs);if(j)throw new An(j,"FILES_NOT_ACCEPTED");let P=this.fileCopyUnwired();if(P)throw new An(P,"FILES_NOT_COPYABLE")}let d=await this.chooseTheRoots(a,t,a.dryRun?void 0:a.stream?.store),c=await Rs(a.ownerMappings,j=>this.deps.queryRecords(n,j),or);if(c)throw c;let u=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,u),f=await this.fieldExclusionsOfTheSource(a.fieldExclusions,e,t),p={...a,fieldExclusions:f.exclusions,...l.bySource.size===0?{}:{recordTypeMappings:jl(a.recordTypeMappings,l),recordTypeDecisions:l.bySource}},h=p.dryRun?new Ld:null,g=p.excludedObjects,m=await this.withWhatStatusesNeed(es(e,g),t,g),y=p.isScoped?await this.withWhatItsRecordsComeWith(m.graph,t,g):m.graph,k=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(y,t,g),t,g),O=this.deps.recordTypePicklists,R=p.dryRun?void 0:p.stream?.store,w=new Date;R?.beginPart(w),d&&R&&!d.fromTheJournal&&R.nameRoots({objectApiName:d.objectApiName,ids:[...d.ids],sha256:d.sha256,readAt:d.readAt,...d.query?{query:d.query}:{}});let A=Hu(),S=await this.bulkTransportOf(p,n),v={...S?{bulk:S}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:k,onProgress:o,remapper:new qr(R),scopeCache:p.isScoped?new Xf:null,scopedBuilder:p.isScoped?new kn:null,recordTypeMapper:p.recordTypeMappings?new ms:null,referenceDataMapper:new $s((j,P)=>this.deps.queryRecords(j,P)),orphanExpander:new vs(h?uy(this.deps,h,async(j,P)=>this.deps.describeObject?this.deps.describeObject(j,P).then(B=>B.keyPrefix,()=>null):null):this.deps),batchWriter:new ef(this.deps,this.deps.batchStrategy,void 0,A),splitting:A,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,fieldExclusionsUnmatched:f.unmatched,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:ap(j=>this.deps.queryRecords(n,j)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:R?{add:j=>R.noteRead(j),has:j=>R.wasRead(j)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(k.nodes.filter(j=>j.included).map(j=>j.objectApiName)),writtenObjects:new Set,sellingModels:k.nodes.some(j=>j.included&&j.objectApiName===jr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...R?{store:R}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:m.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:p.anonymization?this.anonymizerForRun():null,contactPoints:p.keepContactPoints?null:new _f(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:dl(al(j=>this.deps.queryRecords(t,j)),async j=>({fields:await this.deps.describeFields(t,j)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new kl(O&&((j,P)=>O(n,j,P))),picklistChanges:new Ko,currencyChanges:new Fo,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],pricesKeptAsRead:new Map,prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:w,writtenByThePlatform:new Map,personContactsOutsideTheSample:0,contactSentWith:new Map,leftToThePlatform:new tu,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,...d?{roots:d}:{},readUnder:new Map,simulated:h,gaps:p.dryRun?new Du:null,decisionsApplied:new ra,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:u,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[j,P]of p.writtenBefore)v.remapper.addExisting(j,P);for(let{decision:j,reason:P}of l.unresolved)v.errors.push({objectApiName:j.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${j.from} \u2192 ${j.to??"the default"})`,messages:[`The decision was not applied: ${P}.`]}]});this.running=v;try{return await this.runPasses(v)}catch(j){throw this.endBeforeTheEmailsThatWaited(v,v.emailsAfterTheirTask.length+v.emailsLeftForTheirTask,j instanceof be),this.saySyncedQuotesLeft(v),await this.readWrittenBetween(v),this.reportDraftsLeft(v),R?.settleReads(),bp(j,this.summaryOf(v)),j}finally{this.running===v&&(this.running=null),R?.settleReads(),R?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return oa([],[]);let s=this.deps.describeObject,i=async(c,u)=>s?s(c,u).then(l=>this.namedRecordTypes(o,c,l.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return oa(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,No).then(s=>Mo(s),()=>[]),e.set(t,o)),Bo(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>Pn(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!Pn(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of On(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let u of c){let l=Fs(u.SystemModstamp),f=g=>{let m=a?Number.NaN:Fs(u[g]);return Number.isFinite(m)?m:l},p=f("CreatedDate"),h=f("LastModifiedDate");Number.isFinite(p)&&(t=Math.min(t,p)),Number.isFinite(h)&&(n=Math.max(n,h))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=dy(e.startedAt.getTime()-Ya),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Le(a),l=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],f=!1;for(let p of l)try{let[h]=await this.deps.queryRecords(e.targetOrgId,p),g=Fs(h?.f),m=Fs(h?.l);Number.isFinite(g)&&(o=Math.min(o,g)),Number.isFinite(m)&&(s=Math.max(s,m)),f=!0;break}catch{}f||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+Ya)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Le(t);for(let s of sy)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>iy.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&e.roots&&t.rootObjectApiName?e.scopeCache.add(t.rootObjectApiName,e.roots.ids):e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=ql(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&qw(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let u=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let R of u)R.included&&e.turnsAhead.add(R.objectApiName);if(n.nodes.some(R=>mt(R.objectApiName)))try{let[R,w]=await Promise.all([this.deps.queryRecords(o,Oi),this.deps.queryRecords(s,Oi)]),A=R[0]?.Id,S=w[0]?.Id;typeof A=="string"&&typeof S=="string"&&(e.standardPricebookId=A,e.remapper.addExisting(A,S),e.scopeCache?.add(Gt,[A]),e.readObjects.add(Gt),n.nodes.some(v=>v.included&&v.objectApiName===Gt)||e.scopeCache?.addRead(Gt,[]))}catch(R){e.errors.push({objectApiName:et,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[V(R)]}]})}let l=new Map,f=this.deps.isObjectCreatable;if(f){let R=[...new Set(a.filter(w=>w.included&&!t.referenceDataObjects.has(w.objectApiName)).map(w=>w.objectApiName))];for(let w=0;w<R.length&&!this.isAborted;w+=6){let A=R.slice(w,w+6),S=await Promise.allSettled(A.map(async v=>f(s,v)));A.forEach((v,j)=>l.set(v,S[j]))}}for(let[R,w]of l)w.status!=="rejected"||!nr(w.reason)||(e.notInTarget.add(R),e.readObjects.delete(R),e.turnsAhead.delete(R));for(let R of n.nodes){let w=l.get(R.objectApiName);!R.included||w?.status==="fulfilled"&&!w.value||e.notInTarget.has(R.objectApiName)||e.writtenObjects.add(R.objectApiName)}d&&await this.planTheSample(e,u),d&&t.beforeWrite&&await this.countBeforeWrite(e,u);for(let R of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!R.included){e.skippedCount++,i({objectName:R.objectApiName,status:"skipped",progress:100,message:`Skipped ${R.objectApiName} (${bw(R)})`});continue}if(e.notInTarget.has(R.objectApiName)){e.scopeCache&&R.objectApiName!==t.rootObjectApiName?(e.notInTargetPutOff??=[]).push(R):this.reportNotInTarget(R,e),await this.endTurn(R.objectApiName,e);continue}if(await this.skipForFailedParent(R,e)){await this.endTurn(R.objectApiName,e);continue}let w=l.get(R.objectApiName);if(w)if(w.status==="fulfilled")w.value||e.notCreatable.add(R.objectApiName);else{let A=w.reason;e.errors.push({objectApiName:R.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${A instanceof Error?A.message:String(A)}`]}]})}c?await this.readInTurn(R,e):d&&this.streamsNode(R,e)?(await this.streamNode(R,e),e.turnsEnded.add(R.objectApiName),R.objectApiName===ct&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(R,e,!1,!0)&&await this.writeNode(R,e),e.turnsEnded.add(R.objectApiName),R.objectApiName===ct&&await this.writeEmailsAfterTheirTask(e),R.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,R.objectApiName))}let p=Ul(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),h=p.map(R=>He.has(R.objectApiName)).lastIndexOf(!0);for(let[R,w]of p.entries()){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(w,e)||(c?(e.scopeCache&&He.has(w.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,w.objectApiName)),await this.readNode(w,e,!1,!1),await this.readUnderWhatWaited(w.objectApiName,e,h>=0&&R>h?"after the catalog":"before the catalog")):await this.readNode(w,e,!1,!0)&&(await this.writeNode(w,e),e.turnsEnded.add(w.objectApiName),this.releaseRows(e,w.objectApiName)))}await this.readCatalogAgain(e,h<0?[]:p.slice(h+1)),await this.reportNotInTargetOfTheScope(e);for(let R of[...e.preread.keys()])this.releaseRows(e,R,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let g=this.deps.requestsSent?.();e.roots&&g!==void 0&&e.requestsBefore!==void 0&&(e.readRequests=g-e.requestsBefore);let m=t.stream?.everything===!0,y=t.files&&!m?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let R=await this.pricesTheGateCounts(e),w=Wh(e).cappedObjects,A=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([j,P])=>this.toWriteAtTheGate(e,j,P,mt(j)?R:0))))),S=t.dryRun?0:await this.readBackRequests(e,A),v=await t.beforeWrite({objects:A,...w?{capped:w}:{},...S>0?{readBack:S}:{},...e.roots?{roots:ow(e.roots)}:{},dryRun:t.dryRun});await this.afterTheGate(e,v,A)}if(c)for(let R of this.writeOrderOf(e)){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let w=e.preread.get(R.objectApiName);if(w&&!await this.skipForFailedParent(R,e,w.fieldInfos,w.records)&&(await this.writeNode(R,e),R.objectApiName===ct&&await this.writeEmailsAfterTheirTask(e),R.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let A=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),S=[],v=await Ka({pendingFkUpdates:A,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:S,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(j,P,B)=>this.noteLeftEmptyByFilter(e,j,P,B),...this.secondPassOfTheSample(e)});v&&e.errors.push(v),e.pendingFkUpdates.push(...S)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let k=e.secondPassInStore?await this.secondPassFromTheJournal(e):await Ka({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(R,w,A)=>this.noteLeftEmptyByFilter(e,R,w,A),...this.secondPassOfTheSample(e)});if(k&&e.errors.push(k),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");y.length>0&&!t.dryRun?await this.writeFiles(e,y):m&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let O=e.orphanExpander.buildErrorReport();return O&&e.errors.push(O),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||Ma(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){Xe.warn(`[forge] the mute's lease was not given back as the writes ended: ${V(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,Kf(t,n.ids));n.readBack=Vf(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:V(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=zf(Gf(i)),d=e.config.recordTypeDecisions;return(c,u)=>{let l=e.recordTypesGiven.get(t);l||(l={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,l));let f=ly(c,o,d);l.rows++,l.why[f]=(l.why[f]??0)+1,u!==void 0&&l.ids.length<Hf&&l.ids.push(u)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===$e)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},u=n.described.filter(y=>y.externalId===!0&&y.createable&&y.queryable&&!d.has(y.name)&&c[y.name]===void 0);if(u.length===0)return a;let l=n.described.find(y=>y.name==="Id"),f=on({node:t,edges:e.graph.edges,fieldInfos:[...l?[l]:[],...u],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(f.kind!=="query"||f.statements.length!==1)return a;let p=f.limit??1/0,h=new Map(u.map(y=>[y.name,new Set])),g=0,m=Vt(this.deps,s,f.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let y of m){for(let k of y){if(g>=p)break;g++;for(let[O,R]of h){let w=k[O];typeof w!="string"||w.length===0||R.has(w)?h.delete(O):R.add(w)}}if(g>=p||h.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(h.keys()),sent:a.sent}}catch(d){return Xe.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+V(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!He.has(n)&&!mt(n)&&(n!==ct||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(He.has(t)||mt(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&pf.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=Vt(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async chooseTheRoots(e,t,n){let o=e.roots,s=n?.resumes===!0,i=s?n?.roots:void 0;if(!o){if(i)throw Pe.of(Lr(i.objectApiName,"otherQuery"));return}let{objectApiName:a,cap:d}=o,c={cap:d,readTotal:o.readTotal,readingBound:$l(o.sourceRequestsLeft),...o.sourceRequestsLeft!==void 0?{sourceRequestsLeft:o.sourceRequestsLeft}:{}};if(s){if(!i)throw Pe.of(Cl(a));if(i.objectApiName.toLowerCase()!==a.toLowerCase())throw Pe.of(Lr(a,"otherQuery"));if(ia(i.ids)!==i.sha256)throw Pe.of(Lr(a,"changed"));return{objectApiName:a,from:"plan",...i.query?{query:i.query}:{},ids:new Set(i.ids),sha256:i.sha256,readAt:i.readAt,fromTheJournal:!0,...c}}let u,l=o.plan;if(l){let m=Fl(l,{sourceOrgId:t,objectApiName:a,...o.query?{query:o.query}:{},...o.ids?{ids:o.ids}:{}});if(m)throw Pe.of(Lr(a,m));let y=o.planOfTheRunRetried===!0;if(Up(l,new Date)<_p||o.query===void 0||y)return{objectApiName:a,from:"plan",...l.query?{query:l.query}:{},ids:new Set(l.ids),sha256:l.sha256,readAt:l.readAt,fromTheJournal:!1,...y?{ofTheRunRetried:!0}:{},...c};u={roots:l.ids.length,readAt:l.readAt}}let f,p,h;if(o.ids!==void 0){let m=o.ids.filter(y=>!Pl(y));if(m.length>0)throw Pe.of({code:"ROOTS_QUERY_REFUSED",message:`${JSON.stringify(m[0]?.slice(0,40))} is not the id of a record: name each ${a} record by its 15- or 18-character id. Nothing was read or written.`,roots:{objectApiName:a}});if(f=sa(o.ids),p="records",f.length>d)throw Pe.of(Br(a,d,p))}else if(o.query!==void 0){let m=El(o.query);if(m)throw Pe.of(Yo(m,a));let y=o.chosen,k=y?y.ids.map(O=>({Id:O})):await this.deps.queryRecords(t,Qo(a,o.query,e.objectSoqlFilters?.[a],d));if(f=sa(k.flatMap(O=>typeof O.Id=="string"?[O.Id]:[])),p="query",h=y?.readAt,f.length>d)throw Pe.of(Br(a,d,p,o.query))}else throw new Error(`Internal error: the roots of ${a} were asked with neither a query nor ids.`);if(f.length===0)throw Pe.of(Xo(a,o.query,d));let g=h??new Date().toISOString();return o.keepAt!==void 0&&await qp(o.keepAt,{sourceOrgId:t,fingerprint:o.fingerprint??"",objectApiName:a,...o.query?{query:o.query}:{},from:p==="records"?"records":"query",readAt:g,ids:f}),{objectApiName:a,from:p,...o.query?{query:o.query}:{},ids:new Set(f),sha256:ia(f),readAt:g,fromTheJournal:!1,...u?{readAgain:u}:{},...c}}holdTheRootsReading(e,t,n){let o=e.roots,s=this.deps.requestsSent?.();if(!o||s===void 0||e.requestsBefore===void 0)return;let i=s-e.requestsBefore;if(!(i+n<=o.readingBound))throw Pe.of(Ml({roots:o.ids.size,bound:o.readingBound,sent:i,next:n,objectApiName:t,sourceRequestsLeft:o.sourceRequestsLeft}))}holdTheRootsRows(e,t){let n=e.roots;if(!n)return;let o=0;for(let i of e.readByObject.values())o+=i;if(o<=n.readTotal)return;let s=[...e.readByObject].filter(([i])=>i!==t).map(([i,a])=>({objectApiName:i,rows:a}));throw s.push({objectApiName:t,rows:e.readByObject.get(t)??0}),Pe.of(Nl(n.ids.size,n.readTotal,s))}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new ir("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+or);return}let a;if(i)try{a=await sr.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof ks?new ir("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${or} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new ir("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${or}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=my(n),a=t.filter(w=>w.included&&(e.writtenObjects.has(w.objectApiName)||o.referenceDataObjects.has(w.objectApiName))),d=new Map;for(let w of a)d.set(w.objectApiName,await this.deps.describeFields(s,w.objectApiName));let c=(w,A)=>A.nillable===!1&&e.graph.edges.some(S=>S.type==="master-detail"&&S.targetObject===w&&(A.referenceTo??[]).includes(S.sourceObject)),u=[],l=new Map;for(let w of a){let A=w.objectApiName,S=new Set(o.fieldExclusions[A]??[]),v=(d.get(A)??[]).filter(j=>j.isReference&&!S.has(j.name)).map(j=>({name:j.name,referenceTo:j.referenceTo??[],isMasterDetail:c(A,j),...j.nillable!==void 0?{nillable:j.nillable}:{},createable:j.createable,...j.updateable!==void 0?{updateable:j.updateable}:{}}));if(u.push({objectApiName:A,rows:w.recordCount,keyPrefix:(await this.objectInfoOf(s,A))?.keyPrefix??e.sourceKeyPrefixes.get(A)??null,fields:v}),this.streamsNode(w,e)&&!o.referenceDataObjects.has(A)){let j=await this.recordTypesOfTable(e,w);j&&j.closedInSource.length>0&&l.set(A,{closed:new Set(j.closedInSource.map(it)),lacking:new Set(j.lackingInSource.map(it))})}}let f=await n.budget(),p=e.standardPricebookId&&a.some(w=>mt(w.objectApiName))?await this.runCurrencies(e):void 0,h=p&&this.priceCurrencyWrittenIn(e,p.target),g=new Map;if(a.some(w=>w.objectApiName===$e)){let w=await this.averageEmailBytes(e,d.get($e)??[]);w!==void 0&&g.set($e,w)}let m=h?w=>p.target.active.has(w)?void 0:h(w):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let y=Date.now(),k;try{k=await xp({source:{pages:(w,A)=>Vt(this.deps,s,w,void 0,void 0,A),count:async(w,A)=>{let S=this.deps.countRecords;if(S)return A?S(s,w,A):S(s,w);let v=0,j=w.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let P of Vt(this.deps,s,j,void 0,void 0,A))v+=P.length;return v}},objects:u,order:a.map(w=>w.objectApiName),excluded:new Map([...o.excludedObjects].map(w=>[w,null])),referenceData:o.referenceDataObjects,fieldsOf:w=>d.get(w)?.filter(A=>A.queryable).map(A=>({name:A.name,...A.type!==void 0?{type:A.type}:{},...A.groupable!==void 0?{groupable:A.groupable}:{},...A.sortable!==void 0?{sortable:A.sortable}:{},...A.aggregatable!==void 0?{aggregatable:A.aggregatable}:{}})),filterOf:w=>o.objectSoqlFilters?.[w],options:i,budget:f,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(w,A)=>{let S=l.get(w),v=it(A);return S?.lacking.has(v)?"recordTypeNotInTarget":S?.closed.has(v)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...g.size>0?{averageBytes:g}:{},now:y,labelsOf:async(w,A)=>{if(A.toLowerCase()!=="recordtypeid")return;let S=(await this.objectInfoOf(s,w))?.recordTypes??[],v=new Map(S.map(j=>[it(j.recordTypeId),j.developerName]));return j=>typeof j=="string"?v.get(it(j)):void 0},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(w){throw w instanceof vp?new Fd(`${w.message} Or draw among fewer roots: a window of dates (--fit-window) or a filter on the roots of the large objects (--fit-where).`,{rows:w.rows,most:w.most}):w instanceof Ep||this.isAborted?new be("Forge execution was aborted by user request. Remaining objects were not processed."):w}let{cut:O}=k;if(O.kind==="cannotFit"){let w=O.heaviest.map(B=>`${B.objectApiName} (${B.rows} records${B.whole?", copied whole":""})`).join(", "),A=k.strataFloors,S=O.noRoot?"the objects copied whole and the first root drawn with the records it brings":A?`the objects copied whole and the roots kept of each object and of each value of its strata (${A.roots} roots for the floors of ${A.values} values)`:"the objects copied whole and the roots kept of each object",v=O.noRoot?"Leave objects out (--exclude-object)":A?"Keep no root of each object and value (--fit-floor 0), stratify fewer objects (--fit-strata), leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)",j=mw[O.limitedBy],P=O.limitedBy==="storage"||O.limitedBy==="within";throw new Pd(`No sample of the whole org fits: ${S} take ${O.rows} records, ${(O.storageBytes/1048576).toFixed(1)} MB, ${j.past}; the heaviest are ${w}. ${or} ${v}${j.more}.`,O.heaviest,{limitedBy:O.limitedBy,...P?{needMB:Bh(O.storageBytes,"up"),budgetMB:Bh(O.limitedBy==="storage"&&f.storageBytes!==void 0?f.storageBytes:f.budget.bytes,"down")}:{},heaviest:O.heaviest.map(B=>B.objectApiName)})}let R=Fp({...k,cut:O},i,f.budget);return Sp(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:R,...k.newestByIds.length>0?{newestByIds:k.newestByIds}:{},...k.oldestByIds.length>0?{oldestByIds:k.oldestByIds}:{},ids:[...O.ids].map(([w,A])=>({objectApiName:w,ids:A})),counts:{personAccounts:Object.fromEntries(O.personAccounts),byThePlatform:O.byThePlatform.map(w=>({...w}))}})}async averageEmailBytes(e,t){let n=wg(t,e.config.fieldExclusions[$e]);if(n.length===0)return;let o=this.filterOf(e,$e);try{let s=await this.readWholeOf(e,$e,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${$e}${o?` WHERE ${o}`:""} LIMIT ${py}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){Xe.warn("[forge] the size of the emails could not be read before the sample was drawn: "+V(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let f of t.ids(d))for(let p of f)c.add(it(p));i.set(d,c);let l=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);l&&a.set(d,l)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(it(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(it(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&Ft.test(s.lastId)?s.lastId:void 0,d=R=>a===void 0||Mr(R,a)>0,c=0;if(!s?.done)for(let R of i)d(R)&&c++;let u=Math.min(c,await this.writtenBeforeOf(e,t,s)),l=e.standardPricebookId,f=o===Gt&&l&&i.has(it(l))&&d(l)&&!e.config.writtenBefore.has(l)?Math.min(1,c-u):0,p=Math.max(0,c-u-f),h=Math.min(p,n.counts.personAccounts[o]??0),g=0;o===ie&&h>0&&await this.personAccountsInTarget(e)===!0&&(g=h);let m=n.counts.byThePlatform.find(R=>R.objectApiName===o);m&&(g+=Math.min(p-g,m.inPlan)),p-=g;let y=R=>n.report.dropped.filter(w=>w.objectApiName===o&&w.reason===R).reduce((w,A)=>w+A.rows,0),k={...u>0?{writtenBefore:u}:{},...f>0?{linkedToTarget:f}:{},...g>0?{byThePlatform:g}:{},...y("noParentInSource")>0?{noParentInSource:y("noParentInSource")}:{},...y("outsideFilter")>0?{outsideFilter:y("outsideFilter")}:{}},O=o===ie&&g>0?0:h;return{read:c,counted:{rows:p,...O>0?{personAccounts:Math.min(O,p)}:{}},...Object.keys(k).length>0?{leftOut:k}:{}}}async personContactsBeyondThePlan(e,t){if(!e.sample?.drawn.has(ie))return;let n=t.find(i=>i.objectApiName===ie),o=t.find(i=>i.objectApiName===Se)?.counted.personAccounts??0;if(!n||o<=0||await this.personAccountsInTarget(e)!==!0)return;let s=n.leftOut?.byThePlatform??0;o<=s||(n.leftOut={...n.leftOut,byThePlatform:o})}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=Ip({objectApiName:s,columns:Ht(a.filter(c=>!Pn(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Mr(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Le(n),d=this.filterOf(e,a),c=Math.max(1,Ru(a,yu(o),d?`(${d})`:void 0));for await(let u of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let l=u.filter(h=>Ft.test(h));if(l.length===0)continue;let f=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${l.map(h=>`'${h}'`).join(", ")})`,p=await this.readWholeOf(e,a,f);if(p.sort((h,g)=>Mr(String(h.Id),String(g.Id))),i){let h=new Set(p.map(m=>it(String(m.Id)))),g=t.gone.get(a)??new Set;for(let m of l)h.has(it(m))||g.add(it(m));g.size>0&&t.gone.set(a,g)}yield p}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],u=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*Es(u,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=Vt(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let u of d){let l=u.filter(f=>{let p=it(String(f.Id));return i.has(p)?(a.add(p),!0):!1});l.length>0&&(yield l)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let u of i)!a.has(u)&&(s===void 0||Mr(u,s)>0)&&c.add(u);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(i=>[i.objectApiName,i])),o=t.report,s=Pp(o.roots);return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,...s?{roots:s}:{},objects:o.objects.map(i=>{let a=n.get(i.objectApiName),d=a?a.created+(a.linked??0):0,c=e.store?.earlierRecordsOf(i.objectApiName)??0;return{...i,written:Math.min(i.kept,d+c),goneSinceTheSample:t.gone.get(i.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(i.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([i,a])=>[...a].map(([d,c])=>({objectApiName:i,field:d,rows:c})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],u=[];for(let A of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let S=A.objectApiName;if(!A.included||!e.writtenObjects.has(S))continue;let v=s&&!this.streamsNode(A,e);if(n.referenceDataObjects.has(S)){v&&c.push({objectApiName:S,rows:await this.rowsOf(e,A)});continue}let{read:j,counted:P,leftOut:B,capped:I,partial:z}=e.sample?.drawn.has(S)?await this.countToWriteOfThePlan(e,A,e.sample):await this.countToWrite(e,A);e.counted.set(S,j),I&&a.push(S),z&&d.add(S),v&&!e.sample?.drawn.has(S)&&c.push({objectApiName:S,rows:j}),s&&u.push({node:A,read:j,whole:v}),i.push({objectApiName:S,rows:[],counted:P,...B?{leftOut:B}:{}})}let l=e.sample?.drawn.has(Ge)?void 0:i.find(A=>A.objectApiName===Ge),f=i.find(A=>A.objectApiName===De),p=l?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(l&&p!==void 0&&p>0){let A=Math.min(p,l.counted.rows);l.counted={...l.counted,rows:l.counted.rows-A},l.leftOut={...l.leftOut,byThePlatform:A}}let h=f?.leftOut?.writtenBefore??0,g=l?this.rolesThePlatformMayWriteOfTheCounts(e,l.counted.rows,(p===void 0?f?.counted.rows??0:0)+h):0;if(l&&g>0&&(l.mayBeByThePlatform=p!==void 0?{rows:g,before:!0}:{rows:g}),await this.personContactsBeyondThePlan(e,i),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i)),m&&(m.requests+=await this.directRelationsAtTheGate(e,i,d));let y=s?await this.measureTheWholeOrg(e,i,c,u,m):void 0,k=y&&e.sample?{...y,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:y;if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let O=Cs(n),R=n.dryRun&&!s?0:await this.readBackRequests(e,i),w=await o({objects:i,...O!==void 0&&a.length>0?{capped:{perObject:O,objects:a}}:{},...R>0?{readBack:R}:{},...k?{wholeOrg:k}:{},dryRun:n.dryRun});await this.afterTheGate(e,w,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(m=>m.included&&e.writtenObjects.has(m.objectApiName)&&!o.referenceDataObjects.has(m.objectApiName)),i=new Map(s.map((m,y)=>[m.objectApiName,y])),a=new Map,d=new Map,c=new Map,u=Dh,l=new Map,f=new Set,p=(m,y,k)=>{let O=a.get(m)??new Map;return O.has(y)||u<=0?!1:(O.set(y,k),a.set(m,O),u--,!0)},h={requests:0,lookups:new Map},g=async(m,y)=>{let k=await this.idsUnder(e,m,y);return h.requests+=Math.max(1,Math.ceil((k?.length??0)/Gn)),k};for(let m of s){if(this.isAborted)break;let y=m.objectApiName;if(e.sample?.drawn.has(y))continue;if(u>0&&this.streamsNode(m,e)){let O=await this.recordTypesOfTable(e,m);if(O&&O.closed.length>0&&this.typesHeldRowByRow(e,O)){let R=new Set(O.lackingInSource);for(let[w,A]of[[O.closedInSource.filter(S=>!R.has(S)),d],[O.lackingInSource,c]]){let S=w.map(j=>`'${j}'`).join(", ");if(!S)continue;let v=a.get(y)?.size??0;for(let j of await g(y,`RecordTypeId IN (${S})`)??[])p(y,j,"held");A.set(y,(a.get(y)?.size??0)-v)}}}let k=await this.deps.describeFields(e.sourceOrgId,y).catch(()=>[]);for(let O of k){let[R]=O.referenceTo??[],w=R===void 0?void 0:i.get(R);if(!O.isReference||(O.referenceTo??[]).length!==1||w===void 0||w>=(i.get(y)??0)||!O.createable||(o.fieldExclusions[y]??[]).includes(O.name)||!Ye(y,O.name,O.nillable)||(h.lookups.set(y,(h.lookups.get(y)??0)+1),u<=0))continue;let A=Le(O.name),S=Le(R),v=await g(y,`${A} != null AND ${A} NOT IN (SELECT Id FROM ${S})`);for(let H of v??[])p(y,H,{field:O.name,parentObject:R,reason:wd(O.name,R)});let j=o.objectSoqlFilters?.[R];if(j&&v!==void 0){let H=await g(y,`${A} != null AND ${A} NOT IN (SELECT Id FROM ${S} WHERE (${j}))`);for(let U of H??[]){let J={field:O.name,parentObject:R,reason:yd(O.name,R)};p(y,U,J)&&f.add(U)}}let P=a.get(R);if(!P||P.size===0)continue;let B=[...P].filter(([,H])=>H==="held").map(([H])=>H),I=[...P].filter(([H,U])=>U!=="held"&&!f.has(H)).map(([H])=>H),z=[...P].filter(([H])=>f.has(H)).map(([H])=>H),Z={field:O.name,parentObject:R,reason:qh(O.name,R)};for(let[H,U,J]of[[B,"held",!1],[I,Z,!1],[z,Z,!0]])for(let je of On(H)){if(u<=0)break;for(let pe of await g(y,`${A} IN (${je})`)??[])p(y,pe,U)&&J&&f.add(pe)}}for(let O of k){if(!O.isReference||O.name==="RecordTypeId"||!O.createable||(o.fieldExclusions[y]??[]).includes(O.name)||(O.referenceTo??[]).length===1&&Ye(y,O.name,O.nillable))continue;let R=new Set;for(let A of O.referenceTo??[]){let S=A===y?void 0:a.get(A);if(!(!S||S.size===0))for(let v of On([...S.keys()])){let j=await g(y,`${Le(O.name)} IN (${v})`);for(let P of j??[])R.add(P)}}for(let A of a.get(y)?.keys()??[])R.delete(A);if(R.size===0)continue;let w=l.get(y)??[];w.push({field:O.name,rows:R.size}),l.set(y,w)}}for(let m of n){let y=l.get(m.objectApiName);y&&(m.leftEmpty=y)}for(let m of n){let y=a.get(m.objectApiName);if(!y||y.size===0)continue;let k=d.get(m.objectApiName)??0,O=c.get(m.objectApiName)??0,R=[...y.values()].filter(j=>j==="held").length,w=[...y.keys()].filter(j=>f.has(j)).length,A=y.size-R-w,S=Math.max(0,m.counted.rows-y.size),v=m.counted.personAccounts;m.counted={rows:S,...v!==void 0&&Math.min(v,S)>0?{personAccounts:Math.min(v,S)}:{}},m.leftOut={...m.leftOut,...k>0?{heldBack:(m.leftOut?.heldBack??0)+k}:{},...O>0?{recordTypeNotInTarget:(m.leftOut?.recordTypeNotInTarget??0)+O}:{},...R-k-O>0?{withoutParent:R-k-O}:{},...A>0?{noParentInSource:A}:{},...w>0?{outsideFilter:w}:{}}}for(let m of a.values())for(let[y,k]of m)e.heldInTheOrg.set(y,k);return h}async pricesReplacedAtTheGate(e,t){let n=t.find(g=>g.objectApiName===et);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(et)??0)>Dh)return 0;let o=await this.deps.describeFields(e.sourceOrgId,et).catch(()=>[]);if(!o.some(g=>g.name===wt))return 0;let s=["Id",tn,Fn,wt,...o.some(g=>g.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(g=>g.name===Jn)?[Jn]:[]],i=this.filterOf(e,et),a=e.sample,d;try{d=a?.drawn.has(et)?await this.rowsOfThePlan(e,a,et,s):await this.readWholeOf(e,et,`SELECT ${s.join(", ")} FROM ${et}`+(i?` WHERE ${i}`:""))}catch(g){return Xe.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${V(g)}`),1}let c=Math.max(1,Math.ceil(d.length/Gn)),u=e.currencies===void 0,l=d.filter(g=>!e.heldInTheOrg.has(String(g.Id))),f=await this.priceCurrencyInput(e,l,o),p=c+(u&&e.currencies!==void 0?kw:0);if(!f){let g=e.oneCurrency===void 0,m=await this.pricesKeyOf(e);if(!m.oneCurrency)return p;let y=Math.min(n.counted.rows,ki(l,m).standsFor.length);return y>0&&(n.counted={...n.counted,rows:n.counted.rows-y},n.leftOut={...n.leftOut,currencyReplaced:y}),p+(g&&this.deps.orgCurrency?1:0)}let h=Math.min(n.counted.rows,_a(f,[]).standsFor.size);return h===0||(n.counted={...n.counted,rows:n.counted.rows-h},n.leftOut={...n.leftOut,currencyReplaced:h}),p}async directRelationsAtTheGate(e,t,n){if(e.sample?.drawn.has(Mn))return 0;let o=t.find(p=>p.objectApiName===Mn);if(!o||o.counted.rows<=0||!t.some(p=>p.objectApiName===ie)||n.has(ie)||n.has(Mn))return 0;let s=this.deps.countRecords;if(!s)return 0;let i=e.config.stream?.resumeAfter.get(Mn),a=this.filterOf(e,Mn),d=[...a?[`(${a})`]:[],...i&&Ft.test(i.lastId)?[`Id > '${i.lastId}'`]:[],"IsDirect = true"],c;try{c=await s(e.sourceOrgId,`SELECT COUNT() FROM ${Mn} WHERE ${d.join(" AND ")}`)}catch(p){return Xe.warn(`[forge] the relations the platform writes with the contacts could not be counted at the gate: ${V(p)}`),1}let u=o.leftOut,l=(u?.writtenBefore??0)+(u?.withoutParent??0)+(u?.noParentInSource??0)+(u?.outsideFilter??0),f=Math.max(0,Math.min(c-l,o.counted.rows));return f===0||(o.counted={...o.counted,rows:o.counted.rows-f},o.leftOut={...u,byThePlatform:(u?.byThePlatform??0)+f}),1}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&Ft.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Le(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){Xe.warn(`[forge] the ${t} records held back could not be counted at the gate: ${V(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:O})=>O>a).map(({objectApiName:O,rows:R})=>({objectApiName:O,rows:R,bound:a})),c=new Set(o.filter(O=>O.whole).map(O=>O.node.objectApiName)),{writes:u,restOnly:l}=await this.writesOfTheWholeOrg(e,t,c),f=o.find(({node:O})=>O.objectApiName===$e&&O.included),p=t.find(O=>O.objectApiName===$e)?.counted?.rows??0,h=f&&p>0?await this.emailBytesOf(e,f.node):void 0,g=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o),y=t.find(O=>O.objectApiName===Se)?.counted?.personAccounts??0,k=y>0&&await this.personAccountsInTarget(e)===!1?y:0;return{writes:u,...l?{restOnly:l}:{},...h!==void 0?{emailTextBytes:h}:{},...i.files?{files:g??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,g)+Sw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{},...k>0?{personAccountsAsBusiness:k}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...os,...c??ua])}let a=o.stream?.writeWindow??o.stream?.pageSize??Gn,d=t.map(({objectApiName:c,counted:u})=>{let l=Math.max(0,u?.rows??0),f=s&&!i.has(c),p=n.has(c)?[l]:[...Array.from({length:Math.floor(l/a)},()=>a),...l%a>0?[l%a]:[]],h=0,g=0;for(let m of f?p:[])for(let y=0;y<m;y+=Dr){let k=Math.min(Dr,m-y);k<2e3||(h++,g+=k)}return{objectApiName:c,rows:l,jobs:h,jobRows:g,restRows:l-g}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Gn)),i=new Map;for(let{node:c,read:u}of t)i.set(c.objectApiName,u);for(let{objectApiName:c,rows:u}of n)i.set(c,u);let a=0;for(let[c,u]of i){let l=t.find(f=>f.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&l?(await this.readOfThePlan(e,e.sample,l,u)).requests:s(u)}let d=t.find(({node:c})=>c.objectApiName===$e);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===ct)){let c=await this.countOf(e,$e,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=Ed.length+Math.ceil(c/Gn),a+=Math.ceil(c/vd)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Le(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=wg(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let h=0,g=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of g)for(let[y,k]of Object.entries(m))y!=="Id"&&typeof k=="string"&&(h+=Buffer.byteLength(k,"utf8"));return h}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Ft.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],u=c.length>0?` WHERE ${c.join(" AND ")}`:"",l=["Id",...s.map(h=>h.name)].join(", "),f=0,p=Vt(this.deps,e.sourceOrgId,`SELECT ${l} FROM ${Le(n)}${u} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let h of p){for(let g of h)for(let[m,y]of Object.entries(g))m!=="Id"&&typeof y=="string"&&(f+=Buffer.byteLength(y,"utf8"));if(this.isAborted)break}}finally{await p.return(void 0)}return f}catch(o){Xe.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+V(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of Ed){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),u=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),l=await this.sumOfFiles(e,i,a,c);if(!l)return;n+=l.bytes,o+=l.count;let f=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${u}`).catch(()=>{});s+=f??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=Vt(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let u=c[n];s+=typeof u=="number"&&Number.isFinite(u)?u:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){Xe.warn(`[forge] the files of ${t} could not be measured: ${V(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(u=>u.createable&&!a.has(u.name));for(let u of Na(c)){if(u.kind!=="phone")continue;let l=await this.countOf(e,i,`${Le(u.name)} != null`);n+=Math.min(l??s,s)}}return Math.max(0,n-Df)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async U=>{if(!d)return;let J=[...i?[`(${i})`]:[],...U?[U]:[],...s&&Ft.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],je=J.length>0?` WHERE ${J.join(" AND ")}`:"",pe=`SELECT COUNT() FROM ${Le(n)}${je}`;try{return await(a?d(e.sourceOrgId,pe,a):d(e.sourceOrgId,pe))}catch{return}},u=this.readBound(e,t),l=u===void 0?void 0:Math.max(0,u-(s?.read??0)),f=await c(),p=f??t.recordCount,h=l===void 0?p:Math.min(p,l),g=Cs(e.config),m=g===void 0?void 0:Math.max(0,g-(s?.read??0)),y=m!==void 0&&l===m&&p>m,k=o?await this.recordTypesOfTable(e,t):void 0;if(k&&k.closed.length>0&&!this.typesHeldRowByRow(e,k))return{read:h,counted:{rows:0},...h>0?{leftOut:Gh(k.closed,h)}:{}};let O=Math.min(h,await this.writtenBeforeOf(e,t,s)),R=n===Gt?Math.min(h-O,await this.standardBookOfTheTable(e,c)):0,w=h-O-R,A=O>0||R>0?{...O>0?{writtenBefore:O}:{},...R>0?{linkedToTarget:R}:{}}:void 0,S=U=>U===void 0?{rows:w}:{rows:w,personAccounts:U},v=h<p,j=U=>({read:h,counted:S(U),...A?{leftOut:A}:{},...y?{capped:!0}:{},...v?{partial:!0}:{}});if(n!==Se&&n!==ie||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(U=>U.name==="IsPersonAccount"))return j();let B=await c("IsPersonAccount = true"),I=B===void 0?void 0:Math.min(B,w);if(n!==ie||B===void 0||f===void 0)return j(I);let z=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(z===void 0)return j(I);let Z=Math.max(0,B-z-(f-h)-O);if(Z===0)return j(I);let H=(I??0)-Z;return{read:h,counted:{rows:w-Z,...H>0?{personAccounts:H}:{}},leftOut:{...A,byThePlatform:Z},...y?{capped:!0}:{},...v?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Ft.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,Gt)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,Se).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[Se]??[]).includes("RecordTypeId")&&o.fieldMappings[Se]?.RecordTypeId===void 0)){let d=Ba((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>Ft.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return sp({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>xs(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=ip(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=Sd(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(l=>l.name===a)?.referenceTo?.[0]??a,u=i.get(a)??{parent:c,rows:0};u.rows+=d,i.set(a,u)}e.lookupsOutsideTheRun.set(t,i)}async noteLookupsHeldBack(e,t,n,o){let s=Ad(new Map,o);if(s.size===0)return;let i=e.lookupsHeldBack.get(t)??new Map;for(let[a,d]of s){let c=i.get(a)??{parent:await this.parentNamed(e,n,a,o),rows:0};c.rows+=d,i.set(a,c)}e.lookupsHeldBack.set(t,i)}async parentNamed(e,t,n,o){let s=t.find(d=>d.name===n)?.referenceTo??[];if(s.length===1)return s[0];let i=o.find(d=>d.lookupsHeldBack?.includes(n))?.source[n],a=s.filter(d=>e.writtenObjects.has(d));if(typeof i=="string"&&a.length>0){let c=(await this.sourceKeyPrefixes(e,new Set(a))).get(i.slice(0,3));if(c)return c}return s[0]??n}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(u=>{let l=u.referenceTo??[];return u.isReference&&s(u.name)&&l.length===1&&!xs(t,l[0])&&this.isOutsideTheRun(t,l[0])&&Ye(e.objectApiName,u.name,u.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((u,l)=>{for(let f of d){let p=u[f.name];if(!(typeof p!="string"||!c.has(p)||t.remapper.get(p))){i.set(l,{field:f.name,parentObject:(f.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,u)=>{let l=a[u]?.RecordTypeId,f=typeof l=="string"?i.get(l):void 0;f&&d.set(c,{field:"RecordTypeId",parentObject:f.developerName,recordType:{...f,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=jw(t,e.objectApiName,n,s),c=new Set,u=new Map;o.forEach((l,f)=>{let p=t.heldInTheOrg.get(String(l.Id));if(p!==void 0&&p!=="held"){a.set(f,p);return}if(t.sample?.withoutStandard.has(it(String(l.Id)))){i.set(f,{field:Fn,parentObject:et,reason:hy}),c.add(f);return}for(let{field:h,parent:g}of d){let m=l[h];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let y=t.sample;if(y?.drawn.has(g)){this.inThePlan(y,g,m)?y.gone.get(g)?.has(it(m))?a.set(f,{field:h,parentObject:g,reason:Aw(h,g)}):i.set(f,{field:h,parentObject:g}):(i.set(f,{field:h,parentObject:g,reason:Tw(h,g)}),c.add(f));return}let k=t.heldInTheOrg.get(m);if(k==="held"){i.set(f,{field:h,parentObject:g});return}if(k){let R=k===md?wd(h,g):k===_h?yd(h,g):qh(h,g);a.set(f,{field:h,parentObject:g,reason:R});return}let O=u.get(g)??new Map;O.set(m,[...O.get(m)??[],{index:f,field:h}]),u.set(g,O)}});for(let[l,f]of u){let p=[...f.keys()],h=t.config.objectSoqlFilters?.[l],g=h===void 0?void 0:await this.idsInTheSource(t,l,p,h),m=g?p.filter(O=>!g.has(O.slice(0,15))):p,y=m.length>0?await this.idsInTheSource(t,l,m):new Set,k=O=>{let R=O.slice(0,15);if(!(g?.has(R)===!0||y===void 0))return y.has(R)?g?_h:void 0:md};for(let[O,R]of f){let w=k(O);w&&t.heldInTheOrg.set(O,w);for(let{index:A,field:S}of R)i.has(A)||a.has(A)||(w?a.set(A,{field:S,parentObject:l,reason:w===md?wd(S,l):yd(S,l)}):i.set(A,{field:S,parentObject:l}))}}for(let l of i.keys())a.delete(l);if(c.size>0&&t.sample){let l=e.objectApiName;t.sample.changed.set(l,(t.sample.changed.get(l)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n,o){let s=new Set,i=o===void 0?"":`(${o}) AND `;try{for(let a of On(n)){let d=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Le(t)} WHERE ${i}Id IN (${a})`);for(let c of d)s.add(String(c.Id).slice(0,15))}return s}catch(a){Xe.warn(`[forge] whether the source holds the ${t} records named could not be read: ${V(a)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let p of o.keys())p.startsWith(a)&&d.push(p);let c=e.config.objectSoqlFilters?.[s],u=this.deps.countRecords;if(!c||d.length===0||!u)return d.length;let l=this.readOptionsOf(e,s),f=this.filterOf(e,s)??c;try{let p=0;for(let h of On(d)){let g=`SELECT COUNT() FROM ${Le(s)} WHERE (${f}) AND Id IN (${h})`;p+=await(l?u(e.sourceOrgId,g,l):u(e.sourceOrgId,g))}return p}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===$e&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(zo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:iw(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let f=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,f);return}let u=n?n.expected:t.counted.get(o)??Mh(e,d);a.carry.rowsLeft=n?()=>Math.max(0,u-a.carry.rows):()=>Math.max(0,u-(a.read-(i?.read??0)));let l=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let f=n?void 0:await this.keysOfTheTable(t,e,a);for(f&&(a.carry.tableKeys=f);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,l):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let p=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,p,a.carry),o===Se&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==$e||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${Is(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,u]=await Promise.all([this.deps.describeFields(o,i),an(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(P=>P.name==="RecordTypeId"&&P.createable)||u&&!u.creatable.has("RecordTypeId"))return d;let f=n.stream?.resumeAfter.get(i),p=this.filterOf(e,i),h=[...p?[`(${p})`]:[],...f&&Ft.test(f.lastId)?[`Id > '${f.lastId}'`]:[]],g=h.length>0?` WHERE ${h.join(" AND ")}`:"",m=`FROM ${Le(i)}${g}`,y=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),k=y.reduce((P,B)=>P+(typeof B.n=="number"&&B.n>0?B.n:0),0),O=Lu(y),R=async P=>[...Bu(i,P,a.recordTypes),...await this.typesTheTargetLacks(e,i,P,a)],w=await R(this.recordTypesAsSent(e,O)),A=P=>{let B=new Set(P.map(I=>I.recordTypeId));return[...O.keys()].filter(I=>[...this.recordTypesAsSent(e,[[I,1]]).keys()].some(z=>B.has(z)))},S=(P,B)=>({closed:P,rows:B,target:a,closedInSource:A(P),lackingInSource:A(P.filter(I=>I.unmapped))}),v=this.readBound(e,t),j=v===void 0?void 0:Math.max(0,v-(f?.read??0));if(w.length>0&&j!==void 0&&k>j){let P=await this.recordTypesOfTheRowsRead(e,i,m,j);if(P)return S(await R(this.recordTypesAsSent(e,P.counts)),P.rows)}return S(w,k)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(Lo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),Lo(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return Lo(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(zh(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[Do(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${jn(s,o,Qt(t,s))}: `+n.closed.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=f=>i?this.pagesOfThePlan(e,i,t,n,f):Vt(this.deps,e.sourceOrgId,f,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?gd:0,c;for(let f=0;;f++)try{c=await n.pages.next();break}catch(p){let h=ig(p);if(!h&&!ag(p)||f>=d||this.isAborted)throw p;let g=n.lastId===void 0?o:s?.(n.lastId);if(g===void 0)throw p;h||await dg(Fh*2**f),Xe.warn(`[forge] ${t.objectApiName}: the source ${h?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${f+1}/${d}): `+V(p)),n.pages=a(g)}if(c.done)return n.ended=!0,[];n.taken++;let u=c.value;n.room!==void 0&&(u.length>n.room&&(u=u.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=u.length),n.read+=u.length;let l=u[u.length-1]?.Id;return typeof l=="string"&&(n.lastId=l),u}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new Ls(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=Vt(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=Cs(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Qt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),u=[...hd(n),...d],l=zn(u),f=v=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:v})};if(n.heldWhole!==void 0){f(`${jn(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){f(zr(a,c));return}let p=Ih(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){f(`${jn(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(p===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){f(`${jn(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let h=p+n.failed,g=h>0?n.failed/h:0,m=n.failed>0&&n.alreadyExists===n.failed,y=n.failed>0&&!m&&(p===0||g>.5),k=Vo(n.picklists.list())+Co(n.currencies.list())+Od(n.lookupsNotCarried)+jd(n.ownersInactive)+kd(n.lookupsOutsideTheRun)+Td(n.lookupsHeldBack)+Id(t,a),O=ss(n.writtenWithoutFields),R=pg(t,a),w=Ch(t,a),A=Qh(n.sentOnTheirOwn);if(y){p>0&&t.failedInPart.add(a),f(p===0?`Failed all ${a} records: ${n.failed+l} failed${cn(u)}${A}${k}${w}`:`${n.failed+l}/${h+l} ${a} records failed (>50%)${cn(u)}${A}${k}${O}${R}${w}`+Hh);return}let S=xh(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${Rd(s,a,n,u,bd(t,a))}${o.note??""}${A}${S}${k}${O}${R}${Ns(t,a)}${w}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();$d(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...hd(n),...Qt(t,i)],c=Ih(n),u=c+n.failed,l=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/u>.5);l&&t.failedObjects.add(i),l&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:l?"error":"stopped",progress:100,message:`${s}: ${Rd(t.config,i,n,d,bd(t,i))}, ${a} not sent${Qh(n.sentOnTheirOwn)}${xh(n)}${Vo(n.picklists.list())}${Co(n.currencies.list())}${Od(n.lookupsNotCarried)}${jd(n.ownersInactive)}${kd(n.lookupsOutsideTheRun)}${Td(n.lookupsHeldBack)}${Id(t,i)}${ss(n.writtenWithoutFields)}${Ns(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:Cd(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((u,l)=>u+l.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(u=>u.samples).slice(0,Lw)},d=e.errors.indexOf(i),c=e.errors.filter(u=>!o.includes(u));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((u,l)=>u+(l.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((u,l)=>u+l.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((u,l)=>u+l.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(u=>!s.includes(u));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=To(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!To(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=cu[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=uu(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&Ar[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&To(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of hg(n)){let i=0,a=[];for(let d=0;d<s.length;d+=is.rest){let c=s.slice(d,d+is.rest),u;try{u=await t(e.targetOrgId,o,c.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=c.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}c.forEach(({id:l,status:f},p)=>{let h=u[p];h?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${l} Status=${f}`,messages:h?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let u;try{u=await t(e.targetOrgId,a,d.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=d.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}d.forEach(({id:l,status:f},p)=>{let h=u[p];if(h?.success){n.gaveStatus(a,l);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${l} Status=${f}`,messages:h?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let u=o.get(a)??{entries:0,failed:0,samples:[]};u.entries++,o.set(a,u);let l=s.get(a)??[];l.push({id:d,status:c}),s.set(a,l),l.length>=is.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:u}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:u})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(Ar)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[u,l]of a){let f=e.remapper.get(u);if(!e.config.dryRun&&!f)continue;let p;if(t.has(i.object))p=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(u)){let g=d.held.get(u);g&&(p=`none of its ${i.object} records can be written without ${g.excluded}`+(g.target?Kr(g.target):", which is excluded from this run"))}if(!p)continue;f&&n.add(f);let h=f!==void 0&&!e.simulated?.has(f)?f:u;c.push({recordSummary:`${s} ${h} Status=${l}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${p}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of hg(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=u=>Rw(e.objectApiName,t.graph,u).filter(l=>t.failedObjects.has(l)&&!t.failedInPart.has(l)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(u=>!dn(t.config,u)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(u=>`Not written: its records cannot be written without ${u}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Qt(t,e.objectApiName),c=(a??0)+zn(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${cn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((u,l)=>{for(let f of n){let[p]=f.referenceTo??[];if(!f.isReference||(f.referenceTo??[]).length!==1||p===e.objectApiName||!t.failedInPart.has(p)||!Ye(e.objectApiName,f.name,f.nillable))continue;let h=u[f.name];if(typeof h=="string"&&h&&!t.remapper.get(h)){s.set(l,{field:f.name,parentObject:p});return}}});let i=n.filter(u=>u.isReference&&(u.referenceTo??[]).length>1&&Ye(e.objectApiName,u.name,u.nillable)),a=[];if(o.forEach((u,l)=>{for(let f of i){let p=u[f.name];typeof p=="string"&&p&&!t.remapper.get(p)&&a.push({index:l,field:f.name,id:p})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(u=>(u.referenceTo??[]).filter(l=>d.has(l)))));for(let{index:u,field:l,id:f}of a){let p=c.get(f.slice(0,3));p&&!s.has(u)&&s.set(u,{field:l,parentObject:p})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let u=a[c]?.keyPrefix;u&&e.sourceKeyPrefixes.set(d,u)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Ye(t,d.name,d.nillable)))for(let u of c)o.has(u)&&s.add(u)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(u=>e.sourceKeyPrefixes.get(u)===o);if(s)return s;let i=new Set(e.graph.nodes.map(u=>u.objectApiName)),a=n.filter(u=>!e.sourceKeyPrefixes.has(u)),d=a.filter(u=>!i.has(u)),c=[a.filter(u=>i.has(u))];for(let u=0;u<d.length;u+=6)c.push(d.slice(u,u+6));for(let u of c){let l=(await this.sourceKeyPrefixes(e,new Set(u))).get(o);if(l)return l}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,u]of t){cw(u)&&i.push(c);for(let l of u)if(!(!l.isReference||!Tr(l)||!Ye(c,l.name,l.nillable)))for(let f of l.referenceTo??[])f===c||!o.has(f)||s.push({sourceObject:f,targetObject:c,relationshipName:l.name,type:"lookup",required:!0})}let a=zl(o,i),d=t.get(et)?.some(c=>c.name===wt);return da(ts(n,t),[...s,...a,...d?Jf(o,i,[...s,...a]):[],...Ei(o),...xi(o,t),...ep(o,t),...Mi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>mt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(Se)&&o.has(ie)&&(await Promise.allSettled([Se,ie].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([Se,ie][d],a.value)}),da(ts(e.graph,s),[...Ei(o),...xi(o,s),...Mi(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=Ar[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let u;try{u=await this.deps.describeFields(t,c.object)}catch{continue}let l=u.find(f=>f.name===c.lookup&&f.isReference&&(f.referenceTo??[]).includes(d.objectApiName));l&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Ur(c.object,u,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:Ye(c.object,l.name,l.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=sw[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let u=c.find(l=>l.name===d.lookup&&l.isReference&&(l.referenceTo??[]).includes(a.objectApiName));u&&(o.add(d.object),s.push(Ur(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:u.name,type:"lookup",required:Ye(d.object,u.name,u.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=_l(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(u=>`${u.sourceObject}|${u.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(u=>u.included);for(;c.length>0&&!this.isAborted;){let u=[];for(let l=0;l<c.length&&!this.isAborted;l+=6){let f=c.slice(l,l+6);(await Promise.allSettled(f.map(({objectApiName:h})=>this.deps.describeFields(t,h)))).forEach((h,g)=>{if(h.status!=="fulfilled")return;let{objectApiName:m,level:y}=f[g];a.set(m,h.value);for(let k of h.value){let O=k.referenceTo??[];if(!k.isReference||O.length!==1)continue;let[R]=O;R===m||!(o.has(R)||i.has(R))||Dl(m,k)&&(o.delete(R)&&(i.set(R,y+1),u.push({objectApiName:R,level:y+1})),!s.has(`${R}|${m}`)&&(s.add(`${R}|${m}`),d.push({sourceObject:R,targetObject:m,relationshipName:k.name,type:"lookup",required:Ye(m,k.name,k.nillable)})))}})}c=u}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([u,l])=>Ur(u,a.get(u)??[],l))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=u=>e.nodes.find(l=>l.included&&l.objectApiName===u),s=o(Zo),i=o(jr);if(!o(et)||!s||!i||n.has(zt)||e.nodes.some(u=>u.objectApiName===zt))return e;let a;try{a=await this.deps.describeFields(t,zt)}catch{return e}let d=Ur(zt,a,Math.max(s.level,i.level)+1),c=(u,l)=>({sourceObject:u,targetObject:zt,relationshipName:l,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Zo,"Product2Id"),c(jr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,u]of Object.entries(s))n.has(u)&&delete s[c];let i=c=>c in s,a=rg(e),d=[...e.mayHaveBeenWritten].map(([c,u])=>({objectApiName:c,sourceIds:[...u]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...Mw(e),...Pw(e),...Uw(e),...Gw(e),...Hw(e),...oy(e)],truncatedObjects:[...e.truncatedObjects],...Wh(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...yw(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,u])=>({objectApiName:c,rows:u}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,u])=>[...u].map(([l,{records:f,ids:p}])=>({objectApiName:c,field:l,records:f,recordIds:[...p]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,u])=>({objectApiName:c,notSent:u}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,u])=>({objectApiName:c,read:u,...this.originOf(e,c,u)})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,u])=>fy(c,u))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:u,fields:l}])=>({objectApiName:c,rows:u,fields:l.map(f=>({...f}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...gy(this.sampleResultOf(e)),...e.roots?{roots:this.rootsResultOf(e,e.roots)}:{},...e.roots&&e.readRequests!==void 0?{reads:{source:e.readRequests}}:{}}}originOf(e,t,n){let o=e.roots;if(!o)return{};let s=t===e.config.rootObjectApiName,i=0;if(s)for(let u of o.ids)e.idsRead.has(u)&&i++;i=Math.min(i,n);let a=0;for(let u of e.scopeCache?.reachedOf(t)??[])s&&o.ids.has(u)||a++;let d=Math.min(a,n-i),c=e.readUnder.get(t);return{origin:{roots:i,under:d,named:n-i-d},...c&&c.size>0?{readUnder:[...c]}:{}}}rootsResultOf(e,t){let n=[],o=[],s=0,i=0,a=0,d=e.errors.find(m=>m.objectApiName===t.objectApiName)?.samples.flatMap(m=>m.messages)[0]??"not written",c=new Set(e.remapper.updatedSourceIds()),u=new Set(rg(e)),l=new Map((e.preread.get(t.objectApiName)?.records??[]).map(m=>[String(m.Id),m])),f=m=>{let y=l.get(m);return e.simulated!==null&&t.objectApiName===ie&&y!==void 0&&rn(y)&&!e.contactsOnTheirOwn.has(m)&&typeof y.AccountId=="string"&&e.remapper.wasCreated(y.AccountId)},p=0,h=[],g=(m,y)=>{if(h.length>=wn)return;let k=y&&e.simulated===null?e.remapper.get(m):void 0;h.push(k!==void 0?{source:m,target:k}:{source:m})};for(let m of t.ids){if(!e.idsRead.has(m)){n.push(m),g(m,!1);continue}s++,e.remapper.wasCreated(m)||c.has(m)?(i++,g(m,!0)):u.has(m)||f(m)?(i++,p++,g(m,!0)):e.remapper.isExisting(m)?(a++,g(m,!0)):(o.push({id:m,reason:d}),g(m,!1))}return{objectApiName:t.objectApiName,from:t.from,...t.query?{query:{...t.query}}:{},cap:t.cap,asked:t.ids.size,read:s,gone:n,written:i,linked:a,failed:o,sha256:t.sha256,readAt:t.readAt,...t.readAgain?{readAgain:{...t.readAgain}}:{},...p>0?{withTheirAccount:p}:{},ids:h,...t.ids.size>h.length?{idsLeftOut:t.ids.size-h.length}:{},...t.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new qr,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await up({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=lp(i);if(a&&!t.dryRun)throw new An(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(p=>p.into?.unchanged!==!0)},u;if(c.files.length>0)try{u=await gp(s,e.targetOrgId)}catch(p){let h=`The file storage the target has left could not be read (${V(p)}), so the files could not be checked against it.`;if(!t.dryRun)throw new An(`${h} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(Va(h))}e.files=mp(c,o.maxFileBytes,u),a&&(e.files.lookupFailure=a);let l=pp(c.files),f=u===void 0?null:hp(l,u);if(f&&u!==void 0&&!t.dryRun)throw new An(`${f} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:l,remainingBytes:u});if(f&&e.errors.push(Va(f)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:p,sourceId:h,name:g,bytes:m})=>({objectApiName:p,sourceId:h,name:g,bytes:m}));for(let p of e.files.objects)n({objectName:p.objectApiName,status:"done",progress:100,message:wp(p)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await fp({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await Ja({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:Ps(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??Jw;for(let d of Ed){let{counted:c}=d,u=e.config.stream?.resumeAfter.get(zo(c,og));if(u?.done)continue;let f=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),p=u?.read??0,h=u&&Ft.test(u.lastId)?u.lastId:void 0;for(let g=!1;!g;){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,f,h,a);if(!m)break;g=m.length<a;let y=!0;for(let O=0;O<m.length;O+=vd){let R=m.slice(O,O+vd),w=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,R):Qw(e,R);if(!w){y=!1;break}if(w.length===0)continue;let A=await this.filesCopiedBefore(e,w,n);for(let v of A){if(v.into?.unchanged)continue;let j=sg(o,v.objectApiName);j.planned++,j.plannedBytes+=v.bytes}s+=A.filter(v=>v.into?.unchanged).length,e.failedCount+=await Ja({files:A,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:v=>e.remapper.wasCreated(v),get:v=>e.remapper.get(v),add:(v,j,P)=>e.remapper.add(v,j,P),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:Ps(e.store)}:{}});let S=sg(o,c);i(c,`Copying files: ${S.copied} of ${S.planned} copied so far`)}if(!y)break;p+=m.length;let k=m[m.length-1]?.Id;typeof k=="string"&&(h=k),h!==void 0&&e.store?.checkpoint(c,{lastId:h,read:p,...g?{done:!0}:{}},og)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&Xe.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${V(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=ig(o);if(!s&&!ag(o)||n>=gd||this.isAborted)throw o;s||await dg(Fh*2**n),Xe.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${gd}): ${V(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Ft.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let u=c.ContentDocumentId,l=c.LinkedEntityId;if(typeof u!="string"||typeof l!="string"||!e.remapper.wasCreated(l))continue;let f=o.get(u)??[];if(f.some(g=>g.id===l))continue;let p=c.ShareType,h=c.Visibility;f.push({id:l,...typeof p=="string"?{shareType:p}:{},...typeof h=="string"?{visibility:h}:{}}),o.set(u,f)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${V(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let u=n.get(d),l=u?.Id;if(!u||typeof l!="string")continue;let f=u.Title,p=typeof f=="string"&&f!==""?f:d,h=u.PathOnClient,g=u.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:l},name:p,bytes:typeof g=="number"&&Number.isFinite(g)?g:0,hosts:c,fields:{Title:p,PathOnClient:typeof h=="string"&&h!==""?h:p,...u.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!yg(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:He,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=fw)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||He.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let u=c.referenceTo??[];if(!c.isReference||u.length!==1||a.has(c.name)||!Tr(c)||!Ye(t,c.name,c.nillable))continue;let[l]=u;if(l===t||l===i.rootObjectApiName||He.has(l)||i.referenceDataObjects.has(l)||!e.readObjects.has(l)||e.failedObjects.has(l)||e.notCreatable.has(l)||!s.isRead(l))continue;let f=s.scopeOf(l),p=e.askedForRowsThatNeedThem.get(l),h=e.heldForExclusions.get(l);for(let g of o){let m=g[c.name];typeof m!="string"||m===""||f?.has(m)||p?.has(m)||h?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(l,(d.get(l)??new Set).add(m))}}for(let[c,u]of d){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let l=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!l)continue;let f=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of u)f.add(m);e.askedForRowsThatNeedThem.set(c,f);let p=await this.fieldsReadAgain(e,l);if(!p)continue;let h=Ht(p.fields,i.fieldExclusions[c]);(await this.readMore(e,l,p.fields,new kn().buildById({objectApiName:c,selectFields:h.length>0?h:["Id"],ids:u,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(p.described&&this.withoutFileContent(e,c,p.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<hw&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let u=[];for(let[f,p]of c){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let h=await this.refusalOf(e,f,n.get(f),o);h?await this.holdBackForARefusedParent(e,f,h,p,s):u.push([f,p])}let l=[];for(let[f,p]of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let h=gw(e,p);if(h.ids.size===0)continue;let g=await this.readParentsById(e,f,n.get(f),h);g&&l.push(g)}a=l}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let u=a.get(c);return u||(u=new Set((e.preread.get(c)?.records??[]).flatMap(l=>typeof l.Id=="string"?[l.Id]:[])),a.set(c,u)),u};for(let{objectApiName:c,fieldInfos:u,records:l}of t){let f=new Set(s.fieldExclusions[c]??[]);for(let p of u){let h=p.referenceTo??[];if(!p.isReference||h.length!==1||f.has(p.name)||!Tr(p)||!Ye(c,p.name,p.nillable))continue;let[g]=h;if(g===c||g===s.rootObjectApiName||He.has(g)||s.referenceDataObjects.has(g)||s.excludedObjects.has(g)||xs(e,g))continue;let m=o.get(g);if(m&&(!n||!m.included||e.failedObjects.has(g)))continue;let y=e.askedForRowsThatNeedThem.get(g),k=e.heldForExclusions.get(g);for(let O of l){let R=O[p.name];if(typeof R!="string"||R===""||dn(s,O)||e.remapper.get(R)||e.leftToThePlatform.has(R)||y?.has(R)||k?.has(R)||d(g).has(R))continue;let w=i.get(g);w||(w={ids:new Set,neededBy:new Set,rows:[]},i.set(g,w)),w.ids.add(R),w.neededBy.add(c),w.rows.push({objectApiName:c,row:O,field:p.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){nr(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let u=d.Id;if(typeof u!="string"||i.get(a)?.has(u)||!await this.carriesTheLookup(e,a,c,s))continue;let l=i.get(a)??new Map;l.set(u,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,l)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let u=c.records.filter(l=>typeof l.Id!="string"||!d.has(l.Id));this.holdBackRowsRead(e,a,c,u,[...d].map(([l,{row:f,why:p}])=>({id:l,row:f,why:p})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await an(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),u,l;if(c)u=[...c.fieldInfos];else{try{l=await this.deps.describeFields(e.sourceOrgId,t)}catch(S){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[V(S)]}]});return}u=l.filter(S=>!Pn(S))}let f=e.askedForRowsThatNeedThem.get(t)??new Set;for(let S of o.ids)f.add(S);e.askedForRowsThatNeedThem.set(t,f);let p=Ht(u,s.fieldExclusions[t]),h=new kn().buildById({objectApiName:t,selectFields:p.length>0?p:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]});this.holdTheRootsReading(e,t,h.length);let g;try{g=await Wr(d>0?ca(h,d,{byIdCount:h.length}):{kind:"query",statements:h,byIdCount:h.length},S=>this.deps.queryRecords(e.sourceOrgId,S,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(S){if(S instanceof be)throw S;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[V(S)]}]});return}Gr(e,g);let m=new Set((c?.records??[]).flatMap(S=>typeof S.Id=="string"?[S.Id]:[])),y=g.filter(S=>typeof S.Id!="string"||!m.has(S.Id)),k=S=>(e.graph.nodes.find(v=>v.objectApiName===S)??e.parentsOutside.get(S))?.level??0,O=n??e.parentsOutside.get(t)??Ur(t,u,1+Math.max(0,...[...o.neededBy].map(k))),R=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,O,u,y,void 0,await this.excludedByKeyPrefix(e,t,u));let w=[...e.heldForExclusions.get(t)??[]].filter(([S])=>!R.has(S));if(this.leaveToThePlatform(e,t,y,u),y.length===0&&w.length===0)return;let A=c?.createableSet??new Set(u.filter(S=>S.createable).map(S=>S.name));if(y.length>0){e.preread.set(t,c?{...c,records:[...c.records,...y]}:{fieldInfos:u,createableSet:A,records:y,targetSetsPending:null}),l&&this.withoutFileContent(e,t,l,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,O),e.writtenObjects.add(t));let S=y.find(j=>typeof j.Id=="string")?.Id;typeof S=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,S.slice(0,3));let v=e.readAsParents.get(t)??{count:0,neededBy:new Set};v.count+=y.length;for(let j of o.neededBy)v.neededBy.add(j);e.readAsParents.set(t,v)}else if(!n){let S=e.heldForExclusions.get(t);S&&e.onProgress({objectName:t,status:"error",progress:100,message:zr(t,S,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+y.length+w.length),this.holdTheRootsRows(e,t),s.dryRun){let S=y.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,y,A):0,v=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${y.length-S} ${v}record(s) would be inserted`+(S>0?`, ${S} ${v}would be written by the platform with ${Bn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+Bs(Ms(w.map(([,j])=>j)),c!==void 0)})}return y.length>0?{objectApiName:t,fieldInfos:u,records:y}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let u=t.cursors.get(e.objectApiName);try{(!u||u.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let l=u?.described??await this.deps.describeFields(i,e.objectApiName);u&&(u.described=l);let f=l.filter(I=>!Pn(I)),p=new Set(f.filter(I=>I.createable).map(I=>I.name));if(await this.skipForFailedParent(e,t,f))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let I=uw(e.objectApiName,f,t.turnsAhead);if(I)return t.waitingFor.set(I,[...t.waitingFor.get(I)??[],e]),!1}let h={node:e,edges:t.graph.edges,fieldInfos:f,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:t.roots?.ids,extraWhere:Yw(this.filterOf(t,e.objectApiName),u?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:u?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,u):s.maxRecordsPerObject,...u?{inIdOrder:u.resumeAfter!==void 0?{afterId:u.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:He,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},g=on(h);if(n&&this.waitsForWhatPointsAtIt(e,g,t))return t.catalogNodes.push({node:e,fieldInfos:f}),!1;if(g.kind==="skip"){if(n&&g.reason===aa)return t.deferredNodes.push(e),!1;let I=t.heldForExclusions.get(e.objectApiName);return I&&I.size>0?(t.readByObject.set(e.objectApiName,I.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,I,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${g.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let I=on({...h,maxRecordsPerObject:1}),z=I.kind==="query"?await Wr(I,Z=>this.deps.queryRecords(i,Z)):[];return this.reportNotCreatable(e,t,z.length>0),!1}if(this.holdTheRootsReading(t,e.objectApiName,g.statements.length),t.roots&&g.readUnder){let I=t.readUnder.get(e.objectApiName)??new Set;for(let z of g.readUnder)I.add(z);t.readUnder.set(e.objectApiName,I)}let y=o&&!s.referenceDataObjects.has(e.objectApiName)?u?.targetSets??an(this.deps.describeFields,a,e.objectApiName).then(I=>({ok:!0,sets:I}),I=>({ok:!1,error:I})):null;u&&(u.targetSets=y);let k=t.scopeCache?new Set:void 0,O=u?I=>{let z=on({...h,maxRecordsPerObject:u.room===void 0?void 0:Math.max(1,u.room),inIdOrder:{afterId:I}});return z.kind==="query"&&z.statements.length===1?z.statements[0]:void 0}:void 0,R=await Wr(g,I=>u?this.nextPage(t,e,u,I,O):this.readWhole(t,e.objectApiName,I),k,()=>t.cappedObjects.add(e.objectApiName));if(u?.ended&&R.length===0&&u.taken>0)return!1;let w=u?.pass?R.filter(u.pass.keep):R;Gr(t,w),this.keepWhatStatusesNeed(t,e,w,k);let A=this.holdBackWhatExclusionsCost(t,e,f,w,k,await this.excludedByKeyPrefix(t,e.objectApiName,f));k&&t.scopeCache?.addReached(e.objectApiName,k);let S=w.find(I=>typeof I.Id=="string")?.Id;if(typeof S=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,S.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,w.length);let I=await t.referenceDataMapper.resolve(e.objectApiName,w,a);for(let z of I.mappings)c.addExisting(z.sourceId,z.targetId);return I.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:I.unmatched.length,attemptedCount:w.length,referenceData:!0,samples:ww(e.objectApiName,I.unmatched)}),t.scopeCache&&Kl(t.scopeCache,e.objectApiName,w),t.linkedCount+=I.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${I.mappings.length} resolved, ${I.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,w,f),e.objectApiName===Gt&&t.standardPricebookId){let I=t.standardPricebookId,z=w.filter(Z=>Z.Id!==I);z.length!==w.length&&(w.length=0,w.push(...z))}let v=t.scopeCache;if(n&&v&&He.has(e.objectApiName))return rs(v,e.objectApiName,w,f,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),t.catalogNodes.push({node:e,fieldInfos:f}),t.readAtItsTurn.set(e.objectApiName,{records:w,fieldInfos:f}),!1;let j=t.heldForExclusions.get(e.objectApiName);if(A>0&&w.length===0&&j&&!u)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,j.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,j)}),!1;if(mt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,w,f);let I=t.sample;if(I?.drawn.has(e.objectApiName)){let Z=w.filter(J=>this.inThePlan(I,e.objectApiName,String(J.Id)));w.length=0,w.push(...Z);let H=t.standardPricebookId,U=new Set(w.filter(J=>J[tn]===H).map(J=>xd(J,t.sellingModels)));for(let J of w)J[tn]!==H&&(U.has(xd(J,t.sellingModels))||I.withoutStandard.add(it(String(J.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,w,f);let z=await this.keptPrices(t,w);z.length!==w.length&&(w.length=0,w.push(...z))}t.scopeCache&&rs(t.scopeCache,e.objectApiName,w,f,{keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),await this.notePastDraft(t,e.objectApiName,w);let P=e.objectApiName===s.rootObjectApiName||He.has(e.objectApiName)?[]:lw(e.objectApiName,f,t),B=new Set(n?[...t.waitingFor.values()].flat().map(I=>I.objectApiName):[]);for(let I of P){let z=t.readAgainUnder.get(I)??[];t.readAgainUnder.set(I,[...z,{node:e,fieldInfos:f,whileWaiting:B.has(I)}])}if(s.files&&s.stream?.everything!==!0){let I=w.flatMap(z=>typeof z.Id=="string"&&!s.writtenBefore.retried(z.Id)?[z.Id]:[]);t.fileScope.set(e.objectApiName,I)}if(this.withoutFileContent(t,e.objectApiName,l,w.length>0),u&&(u.carry.rows+=w.length),u?.pass||t.readByObject.set(e.objectApiName,(u?u.carry.rows:w.length)+(j?.size??0)),this.holdTheRootsRows(t,e.objectApiName),t.preread.set(e.objectApiName,{fieldInfos:f,createableSet:p,records:w,targetSetsPending:y}),s.dryRun){let I=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,w,p),z=w.length-I;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${z} record(s) would be inserted`+(I>0?`, ${I} would be written by the platform with ${Bn(e.objectApiName)}`:"")+Vh(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,f,w),!0}catch(l){if(l instanceof be||l instanceof Ls||Ia(l))throw l;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),u&&(u.failed=!0);let f=s.isScoped?0:Math.max(0,Mh(e,s.maxRecordsPerObject)-(u?.read??0));return t.failedCount+=f,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:f,attemptedCount:f,samples:[{recordSummary:"(stage failed before insert)",messages:[V(l)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(l)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(R=>R.isReference&&Ye(d,R.name,R.nillable)),u=c.filter(R=>{let w=R.referenceTo??[];return w.length===1&&w[0]!==d&&a.has(w[0])}),l=c.filter(R=>{let w=R.referenceTo??[];return w.length>1&&w.some(A=>a.has(A))}),f=d===et&&e.sellingModels&&a.has(zt),p=Zh(d),h=c.length>0&&e.heldForExclusions.size>0;if(u.length===0&&l.length===0&&!h&&!f&&!p)return 0;let g=R=>{for(let S of u){let v=R[S.name];if(typeof v=="string"&&v!==""&&!e.remapper.get(v))return{field:S.name,excluded:(S.referenceTo??[])[0]}}for(let S of l){let v=R[S.name];if(typeof v!="string"||v===""||e.remapper.get(v))continue;let j=i.get(v.slice(0,3));if(j!==void 0&&(S.referenceTo??[]).includes(j))return{field:S.name,excluded:j}}let w=h?Jh(e,R,c):void 0;if(w)return w;let A=R[Jn];if(f&&typeof A=="string"&&A!=="")return{field:Jn,excluded:zt}},m=e.heldForExclusions.get(d)??new Map,y=p?e.statusChildrenRead.get(p.parent)??{kept:new Set,held:new Map}:void 0,k=[];for(let R of o){let w=g(R),A=p?R[p.lookup]:void 0;if(!w){k.push(R),y&&typeof A=="string"&&y.kept.add(A);continue}y&&typeof A=="string"&&!y.held.has(A)&&y.held.set(A,w);let S=R.Id;typeof S=="string"&&(s?.delete(S),!m.has(S)&&(m.set(S,w),e.failedCount++))}y&&p&&e.statusChildrenRead.set(p.parent,y),m.size>0&&e.heldForExclusions.set(d,m);let O=o.length-k.length;return O>0&&(o.length=0,o.push(...k)),O}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Ye(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let u=c.Id,l=typeof u=="string"&&!dn(t,c)?Jh(e,c,i):void 0;typeof u=="string"&&l?d.push({id:u,row:c,why:l}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=Yh(e),n=!1;for(let[o,s]of[...e.preread]){if(!He.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,u=typeof c=="string"?Xh(e,o,c,t):void 0;typeof c=="string"&&u?a.push({id:c,row:d,why:u}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=Yh(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Xh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:f,why:p}of s)d.set(f,p);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(f=>f.isReference);for(let{row:f,why:p}of s)for(let h of c){let g=f[h.name];typeof g!="string"||g===""||e.namedByRowsHeldBack.has(g)||e.namedByRowsHeldBack.set(g,{field:h.name,excluded:p.excluded,namedBy:t})}let u=new Set(s.map(({id:f})=>f)),l=e.fileScope.get(t)??[];if(l.length>0&&e.fileScope.set(t,l.filter(f=>!u.has(f))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+Bs(Ms(s.map(({why:f})=>f)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:zr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=Zh(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:u}of o){let l=c[s.lookup];typeof l=="string"&&!a.has(l)&&a.set(l,u)}let d=new Set;for(let c of n){let u=c[s.lookup];typeof u=="string"&&d.add(u)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,_w(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===ct))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(ct)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)Oo(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===$e);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(u=>u.included&&u.objectApiName===$e),o=e.config.stream?.resumeAfter,s=o?.has($e)===!0||o?.has(zo($e,Ph))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has($e)&&e.graph.nodes.some(u=>u.included&&u.objectApiName===ct))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:Ph,where:"ActivityId != null",keep:u=>Oo(u),expected:t,stopped:`Stopped ${$e} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${$e} after their task`}})}catch(u){throw e.emailsWrittenFirst=void 0,u}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&($d(e,$e,t),e.onProgress(Kw(o,t,n,Vh(e,$e))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get($e)?.records??[]){let u=c.ActivityId,l=c.Id;if(typeof u!="string"||u===""||typeof l!="string"||!e.remapper.isCreated(l))continue;let f=e.remapper.get(l);f&&n.set(u,f)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await Ii(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:ct,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let u=String(c.Id),l=n.get(u),f=l===void 0?void 0:s.get(l);return f===void 0?!0:(e.remapper.addExisting(u,f,ct),cr(e,u),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),Un(e,ct,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),Un(e,ct,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get($e)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||Oo(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await Ii(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:ct,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,ct),cr(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!So(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,u=Pi[t],l=a.decisions.defaultOf(t,u),f=c?await this.writesAs(e):void 0,p=await Bi(t,n,{source:y=>this.deps.queryRecords(e.sourceOrgId,y),target:y=>this.deps.queryRecords(e.targetOrgId,y),targetIdOf:y=>d.get(y),mappedUser:y=>a.ownerMappings[y],...l!==void 0?{defaultUser:l}:{},written:s,...c?{simulated:{ownerOf:y=>a.ownerMappings[y]??(f??=c.idFor(gg)),idFor:()=>c.idFor(o)}}:{}});p.defaulted.size>0&&l!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:u,to:l},p.defaulted.size);for(let[,{field:y,parentObject:k}]of p.held)k==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:y,rows:1,detail:{type:"reference"},decisions:[...Wu.required_field_missing??[]]});let h=0,g=0;for(let[y,{id:k,owners:O,notKept:R,unread:w=[]}]of p.linked){let A=String(y.Id);d.addExisting(A,k,t),d.isCreated(String(y.OpportunityId))&&(cr(e,A),g++),O&&h++;for(let S of R)i.notKept.set(S,(i.notKept.get(S)??0)+1);for(let S of w)i.unread.set(S,(i.unread.get(S)??0)+1)}let m=p.linked.size;return m>0&&(e.linkedCount+=m),Un(e,t,g),m>g&&e.existingRecords.push({objectApiName:t,linked:m-g,unidentified:0}),{rows:m>0?n.filter(y=>!p.linked.has(y)):n,lookups:p.lookups,held:p.held,linked:m,owners:h,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,u=g=>a.wasCreated(g)||c.writtenBefore.has(g),l=[];if(t.forEach(({source:g},m)=>{let y=g[za],k=g[Ha];if(typeof y!="string"||typeof k!="string"||!u(y)||!u(k))return;let O=a.get(y),R=a.get(k);O&&R&&l.push({index:m,quote:O,product:R})}),l.length===0)return i;let f=g=>s.updatable?s.updatable.has(g):s.fields?.find(m=>m.name===g)?.updateable!==!1,p;if(d)p=this.copiesASimulationFinds(e,t,l,s.keyPrefix);else{let g=O=>s.fields===void 0||s.fields.some(R=>R.name===O&&R.queryable!==!1),m=[...new Set(l.flatMap(({index:O})=>Object.keys(n[O]??{})))].filter(O=>f(O)&&g(O)),y;try{y=await tp(O=>this.deps.queryRecords(e.targetOrgId,O),l,m)}catch(O){return e.errors.push({objectApiName:rr,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${V(O)}`]}]}),i}let k=new Set;for(let O of o){let R=a.get(String(O.Id));R&&k.add(R.slice(0,15))}p=np(l,y,k)}if(p.size===0)return i;let h=d?0:await this.giveTheCopiesTheirFields(e,t,n,p,f);for(let[g,m]of p){let y=t[g],k=typeof y.source.Id=="string"?y.source.Id:void 0,O=String(m.Id);k!==void 0&&a.add(k,O,rr),y.nullifiedFks.length>0&&this.oweToTheSecondPass(e,y.nullifiedFks.map(R=>({objectApiName:rr,newId:O,sourceId:k,fieldName:R.field,sourceRefId:R.sourceRefId,...R.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let g of[...p.keys()].sort((m,y)=>y-m))t.splice(g,1),n.splice(g,1);return{taken:p.size,given:h}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=l=>typeof l=="string"&&l!==""?l.slice(0,15):void 0,d=new Map;for(let l of e.pendingFkUpdates){let f=a(l.sourceId),p=a(l.sourceRefId);l.objectApiName===De&&l.fieldName===bs&&f&&p&&d.set(f,p)}if(d.size===0)return s;let c=new Map;for(let l of e.preread.get(Zf)?.records??[]){let f=a(l.Id),p=a(l.OpportunityId);f&&p&&c.set(f,p)}let u=new Set;for(let{index:l}of n){let{source:f}=t[l],p=a(f[Ha]),h=a(f[za]),g=p?c.get(p):void 0;!p||!h||!g||d.get(g)!==h||u.has(p)||(u.add(p),s.set(l,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:rr,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[l,f]of o){let p=new Set(t[l].nullifiedFks.map(g=>g.field)),h=rp(n[l]??{},f,s,p);Object.keys(h).length>0&&a.push({Id:f.Id,...h})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],u=0;for(let l=0;l<a.length;l+=lg){let f=a.slice(l,l+lg);if(!d||this.isAborted){c.push(`${f.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let p=await d(e.targetOrgId,i.objectApiName,f);f.forEach((h,g)=>{let m=p[g];m?.success?u++:c.push(`${String(h.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(p){c.push(`${f.length} not updated: ${V(p)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),u}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:y},k)=>{let O=y.OpportunityId,R=n[k]?.[We];typeof O!="string"||typeof R!="string"||R===""||Fi(y)&&d.writtenBefore.has(O)&&c.set(O,R)}),e.contactSentWith.size===0&&c.size===0)return s;let u=Ir(t.map(({source:y},k)=>({OpportunityId:y.OpportunityId,[We]:n[k]?.[We],IsPrimary:y.IsPrimary})),y=>i.isCreated(y)?e.contactSentWith.get(y):c.get(y));if(u.length===0)return s;let l=y=>o.updatable?o.updatable.has(y):o.fields?.find(k=>k.name===y)?.updateable!==!1,f=a?u.filter(y=>i.isCreated(String(t[y].source.OpportunityId))):[],p=u.filter(y=>!f.includes(y)),h=new Map(f.map(y=>[y,{Id:a?.idFor(o.keyPrefix)??""}]));if(p.length>0){let y=S=>o.fields===void 0||o.fields.some(v=>v.name===S&&v.queryable!==!1),k=a?[]:[...new Set(p.flatMap(S=>Object.keys(n[S]??{})))].filter(S=>l(S)&&y(S)),O=new Map(p.map(S=>[S,{opportunity:String(i.get(String(t[S].source.OpportunityId))),contact:String(n[S]?.[We])}])),R;try{R=await Ci(S=>this.deps.queryRecords(e.targetOrgId,S),[...new Set([...O.values()].map(({opportunity:S})=>S))],k)}catch(S){e.errors.push({objectApiName:Ge,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${V(S)}`]}]}),R=[]}let{found:w,alike:A}=Ni(O,R);for(let[S,v]of w)h.set(S,v);if(A.length>0){for(let S of A)e.contactSentWith.delete(String(t[S].source.OpportunityId));e.errors.push({objectApiName:Ge,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[au(A.length)]}]})}}if(h.size===0)return s;let g=a?0:await this.giveTheCopiesTheirFields(e,t,n,h,l,{objectApiName:Ge,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[y,k]of h){let O=t[y],R=typeof O.source.Id=="string"?O.source.Id:void 0,w=String(k.Id);if(R===void 0)continue;let A=String(O.source.OpportunityId);e.contactSentWith.delete(A),i.addExisting(R,w,Ge),i.wasCreated(A)&&(cr(e,R),m++),O.nullifiedFks.length>0&&this.oweToTheSecondPass(e,O.nullifiedFks.map(S=>({objectApiName:Ge,newId:w,sourceId:R,fieldName:S.field,sourceRefId:S.sourceRefId,...S.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let y of[...h.keys()].sort((k,O)=>O-k))t.splice(y,1),n.splice(y,1);return e.linkedCount+=h.size,Un(e,Ge,m),h.size>m&&e.existingRecords.push({objectApiName:Ge,linked:h.size-m,unidentified:0}),{linked:h.size,given:g}}async mapContactsOfPersonAccounts(e,t=e.preread.get(Se)?.records??[]){let n=new Map;for(let i of t){let a=i[Er],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null),ie),e.remapper.isCreated(a)&&this.contactWithItsAccount(e,i));return}let s;try{s=await iu(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:Se,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${V(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c,ie),e.remapper.isCreated(d)&&this.contactWithItsAccount(e,a)}}contactWithItsAccount(e,t){cr(e,t);let n=e.sample;(n?.drawn.has(ie)?this.inThePlan(n,ie,t):e.writtenObjects.has(ie))||(e.linkedCount++,Un(e,ie,1),n?.drawn.has(ie)&&e.personContactsOutsideTheSample++)}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,Se).then(t=>t.some(n=>n.name===Er),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${Se}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(rn);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(u=>[u.sourceId,u.targetId])),d=u=>{let l=u.RecordTypeId;return n&&typeof l=="string"&&l!==""?l:void 0},c=o.some(u=>d(u)===void 0)?Ba((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes):void 0;return new Set(o.filter(u=>{let l=d(u),f=l===void 0?c:a.get(l);return f!==void 0&&!i.has(f.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[Er];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(So(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!dn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===Ge)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(De)?.records??[],e.preread.get(ie)?.records??[],n)).size;if(t===Se)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ie)return 0;let s=n.filter(i=>rn(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:ie,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let u=String(c.Id),l=e.remapper.get(u);if(l){e.remapper.addExisting(u,l,ie),n++,Vw(e,u)&&o++;continue}let f=c.AccountId;typeof f=="string"&&e.remapper.get(f)?i++:s++}n>0&&(e.linkedCount+=n),Un(e,ie,o),n>o&&e.existingRecords.push({objectApiName:ie,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:Kh.accountNotWritten}]:[],...i>0?[{count:i,why:Kh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ie,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:u})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${u.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}async reportNotInTargetOfTheScope(e){for(let t of e.notInTargetPutOff?.splice(0)??[]){let n=await this.deps.describeFields(e.sourceOrgId,t.objectApiName).catch(()=>{}),o=n&&on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,readObjects:e.readObjects,catalog:He});if(o?.kind!=="skip"||o.reason!==aa){this.reportNotInTarget(t,e);continue}e.skippedCount++,e.onProgress({objectName:t.objectApiName,status:"skipped",progress:100,message:`Skipped ${t.objectApiName} (not in the target org; nothing the run read names its records)`})}}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!He.has(e.objectApiName)?!1:t.kind==="skip"||!Hl(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=Wl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>Nh(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let u=d.objectApiName,l=[...c],f=o.objectSoqlFilters?.[u],p=async m=>u===Gt&&e.standardPricebookId?m.filter(y=>y.Id!==e.standardPricebookId):mt(u)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,l),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,l),this.keptPrices(e,m)):m;if(u===zt){if(!a.has(Zo)&&!a.has(jr))continue;let m=on({node:d,edges:e.graph.edges,fieldInfos:l,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:f,fieldsLeftOut:o.fieldExclusions[u],readObjects:e.readObjects,catalog:He});if(m.kind!=="query")continue;(await this.readMore(e,d,l,m.statements,"named by records read after the catalog",p)).length>0&&a.add(u);continue}let h=Ht(l,o.fieldExclusions[u]),g=new Set;for(let m=0;m<pw;m++){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let y=[...Nh(n,u)].filter(O=>!g.has(O));if(y.length===0)break;for(let O of y)g.add(O);if((await this.readMore(e,d,l,new kn().buildById({objectApiName:u,selectFields:h.length>0?h:["Id"],ids:new Set(y),extraWhere:f}),m===0?"named by records read after the catalog":"named by its own records read before them",p)).length===0)break;a.add(u)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),u=o.isRead(d)?o.scopeOf(d):void 0,l=new Set([...o.get(d)??[]].filter(k=>!c?.has(k)&&!u?.has(k))),f=new Set(e.graph.edges.filter(k=>k.targetObject===d&&i.has(k.sourceObject)).map(k=>k.sourceObject));if(l.size===0&&f.size===0)continue;let p=await this.fieldsReadAgain(e,a);if(!p)continue;let{fields:h}=p,g=s.objectSoqlFilters?.[d],m=[];if(l.size>0){let k=Ht(h,s.fieldExclusions[d]);m.push(...new kn().buildById({objectApiName:d,selectFields:k.length>0?k:["Id"],ids:l,extraWhere:g}))}if(f.size>0){let k=on({node:a,edges:e.graph.edges,fieldInfos:h,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:g,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:He,under:f});k.kind==="query"&&m.push(...k.statements)}m.length===0||(await this.readMore(e,a,h,m,"for what the catalog read again brought")).length===0||(i.add(d),p.described&&this.withoutFileContent(e,d,p.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!Pn(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,u=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,l=u>0?u-(e.readByObject.get(c)??0):0;if(u>0&&l<=0)return o.length>0&&e.cappedObjects.add(c),[];let f=a.isRead(c),p=new Set(f?a.scopeOf(c)??[]:[]),h=m=>typeof m.Id!="string"||!p.has(m.Id);this.holdTheRootsReading(e,c,o.length);let g;try{let m=await Wr(l>0?ca(o,l,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},B=>this.deps.queryRecords(e.sourceOrgId,B,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Gr(e,m);let y=m.filter(h);this.keepWhatStatusesNeed(e,t,y,void 0);let k=e.heldForExclusions.get(c),O=0;for(let B of k?y:[]){let I=B.Id;typeof I!="string"||k?.get(I)?.namedBy===void 0||(k.delete(I),O++)}O>0&&(k?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=O,e.readByObject.set(c,(e.readByObject.get(c)??O)-O));let R=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,y,void 0,await this.excludedByKeyPrefix(e,c,n));let w=[...e.heldForExclusions.get(c)??[]].filter(([B])=>!R.has(B));if(this.leaveToThePlatform(e,c,y,n),g=(await i(y)).filter(h),rs(a,c,g,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,g.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])),await this.notePastDraft(e,c,g),g.length===0&&w.length===0)return[];if(d.files&&d.stream?.everything!==!0){let B=g.flatMap(I=>typeof I.Id=="string"?[I.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...B])}f||e.skippedCount--;let A=e.preread.get(c),S=A?.records??[],v=mt(c)?await this.keptPrices(e,[...S,...g]):[...S,...g],j=v.length-S.length,P=A?.createableSet??new Set(n.filter(B=>B.createable).map(B=>B.name));if(e.preread.set(c,A?{...A,records:v}:{fieldInfos:n,createableSet:P,records:v,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+j+w.length),this.holdTheRootsRows(e,c),d.dryRun){let B=await this.writtenWithTheirAccountOnADryRun(e,c,mt(c)?[]:g,P);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${j-B} more record(s) would be inserted`+(B>0?`, ${B} more would be written by the platform with ${Bn(c)}`:"")+`, ${s}`+Bs(Ms(w.map(([,I])=>I)),!0)})}}catch(m){if(m instanceof be||Ia(m))throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[V(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,g),g}async keptPrices(e,t){let n=await this.pricesKeyOf(e),{kept:o,standsFor:s}=ki(t,n);if(this.pricesStandFor(e,s),n.oneCurrency)for(let i of o){let a=i.Id,d=i[wt];typeof a=="string"&&typeof d=="string"&&d!==""&&e.pricesKeptAsRead.set(a,{from:d,to:n.oneCurrency.code})}return o}async pricesKeyOf(e){e.oneCurrency??=(async()=>{let n=a=>this.deps.describeFields(a,et).catch(()=>[]),[o,s]=await Promise.all([n(e.sourceOrgId),n(e.targetOrgId)]),i=a=>a.some(d=>d.name===wt);if(!(s.length===0||!i(o)||i(s)))try{let a=await this.deps.orgCurrency?.(e.targetOrgId);return typeof a=="string"&&/^[A-Z]{3}$/.test(a)?{code:a}:{}}catch(a){return Xe.warn(`[forge] the target's one currency could not be read: ${V(a)}`),{}}})();let t=await e.oneCurrency;return{sellingModel:e.sellingModels,...t?{oneCurrency:t}:{}}}pricesStandFor(e,t){for(let{left:n,kept:o}of t){let s=n.Id,i=o.Id;if(typeof s!="string"||typeof i!="string"||s===i||e.prices.standsFor.get(s)===i)continue;e.remapper.alias(s,i),e.prices.standsFor.set(s,i);for(let[c,u]of e.prices.standsFor)u===s&&(e.remapper.alias(c,i),e.prices.standsFor.set(c,i));let a=n[wt],d=o[wt];typeof a=="string"&&typeof d=="string"&&a!==d&&e.pricesSwappedSaid.push({from:a,to:d,how:"replaced",forLines:!1})}}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=u=>xd(u,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let u of n){let l=u.Id;if(typeof l=="string"&&c.add(l),u[tn]===s)continue;let f=u[Fn];typeof f=="string"&&f&&(a.add(f),d.add(i(u)))}if(a.size!==0)try{let u=new kn().buildJoining({objectApiName:e.objectApiName,selectFields:Ht(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Fn,ids:a},whole:{field:tn,ids:new Set([s])}}),l=0;for(let f of u)for(let p of await this.deps.queryRecords(t.sourceOrgId,f)){let h=p.Id;typeof h=="string"&&c.has(h)||d.has(i(p))&&(n.push(p),Gr(t,[p]),l++)}l>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${l} standard price book entr${l===1?"y":"ies"} the custom prices depend on`})}catch(u){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[V(u)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=Da(a).filter(g=>!d||d.has(Wa(g))),u=[],l=[...new Set(c.map(({currency:g})=>g))].filter(g=>/^[A-Z]{3}$/.test(g));if(l.length>0)try{let g=new kn().buildJoining({objectApiName:e.objectApiName,selectFields:Ht(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Fn,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:tn,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${wt} IN (${l.map(m=>`'${m}'`).join(", ")})`});for(let m of g)u.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(g){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[V(g)]}]});return}let f=t.sample;if(f?.drawn.has(e.objectApiName)){let g=u.filter(m=>this.inThePlan(f,e.objectApiName,String(m.Id)));u.length=0,u.push(...g)}let p=_a(a,d?u.filter(g=>d.has(La(Qf(g,t.sellingModels),String(g[wt])))):u),h=new Set(n);n.length=0,n.push(...p.rows),Gr(t,p.rows.filter(g=>!h.has(g)));for(let[g,m]of p.standsFor)t.remapper.alias(g,m),t.prices.standsFor.set(g,m);for(let[g,m]of t.prices.standsFor){let y=p.standsFor.get(m);y!==void 0&&(t.remapper.alias(g,y),t.prices.standsFor.set(g,y))}for(let[g,m]of p.convertedInto)t.prices.convertedInto.set(g,m);for(let[g,m]of p.written)t.prices.written.set(g,m);for(let[g,m]of p.keys)t.prices.keys.set(g,m);t.pricesSwappedSaid.push(...p.said),!(p.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:qa(p.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===wt)||!t.some(d=>typeof d[wt]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[wt]:n};e.config.decisions.applyToRow(et,o,void 0,new ra);let s=o[wt];return typeof s=="string"&&t.active.has(s)?s:Eu(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(et);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=Da({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(Wa)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!Po(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(u=>u.name===Iu[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:u}]of Object.entries(ws)){let l=i(c);for(let f of e.preread.get(d)?.records??[]){let p=f[_r];if(typeof p!="string"||typeof f[u]!="string")continue;let h=e.prices.standsFor.get(p)??p;if(!o.has(h))continue;let g=f[ze],m=!l&&typeof g=="string"&&n.has(g)?[g]:[...n],y=a.get(h)??new Set;for(let k of m)y.add(k);a.set(h,y)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(ws))for(let a of e.preread.get(s)?.records??[]){let d=a[_r];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let u=this.currencyTheirRecordWentIn(e,a,i);if(u===void 0)continue;let l=o.get(c)??new Set;l.add(u),o.set(c,l)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[ze];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=ws[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[_r];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let u=e.prices.written.get(La(d,c));return u===void 0||u===a||u===i||e.remapper.get(u)===void 0?s:{...s,[_r]:u}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(u=>!dn(e.config,u)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?Gh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=u=>t.find(l=>l.objectApiName===u)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(u=>String(u.Id)));for(let u of t)if(!(!So(u.objectApiName)||u.rows.length===0)){if(s.size===0)break;o.set(u.objectApiName,await this.teamThePlatformWrites(e,u.objectApiName,u.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(Se),n(ie));i.size>0&&o.set(ie,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(De),n(ie),n(Ge)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(Ge).filter(u=>!a.has(u))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(Ge,c),t.map(u=>{let l=o.get(u.objectApiName),f=u.objectApiName===Ge&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!l||l.size===0?{...u,...f}:{...u,rows:u.rows.filter(p=>!l.has(p)),leftOut:{...u.leftOut,byThePlatform:l.size},...f}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,i).then(w=>({ok:!0,sets:w}),w=>({ok:!1,error:w})));if(!c.ok){o.push(s);continue}let u=dr(d.createableSet,c.sets.creatable),l=new Set(n.fieldExclusions[i]??[]),f=n.fieldMappings[i]??{},p=new Set(Object.values(f)),h=new Set(await e.maskedSourceFields(i).catch(()=>[])),g=n.anonymization,m=new Set(e.anonymize&&g?g.fields[i]??this.detectedPersonalFields(e,g,i,d.fieldInfos):[]),y=new Set(e.contactPoints?Na(d.fieldInfos).map(({name:w})=>w):[]),k=n.decisions.truncatedFieldsOf(i),O=c.sets.fields.filter(({name:w,unique:A,externalId:S})=>A===!0&&u.has(w)&&!(n.upsertMode==="auto"&&S===!0)&&!l.has(w)&&f[w]===void 0&&!p.has(w)&&!h.has(w)&&!m.has(w)&&!y.has(w)&&!k.has(w)&&!(i===Se&&w.endsWith("__pc"))),R=new Map;for(let w of O){let{name:A}=w,S=new Map;for(let P of a){let B=P[A];if(typeof B!="string"||B===""||Bd.test(B))continue;let I=Rn(w,B);S.has(I)||S.set(I,B)}let v=[...S.values()];if(v.length===0)continue;let j=new Set;try{let P=Le(i),B=Le(A);for(let I of On(v,ug)){let z=await this.deps.queryRecords(e.targetOrgId,`SELECT ${B} FROM ${P} WHERE ${B} IN (${I})`);for(let Z of z){let H=Z[A];typeof H=="string"&&j.add(Rn(w,H))}}}catch{continue}for(let P of a){let B=P[A];typeof B=="string"&&j.has(Rn(w,B))&&!R.has(P)&&R.set(P,A)}}if(R.size===0){o.push(s);continue}o.push({...s,rows:a.filter(w=>!R.has(w)),leftOut:{...s.leftOut,linkedByValue:{rows:R.size,fields:[...new Set(R.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=u=>u.slice(0,15),i=new Map;for(let u of t){let l=u.OpportunityId,f=u[We];typeof l!="string"||typeof f!="string"||f===""||Fi(u)&&n.writtenBefore.has(l)&&i.set(s(l),f)}if(i.size===0)return o;let a=Ir(t,u=>i.get(s(u))),d=u=>typeof u=="string"&&u!==""?n.writtenBefore.get(u)??e.remapper.get(u):void 0,c=new Map;for(let u of a){let l=d(t[u].OpportunityId),f=d(t[u][We]);l!==void 0&&f!==void 0&&c.set(u,{opportunity:l,contact:f})}if(c.size===0)return{...o,mayBe:a.length};try{let u=await Ci(f=>this.deps.queryRecords(e.targetOrgId,f),[...new Set([...c.values()].map(({opportunity:f})=>f))]),{found:l}=Ni(c,u);return{linked:new Set([...l.keys()].map(f=>t[f])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(u=>u.objectApiName));if(!i.has(De)||(s.fieldExclusions[De]??[]).includes(We)||s.fieldMappings[De]?.[We]!==void 0)return 0;if([De,Ge,ie].some(u=>o.has(u)))return;let d=u=>t.findIndex(l=>l.objectApiName===u),c=i.has(ie)&&d(ie)<d(De);try{if(!(await this.deps.describeFields(e.sourceOrgId,De)).some(w=>w.name===We&&w.createable)||!(await an(this.deps.describeFields,e.targetOrgId,De)).creatable.has(We))return 0;let f=w=>s.objectSoqlFilters?.[w],p=s.stream?.resumeAfter.get(Ge),h=f(De),g=f(ie),m=[...f(Ge)?[`(${f(Ge)})`]:[],`Opportunity.${We} != null`,...p&&Ft.test(p.lastId)?[`Id > '${p.lastId}'`]:[],...h?[`OpportunityId IN (SELECT Id FROM ${De} WHERE (${h}))`]:[],...c&&g?[`${We} IN (SELECT Id FROM ${ie} WHERE (${g}))`]:[]],y=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${We}, IsPrimary, Opportunity.${We} FROM ${Ge} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${Eh+1}`);if(y.length>Eh)return;let k=w=>c||s.writtenBefore.has(w)||e.remapper.get(w)!==void 0,O=w=>{let A=w.Opportunity,S=A!==null&&typeof A=="object"?A[We]:void 0;return typeof S=="string"&&S!==""?S:void 0},R=new Map;for(let w of y){let A=w.OpportunityId,S=O(w);typeof A!="string"||S===void 0||s.writtenBefore.has(A)||!k(S)||R.set(A.slice(0,15),S)}return Ir(y,w=>R.get(w.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[De]??[]).includes(We)||o.fieldMappings[De]?.[We]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[De]??[]).includes(We)||s.fieldMappings[De]?.[We]!==void 0)return new Set;let a=e.preread.get(De);if(!a?.createableSet.has(We))return new Set;let d=await(a.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,De).then(f=>({ok:!0,sets:f}),f=>({ok:!1,error:f})));if(!d.ok||!d.sets.creatable.has(We))return new Set;let c=f=>f.slice(0,15),u=new Set(n.map(f=>c(String(f.Id)))),l=new Map;for(let f of t){let p=f.Id,h=f[We];typeof p!="string"||typeof h!="string"||h===""||dn(s,f)||!u.has(c(h))&&i.get(h)===void 0||l.set(c(p),h)}return l.size===0?new Set:new Set(Ir(o,f=>l.get(c(f))).map(f=>o[f]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,Pi[t]),a=await this.writesAs(e);try{let d=await Bi(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${gg}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>rn(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(Se)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[Er])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(u=>u.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(u=>!u.available&&!u.master))return[];let d=await(n.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,t).then(u=>({ok:!0,sets:u}),u=>({ok:!1,error:u}))),c=d.ok?dr(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let u=c.RecordTypeId;typeof u=="string"&&d.set(u,(d.get(u)??0)+1)}return[...Mu(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==De||o.fieldName!==bs);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:De,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${De}.${bs})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return fg(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:i,recordId:a}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,i,a);for(let i of n.withTheirRecord??[])cr(e,i);let o=Math.min(n.linkedExistingCount,n.writtenByThePlatformCount??0);Un(e,t,o);let s=n.linkedExistingCount-o;(s>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:s,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,la(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<aw&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[Sl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},u=o.filter(l=>l.isReference&&l.name!=="RecordTypeId"&&!d.has(l.name)&&fd(l,s,c[l.name])&&(l.referenceTo??[]).some(f=>a.has(f)));if(u.length!==0)for(let l of n){let f=l.Id;if(typeof f!="string")continue;let p=i.writtenBefore.get(f);if(p)for(let h of u){let g=l[h.name];if(typeof g!="string"||!g||i.writtenBefore.has(g)&&!e.store?.owesUntold(f))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:p,sourceId:f,fieldName:c[h.name]??h.name,sourceRefId:g}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new cp({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:fg(t),onAnswered:()=>t.flush(),onRefusedByFilter:(l,f,p)=>this.noteLeftEmptyByFilter(e,l,f,p),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??dw,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=l=>t.wasPatched(l.newId,l.fieldName),d=new dp;for(let l of i)d.note(0,l.newId);let c=1;for(let l of t.owedPages(s)){for(let{update:f}of l)a(f)||d.note(c,f.newId);c++}let u=l=>d.spans(l.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),u);for(let l of t.owedPages(s)){let f=l.filter(({update:p,toRowWrittenBefore:h})=>!a(p)&&(!h||e.remapper.get(p.sourceRefId)!==void 0)).map(({update:p})=>p);await n.patch(this.keepLookupsInTheClone(e,f,o),u)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let u=n[c]?.cleaned.RecordTypeId;if(typeof u!="string"||u===""||!("RecordTypeId"in d))return;let l=s.recordTypeDecisions.get(u);if(l){l.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:l.from,...l.to!==null?{to:l.to}:{}});return}!e.simulated||!a||ey.test(u)||a.has(u)||i.set(u,(i.get(u)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:u}=e;if(!u)return;let l=t.objectApiName,f=new Set,p=0,h=d?mg(e.config,d):[],g=new Set,m=0;i({objectName:l,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${l} records: nothing is sent...`});for(let[y,k]of n.cleaned.entries()){let O=n.records[y]??{},R=d?qu(l,O,k.source,d):[];if(R.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:tf(O),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${R.map(P=>P.name).join(", ")}]`]});continue}let w=u.idFor(o),A=typeof k.source.Id=="string"?k.source.Id:void 0,S=c.get(O);if(S!==void 0){s.linkedExistingCount++,p++,f.add(S),A!==void 0&&e.remapper.addExisting(A,w,l);continue}let v=h.flatMap(P=>{let B=cy(O,P.name);return B===void 0?[]:[{field:P.name,key:Rn(P,B)}]}),j=v.map(({field:P,key:B})=>({field:P,id:u.holderOf(l,P,B)})).find(P=>P.id!==void 0);if(j?.id!==void 0){s.linkedExistingCount++,s.linkedToCreatedCount=(s.linkedToCreatedCount??0)+1,m++,g.add(j.field),A!==void 0&&e.remapper.addExisting(A,j.id,l);continue}s.successCount++;for(let{field:P,key:B}of v)u.hold(l,P,B,w);a&&!Yl(n.records[y]??{})&&a(k),A!==void 0&&e.remapper.add(A,w,l);for(let P of k.nullifiedFks)s.pendingFkUpdates.push({objectApiName:l,newId:w,sourceId:A,fieldName:P.field,sourceRefId:P.sourceRefId,...P.insertOnly?{insertOnly:!0}:{}})}p>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${p} fewer would be inserted, linked to the record${p===1?"":"s"} the target holds under the same ${[...f].join(", ")}, which its refusal of the row names`}),m>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${m} fewer would be inserted, linked to the record${m===1?"":"s"} the run creates under the same ${[...g].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([l,f])=>[f,l])),c=n.filter(l=>{let f=l.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,p=>{let h=d.get(p)??p;return a.has(h)?void 0:l[h]},cg(i,typeof f=="string"?f:void 0),e.decisionsApplied,s)}),u=n.length-c.length;return u>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${u} record${u===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=_u(s,d,u=>{if(u.recordType!==void 0)return i.get(u.recordType)?.picklists.get(u.field)?.values;let l=n.picklistValuesByField?.get(u.field);return l?[...l]:void 0});for(let u of c)o.add(u)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,u]of n.unmapped){let l=d.find(f=>f.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(zi("record_type_unmapped",s,l,u,Tg(n.targetObject)))}}let a=n.targetFields;return a?(Uu({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let u=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof u=="string"&&n.recordTypes?.has(u)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===ze&&i.createable)===!0&&o(ze)&&n.some(i=>typeof i[ze]=="string"&&i[ze]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===ze);if(!s||s.createable&&!Po(t)||!o.some(a=>typeof a[ze]=="string"&&a[ze]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=vu(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===ze&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let u=d[ze];if(typeof u!="string"||u===""||(s.set(u,(s.get(u)??0)+1),!c||c.chosenBy==="decision"))continue;let l=i.get(u)??{to:new Set,fields:new Set,kept:!1};l.to.add(c.to);for(let f of c.fields)l.fields.add(f);c.notConverted&&(l.kept=!0),i.set(u,l)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let u=i.get(d);e.gaps?.add(Gu(t,d,c,u&&{to:[...u.to].sort(),converted:[...u.fields].sort(),asRead:u.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map;for(let i of mg(e.config,n)){let a=new Map;for(let l of o){let f=l[i.name];if(typeof f!="string"||f===""||Bd.test(f))continue;let p=Rn(i,f),h=a.get(p);h?h.rows++:a.set(p,{value:f,rows:1})}if(a.size===0)continue;let d=new Set;try{let l=Le(t),f=Le(i.name),p=[...a.values()].map(({value:h})=>h);for(let h of On(p,ug)){let g=await this.deps.queryRecords(e.targetOrgId,`SELECT ${f} FROM ${l} WHERE ${f} IN (${h})`);for(let m of g){let y=m[i.name];typeof y=="string"&&d.add(Rn(i,y))}}}catch{continue}let c=0,u=0;for(let[l,{rows:f}]of a)d.has(l)&&(c+=f,u++);c>0&&e.gaps?.add(zu(t,i.name,c,u));for(let l of o){let f=l[i.name];typeof f=="string"&&d.has(Rn(i,f))&&!s.has(l)&&s.set(l,i.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===$e?this.endOfTheEmails(t,n!==void 0):t.onProgress,u=s.dryRun?"Simulated":"Completed",l=n===void 0?`${u} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${u} ${e.objectApiName} after their task`,f=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,p=t.preread.get(e.objectApiName);if(!p)return;let{fieldInfos:h,createableSet:g,targetSetsPending:m}=p;if(mt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,p.records,h,this.currenciesTheirLinesWant(t,p.records));let j=await this.keptPrices(t,p.records);j.length!==p.records.length&&(p.records.length=0,p.records.push(...j))}let y=n??p.records,k=y.filter(j=>dn(s,j)),O=e.objectApiName===ie?y.filter(j=>rn(j)&&!dn(s,j)):[],R=await this.personContactsOnTheirOwn(t,O),w=new Set(O.filter(j=>!R.rows.has(j))),A=k.length>0||w.size>0?y.filter(j=>!dn(s,j)&&!w.has(j)):y,S=A,v=[];try{let j=null,P,B=null,I,z,Z=await(m??an(this.deps.describeFields,a,e.objectApiName).then($=>({ok:!0,sets:$}),$=>({ok:!1,error:$})));if(Z.ok)j=Z.sets.creatable,P=Z.sets.updateable,B=Z.sets.picklistValuesByField,I=Z.sets.picklistFields,z=Z.sets.fields;else{let $=Z.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[$ instanceof Error?$.message:String($)]}]})}let H=j?dr(g,j):g,U=this.linkPersonContacts(t,[...w]);if(o&&(o.withTheirAccount+=U.linked,pd(o,U.notSent),U.linked===0&&(o.personContactsUnlinked+=w.size)),w.size>0&&U.linked===0&&A.length===0&&k.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${jn(e.objectApiName,w.size,Qt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(k.length>0&&(t.linkedCount+=k.length,o&&(o.writtenBefore+=k.length),this.oweLookupsOfRowsWrittenBefore(t,e,k,h,P),await this.oweStatusesFoundAfterStop(t,e.objectApiName,k),A.length===0&&w.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: 0 succeeded, ${Md(s,k.length)}, 0 failed`});return}let J=await this.targetObjectInfoOf(t,e.objectApiName),je=Xw(J);t.gaps?.knowRecordTypes(e.objectApiName,"target",J?.recordTypes??[]);let pe=await this.recordTypesHeldBack(e,A,J,H,t),ae=pe.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,A,pe):void 0,K=ae!==void 0&&ae.size>0&&(o!==void 0||ae.size<A.length);if(K){S=A.filter(D=>!ae.has(D)),t.failedCount+=ae.size;for(let D of ae.keys())t.heldInTheOrg.set(String(D.Id),"held");let $=[...ae.values()];if(v.push(...$),o?(o.withoutParent+=$.length,Hr($,o.withoutParentGroups),pd(o,Uh($))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:$.length,attemptedCount:0,samples:Cd(Hr($),t.failedObjects)}),o&&S.length===0)return}else if(o?.heldWhole!==void 0&&pe.length===0){t.failedCount+=A.length,o.heldWholeRows+=A.length;return}if(pe.length>0&&!K){for(let D of pe)t.gaps?.add(zh(D,J));if(t.failedObjects.add(e.objectApiName),t.failedCount+=A.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:A.length,attemptedCount:0,samples:pe.map(D=>({recordSummary:`RecordType=${D.developerName} (${D.recordCount} record${D.recordCount===1?"":"s"})`,messages:[Do(D)]}))}),o){o.heldWhole??=pe.map(Wo).join(" "),o.heldWholeRows+=A.length;return}let $=Qt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${jn(e.objectApiName,A.length,$)}: `+pe.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."});return}S=this.holdBackSkippedRows(t,e,S,c,je),S=this.leaveWhatHangsFromThePlatform(t,e,h,S);let X=0;if(e.objectApiName===$e&&n===void 0){let $=this.holdEmailsForTheirTask(t,S);if(X=S.length-$.length,S=$,X>0&&S.length===0){let D={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${Is(X)}`};c(D),o||(t.emailsAllWaiting={...D,status:"done",progress:100});return}}let ce=0;if(e.objectApiName===ct){let $=await this.linkTasksWrittenWithEmails(t,S);S=$.rows,ce=$.linked,o&&(o.withTheirEmail+=$.linked)}let Te=new Set(s.fieldExclusions[e.objectApiName]??[]),we=s.fieldMappings[e.objectApiName]??{},de=await this.teamOfTheOpportunities(t,e.objectApiName,S,J?.keyPrefix,h.flatMap($=>!$.isReference&&H.has($.name)&&!Te.has($.name)&&we[$.name]===void 0?[$.name]:[]));S=de.rows,o&&(o.teamOwners+=de.owners,o.teamOthers+=de.linked-de.owners,Dw(o.teamValues,de.values));let _=await this.rowsWithoutTheirParent(e,t,h,S);for(let[$,D]of await this.rowsWhoseParentTheTargetLacks(e,t,h,S,me=>H.has(me)&&!Te.has(me)&&we[me]===void 0))_.has($)||_.set($,D);let L=await this.rowsHeldInTheWholeOrg(e,t,h,S,$=>H.has($)&&!Te.has($)&&we[$]===void 0);for(let[$,D]of L.held)_.has($)||_.set($,D);if(L.aside.size>0){for(let le of _.keys())L.aside.delete(le);Ew(t,e.objectApiName,L.aside.values()),S.forEach((le,Ce)=>{let ht=L.aside.get(Ce);ht&&t.heldInTheOrg.set(String(le.Id),ht)});let $=S.filter((le,Ce)=>!L.aside.has(Ce)),D=new Map;S.forEach((le,Ce)=>{L.aside.has(Ce)||D.set(Ce,D.size)});let me=new Map;for(let[le,Ce]of _){let ht=D.get(le);ht!==void 0&&me.set(ht,Ce)}_.clear();for(let[le,Ce]of me)_.set(le,Ce);S=$}if(S.forEach(($,D)=>{let me=de.held.get($);me&&!_.has(D)&&_.set(D,{field:me.field,parentObject:me.parentObject,reason:me.why})}),_.size>0&&(s.stream?.everything===!0&&S.forEach(($,D)=>{_.has(D)&&t.heldInTheOrg.set(String($.Id),"held")}),S=S.filter(($,D)=>!_.has(D)),t.failedCount+=_.size,o?(o.withoutParent+=_.size,Hr(_.values(),o.withoutParentGroups),pd(o,[{count:_.size,why:Nd}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:_.size,attemptedCount:0,samples:Ow(_,t.failedObjects)}),S.length===0&&de.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let $=X===0?Qt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${jn(e.objectApiName,_.size,$)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:h,records:S,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?($,D,me,le)=>this.anonymizeRows(t,$,[D],[me],le,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:($,D)=>this.withoutFileContent(t,$,D,!0),startAsDraft:async($,D)=>(await this.startAsDrafts(t,$,[D])).get(0),oweStatus:($,D,me)=>this.oweStatus(t,$,D,me),objectOf:($,D)=>this.objectOfSourceId(t,$,D),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:($,D)=>this.sayRecordTypeNote(t,$,D),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:($,D)=>this.countWrittenWithoutFields(t,$,D),linkPersonContacts:$=>this.mapContactsOfPersonAccounts(t,$),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:$=>t.maskedSourceFields($),onMaskedLeftOut:($,D)=>this.noteEncryptedLeftOut(t,$,D),businessAccountsAmong:($,D)=>this.takenAsBusinessAccounts(t,$,D),contactOnItsOwn:$=>t.contactsOnTheirOwn.has($),...t.store?{calls:Ps(t.store)}:{}}),S=this.leaveWhatHangsFromThePlatform(t,e,h,S);let Re=s.fieldMappings[e.objectApiName]??{},Ie=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),S,$=>H.has($)||Re[$]!==void 0),Ne=I?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:S,fields:I,written:$=>H.has($)&&!Ie.has($)&&Re[$]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:z!==void 0&&!z.some($=>$.name==="RecordTypeId")}):void 0;for(let $ of Ne?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,$);let he=H.has("RecordTypeId")&&!Ie.has("RecordTypeId")&&Re.RecordTypeId===void 0,Ke=e.objectApiName===Se?await this.takenAsBusinessAccounts(t,S,he):void 0,ve=Po(e.objectApiName)?void 0:await this.currenciesFor(t,z,S,$=>H.has($)&&!Ie.has($)&&Re[$]===void 0),E=ve?void 0:await this.parentCurrenciesFor(t,e.objectApiName,z,S);S=this.pricedInTheirRecordsCurrency(t,e.objectApiName,S);let W=mt(e.objectApiName)?$=>t.prices.convertedInto.get(String($.Id)):void 0,q=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,h,S,$=>H.has($)&&!Ie.has($)&&Re[$]===void 0):void 0,ge=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,S,H.has("OwnerId")&&!Ie.has("OwnerId")&&Re.OwnerId===void 0):void 0,ee=Th({objectApiName:e.objectApiName,records:S,...W?{pricedIn:W}:{},fieldInfos:h,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:$=>xs(t,$),ownerMappings:s.ownerMappings,...de.lookups.size>0?{resolvedLookups:de.lookups}:{},...q&&q.size>0?{targetLacks:q}:{},...ge?{inactiveOwners:ge}:{},...t.sample?{outsideTheSample:($,D)=>this.outsideTheSample(t,$.referenceTo??[],D)||t.heldInTheOrg.has(D)}:s.stream?.everything===!0?{heldByTheRun:$=>t.heldInTheOrg.has($)}:{},excludedFields:Ie,fieldRename:Re,creatableFields:H,updatableFields:P,picklistValuesByField:B,picklistFields:I,recordTypeValues:Ne?.byRecordType,businessAccounts:Ke,contactPoints:t.contactPoints??void 0,decide:($,D)=>s.decisions.applyToRow(e.objectApiName,$,cg(s,D),t.decisionsApplied,je),...ve||E?{currencyFields:Io(z??[])}:{},...ve?{currencies:ve}:{},...E?{parentCurrencies:E}:{}}),te=new Ko,G=new Fo;for(let{picklistChanges:$=[],currencyChange:D,source:me}of ee){te.add(e.objectApiName,$),t.picklistChanges.add(e.objectApiName,$),o?.picklists.add(e.objectApiName,$),G.add(e.objectApiName,D),t.currencyChanges.add(e.objectApiName,D),o?.currencies.add(e.objectApiName,D);let le=me.Id;D&&typeof le=="string"&&t.currencyChangesById.set(le,D)}let Oe=Vo(te.list())+Co(G.list())+Od(eg(new Map,ee))+jd(ng(ee))+kd(Sd(new Map,ee))+Td(Ad(new Map,ee))+(o?"":Id(t,e.objectApiName));o&&(eg(o.lookupsNotCarried,ee),Sd(o.lookupsOutsideTheRun,ee),Ad(o.lookupsHeldBack,ee),o.ownersInactive+=ng(ee)),this.noteLookupsOutsideTheRun(t,e.objectApiName,h,ee),await this.noteLookupsHeldBack(t,e.objectApiName,h,ee);for(let $ of ee)for(let D of $.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,D);zw(t,e.objectApiName,ee);let ye=ee.map($=>$.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ye=t.recordTypeMapper.apply(ye,s.recordTypeMappings,$=>gs(e.objectApiName,$)));let ue=this.applyRecordTypeDecisions(t,e.objectApiName,ee,ye);ye=this.anonymizeRows(t,e.objectApiName,ye,ee.map($=>String($.source.Id??"")),h,s.fieldMappings[e.objectApiName]??{});let Ct=new Map((z??[]).flatMap($=>$.length!==void 0&&$.length>0?[[$.name,$.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let $ of ye)s.decisions.truncate(e.objectApiName,$,Ct,t.decisionsApplied);let lt=new Map;t.gaps&&(lt=await this.findGaps(t,e,{cleanedRecords:ee,recordsToInsert:ye,targetFields:z,targetObject:J,picklistValuesByField:B,picklistFields:I,recordTypes:Ne?.byRecordType,unmapped:ue}));let Tt=e.objectApiName===rr?await this.takeTheSyncCopies(t,ee,ye,k,{fields:z,updatable:P,keyPrefix:J?.keyPrefix}):{taken:0,given:0};e.objectApiName===De&&Ww(t,ee,ye);let yt=e.objectApiName===Ge?await this.linkTheRolesThePlatformWrote(t,ee,ye,{fields:z,updatable:P,keyPrefix:J?.keyPrefix}):{linked:0,given:0},nt=await this.startAsDrafts(t,e.objectApiName,ye),At=new Map;if(t.store)for(let[$,D]of nt){let me=ee[$];me&&At.set(me,D)}let dt=[];if(mt(e.objectApiName)&&t.standardPricebookId){let $=ee.map((le,Ce)=>Ce),{standard:D,custom:me}=_c($.map(le=>({index:le,[tn]:ee[le].source[tn]})),t.standardPricebookId);for(let le of[D,me])le.length!==0&&dt.push({records:le.map(Ce=>ye[Ce.index]),cleaned:le.map(Ce=>ee[Ce.index])})}dt.length===0&&(ye.length>0||Tt.taken===0&&yt.linked===0)&&dt.push({records:ye,cleaned:ee});let Xt=await this.recordTypeCounter(t,e.objectApiName,J,he),ke=Zl();ke.successCount+=Tt.taken;let ft;try{for(let $ of dt){if(t.simulated){this.simulateWrite(t,e,$,J?.keyPrefix,ke,c,Xt,z,lt);continue}await t.batchWriter.writeNode({node:e,records:$.records,cleanedRecords:$.cleaned,fieldInfos:h,creatableFields:H,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:J?.keyPrefix,picklistFields:I,remapper:d,...t.store?{oweLookups:D=>this.oweToTheSecondPass(t,D)}:{},...t.store?{calls:Ps(t.store)}:{},...At.size>0?{onWritten:(D,me)=>{let le=At.get(D);le!==void 0&&(At.delete(D),this.oweStatus(t,e.objectApiName,me,le))}}:{},...Xt?{onCreatedWithoutRecordType:Xt}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(D=>D.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},ke)}}catch($){if(!($ instanceof be))throw $;ft=$}finally{for(let[$,D]of nt){let me=ee[$];if(me&&t.store&&!At.has(me))continue;let le=me?.source.Id;if(typeof le!="string")continue;let Ce=d.get(le);!Ce||d.isExisting(le)||this.oweStatus(t,e.objectApiName,Ce,D)}this.countWrites(t,e.objectApiName,ke)}let _e=ke.successCount,pt=ke.updatedCount,$t=ke.linkedExistingCount,F=ke.failureCount,Y=ke.unidentifiedExistingCount;if(o){let $=dt.reduce((ht,hr)=>ht+hr.records.length,0),D=dt.flatMap(ht=>ht.cleaned);o.sent+=$,o.succeeded+=_e,o.updated+=pt,o.linked+=$t,o.linkedToCreated+=ke.linkedToCreatedCount??0,o.linkedByThePlatform+=ke.writtenByThePlatformCount??0,o.failed+=F,o.alreadyExists+=ke.alreadyExistsCount,o.unidentified+=Y,o.rolesOfTheirOpportunity+=yt.linked,o.rolesGiven+=yt.given,o.writtenWithoutFields=ke.writtenWithoutFields?la(o.writtenWithoutFields,ke.writtenWithoutFields):o.writtenWithoutFields,ke.flagsNotKept&&(o.flagsNotKept=du(o.flagsNotKept,ke.flagsNotKept));let me=ft?$-(_e+pt+$t+F):0,le=D.slice(0,$-me).filter(ht=>R.rows.has(ht.source)).length;o.sentOnTheirOwn+=le,le>0&&(o.onTheirOwnWhy=R.why);let Ce=[...hd(o),...Qt(t,e.objectApiName)];if(ft)throw this.stopStreamedNode(e,t,o,me,f),ft;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${Rd(s,e.objectApiName,o,Ce)}`});return}let ne=_e+pt+$t+k.length+U.linked+de.linked+yt.linked,Ee=ne+F,re=Ee>0?F/Ee:0,oe=F>0&&ke.alreadyExistsCount===F,rt=F>0&&!oe&&(ne===0||re>.5),fe=Rg(s,$t,ke.linkedToCreatedCount??0,{objectApiName:e.objectApiName,rows:ke.writtenByThePlatformCount??0}),qe=pt>0?`, ${pt} updated through their external id`:"",Ve=Y>0?` (${Y} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",bt=$=>[...Uh(v),..._.size>0?[{count:_.size,why:Nd}]:[],...U.notSent,...$?Qt(t,e.objectApiName):[]],Zt=bt(X===0),En=ce>0?`, ${ce} written by the platform with their email`:"",Nt=bg(U.linked,bd(t,e.objectApiName)),Kn=Og(de.owners,de.linked-de.owners)+kg(yt.linked,yt.given),vt=dt.flatMap($=>$.cleaned),Je=$=>vt.slice(0,$).filter(D=>R.rows.has(D.source)).length,en=$=>$>0?`, ${$} ${$===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",Ze=en(Je(vt.length)),_t=k.length>0?`, ${Md(s,k.length)}`:"",Mt=X>0?`, ${Is(X)}`:"",Et=[Li(ke.flagsNotKept),Sg(de.values)].flatMap($=>$?[`, ${$}`]:[]).join(""),Bt=ss(ke.writtenWithoutFields),ot=pg(t,e.objectApiName),Me=Ns(t,e.objectApiName),In=n===void 0?Ch(t,e.objectApiName):"",Vn=s.dryRun?"would be inserted":"succeeded",eo=Tt.taken>0?` (${op(Tt.taken,Tt.given,s.dryRun)})`:"",xn=$=>`${_e} ${Vn}${eo}${qe}${fe}${En}${Nt}${Kn}${_t}, ${F+zn($)} failed${Ve}${cn($)}`,ai=`${Ze}${Mt}${Et}${Oe}${Bt}${ot}${X===0?Me:""}${In}`;if(ft){let $=dt.reduce((Ce,ht)=>Ce+ht.records.length,0),D=$-(_e+pt+$t+F)+X;$d(t,e.objectApiName,D);let me=X>0?` (${Is(X)})`:"",le=Je($-D+X);throw this.saySentOnTheirOwn(t,le,R.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:rt?"error":"stopped",progress:100,message:`${f}: ${xn(bt(!0))}, ${D} not sent${me}${en(le)}${Et}${Oe}${Bt}${ot}${Me}`}),ft}if(this.saySentOnTheirOwn(t,Je(vt.length),R.why),rt){t.failedObjects.add(e.objectApiName),ne>0&&t.failedInPart.add(e.objectApiName);let $=zn(Zt);c({objectName:e.objectApiName,status:"error",progress:100,message:ne===0?`Failed all ${e.objectApiName} records: ${F+$} failed${cn(Zt)}${Ze}${Oe}${In}`:`${F+$}/${Ee+$} ${e.objectApiName} records failed (>50%)${cn(Zt)}${Ze}${Oe}${Bt}${ot}${In}${Hh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: ${xn(Zt)}${ai}`})}catch(j){if(j instanceof be)throw j;t.failedObjects.add(e.objectApiName),t.failedCount+=S.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:S.length,attemptedCount:S.length,samples:[{recordSummary:"(stage failed before insert)",messages:[V(j)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(j)}`})}}};function wy(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function Dd(r,e,t,n){let o=t?.recordTypeMappings,s=Os(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",u=t?.stream,l=wy(e,u?.sample),f=c?{...u,everything:!0,writeWindow:Wd,secondPassPageSize:Wd,ceiling:void 0,wholeReadBound:u?.wholeReadBound??u?.ceiling??fo,...l?{sample:l}:{}}:u,p=[...new Set([...r.nodes.filter(Kc).map(R=>R.objectApiName),...e.excludedObjects??[]])],h=p.length>0?p:void 0,g=e.dryRun===!0?!0:void 0,m=Jo(e),y=e.keepContactPoints===!0?!0:void 0,k=yy(r,e,t?.roots);return k||e.inputMode==="record"&&typeof e.recordId=="string"?{...k?{roots:k}:{rootRecordId:e.recordId},rootObjectApiName:k?.objectApiName??r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:y,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:g,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||h||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||y||i||a||d||f||g||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:y,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:g,decisions:m}:void 0}function yy(r,e,t){let n=e.maxRoots??kr,o=r.nodes.find(a=>a.level===0)??r.nodes[0],s={...t?.plan?{plan:t.plan}:{},...t?.plan&&t.planOfTheRunRetried?{planOfTheRunRetried:!0}:{},...t?.keepAt!==void 0?{keepAt:t.keepAt}:{},...t?.fingerprint!==void 0?{fingerprint:t.fingerprint}:{},...t?.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t?.readTotal!==void 0?{readTotal:t.readTotal}:{}};if(e.inputMode==="record"&&t?.ids!==void 0){let a=o?.objectApiName;return a===void 0?void 0:{objectApiName:a,ids:[...t.ids],cap:n,...s}}if(!Cc(e)||e.inputMode!=="soql")return;let i=vl(e.soqlQuery??"");if("issue"in i)throw Pe.of(Yo(i.issue,o?.objectApiName));return{objectApiName:o?.objectApiName??i.objectApiName,query:i.query,cap:n,...s}}var Jr="--checkpoint-first",_d={switches:[Jr],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},by=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function jg(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
|
|
8
|
-
`)}function Vr(r){process.stderr.write(`${r}
|
|
9
|
-
`),process.exit(2)}function $g(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Jr)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Vr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Jr}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Vr(`${Jr} does not go with ${a}: ${d}`);n.length>1&&Vr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{wa(s,void 0)}catch{Vr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)by.test(a)||Vr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function Ag(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function Ry(r){let e=r.self??sl,t=r.elsewhere??(s=>il(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(Ag(d.targetOrganizationId,s)||Ag(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let u=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!u:t(d))return n}}}function vg(r,e){return{id:e.id,orgType:Gc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function Oy(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function ky(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${yf(t)}`))}}function Eg(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-XMJRXXUN.mjs"),{openCheckpointStore:i}=await import("./chunk-SBDF4AE5.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-NN2IO4WE.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-RTPNK7OB.mjs"),{envLockHolder:c,envLockLine:u}=await import("./chunk-P3OYE2FS.mjs"),l=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in l)throw new Error(Oy(l.refusal));let{store:f}=l,{session:p}=r,h=r.connect(p),g={id:r.org.id,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:h.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:y=>{y.startsWith("[WARN] ")&&r.say(`warning: ${y.slice(7)}`)},orgManager:{getOrg:y=>y===g.id?g:void 0},orgRegistry:{getCredentials:async y=>y===g.id?{accessToken:p.accessToken,instanceUrl:p.instanceUrl}:void 0}};return{deps:{org:s(h),store:f,handler:m,runWriting:Ry({orgName:p.alias,alias:p.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:y=>{let k=c(f.locksDir,y);return k!==void 0?u(k):void 0},...r.own?{own:r.own}:{}}),...r.freeBytes?{freeBytes:r.freeBytes}:{}},org:{orgId:r.org.id,orgName:p.alias,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,registered:{orgType:r.org.orgType,...r.org.edition!==void 0?{metadata:{edition:r.org.edition}}:{}}}}})(),n=o=>({module:r.module,written:o.written,running:o.running,request:r.request,operationId:r.operationId,tool:"cli",keepDays:wa(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-K2WOT75I.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-K2WOT75I.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:ky(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-K2WOT75I.mjs"),{deps:a}=await t(),d=await i.settleBeforeRun(a.store,o,s);return d.notDeleted!==void 0&&r.say(`warning: ${d.notDeleted}`),d.info}}}function qd(r){return fl(r).map(e=>` ${e}`)}var Sy=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function Ws(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=Sy.has(r.code)?"leave an object out of it (--checkpoint-exclude-object <ApiName>), ":"";return`The checkpoint before the run was refused: ${e} Fix what refuses it, ${t}or run without ${Jr} to write without one.`}function Ud(r){return r.code!==Sn?Tf:r.refusal!==void 0?`${Ws(r.refusal)} Nothing was written.`:r.message}function Ty(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function Ig(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${Ty(r.expiresAt)}`,` rewind to it: ${Ut("checkpoint")} rewind --org ${e} --checkpoint ${r.checkpointId}${t?" --mute-automation":""}`,...r.notHeld.map(({objectApiName:n,reason:o})=>` not in the checkpoint: ${n} \u2014 ${o}`)]}function Gd(r){return r.state==="deleted"?[wf]:[]}async function nT(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of Gd(s))o(i);return s}catch(s){return o(`warning: the checkpoint '${e.name}' taken before the run, which wrote nothing, could not be deleted (${s instanceof Error?s.message:String(s)}): delete it with ${Ut("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var Ds="--leave-undeletable",zd="UNDELETABLE_NOT_LEFT";function Ay(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=St(Ds)?`run again with ${Ds}`:`run ${at(Ds,"removal")}`;return{code:zd,message:`The user SandForge connects as may not delete the records of ${t} in ${e}. Nothing was removed. Give that user Delete on those objects, or ${n} to remove the rest and leave them.`}}function xg(r,e,t,n=o=>process.stderr.write(`${o}
|
|
10
|
-
`)){return async o=>{if(!r)return t(Ay(o,e)),!1;let s=o.map(i=>`${i.objectApiName} (${i.records} records)`).join(", ");return n(`The user SandForge connects as may not delete the records of ${s} in ${e}.`),n(`Those stay, with the records they hang from; the rest is removed (${Ds}).`),!0}}function Pg(r,e){let t;return async n=>{let o=await r.describeObject?.(e,n);return!o||!o.recordTypes.some(s=>!s.master)?o?.recordTypes:(t??=r.queryRecords(e,No).then(Mo,()=>[]),Bo(o.recordTypes,await t))}}var fc=`sandforge clone \u2014 Forge a clone of one record, or of whole tables, from a source org
|
|
11
|
-
to a target sandbox, or remove what a run of it created.
|
|
12
|
-
|
|
13
|
-
Usage:
|
|
14
|
-
npx sandforge clone \\
|
|
15
|
-
--record <id> --source <alias> --target <alias> [options]
|
|
16
|
-
npx sandforge clone \\
|
|
17
|
-
--query "<SOQL>" | --record <id> --record <id>... \\
|
|
18
|
-
--source <alias> --target <alias> [--max-roots <n>] [--roots-plan <file>]
|
|
19
|
-
[--max-read-total <n>] [options]
|
|
20
|
-
npx sandforge clone \\
|
|
21
|
-
--object <ApiName> [--where <condition>] [--object <ApiName> [--where <condition>]]... \\
|
|
22
|
-
--source <alias> --target <alias> [options]
|
|
23
|
-
npx sandforge clone \\
|
|
24
|
-
--depth all --source <alias> --target <alias> [--fit share] [--dry-run] [--yes]
|
|
25
|
-
[options]
|
|
26
|
-
npx sandforge clone \\
|
|
27
|
-
--remove <summary.json> --target <alias> [--include-changed] [--accept-automation]
|
|
28
|
-
[--mute-automation] [--leave-undeletable] [--json]
|
|
29
|
-
[--preview] [--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--sweep-user <id>]
|
|
30
|
-
[--audit <file>]
|
|
31
|
-
npx sandforge clone \\
|
|
32
|
-
--verify <summary.json> --target <alias> [--source <alias>] [--json] [--audit <file>]
|
|
33
|
-
|
|
34
|
-
The target must be a sandbox or a Developer Edition org (a Trailhead
|
|
35
|
-
playground is one). Its Organization record says which, and any other
|
|
36
|
-
org, an org whose edition it does not say included, is refused as a
|
|
37
|
-
production org before anything is written or deleted. --dry-run and
|
|
38
|
-
--list-objects only read, and run against any org.
|
|
39
|
-
|
|
40
|
-
Before it reads a row, the clone says what the target runs on the objects
|
|
41
|
-
it writes: its active record-triggered flows, Apex triggers, Process
|
|
42
|
-
Builder processes and workflow rules, per object and write, with what of
|
|
43
|
-
them sends messages (SENDS MESSAGES) or runs after commit; its assignment
|
|
44
|
-
and duplicate rules; and what keeps a flow from starting for the user the
|
|
45
|
-
run writes as, and whether that user holds it (with --json, under
|
|
46
|
-
targetAutomation). When any of them fires as the clone inserts its
|
|
47
|
-
records, or as it updates those it writes a second time \u2014 a lookup
|
|
48
|
-
filled in once its record exists, an order or a contract given back its
|
|
49
|
-
status \u2014 or the target would not say what it runs, nothing is written
|
|
50
|
-
unless --accept-automation is given. A bypass the user does not hold is
|
|
51
|
-
given with the permission set of the target that holds it, which
|
|
52
|
-
--mute-automation assigns for the run alone, under a lease.
|
|
53
|
-
|
|
54
|
-
It then says what the target holds against the rows, read from its
|
|
55
|
-
metadata: its active validation rules and what keeps them quiet, its
|
|
56
|
-
active duplicate rules and whether each blocks an insert or lets it
|
|
57
|
-
through, the fields only the target requires that the clone does not
|
|
58
|
-
write, the lookup filters of the lookups it writes, and the daily API
|
|
59
|
-
requests the target has left against those the run takes (with --json,
|
|
60
|
-
under targetGaps). A gap a decision of --config or --template answers \u2014
|
|
61
|
-
a default given to a field only the target requires \u2014 is said answered
|
|
62
|
-
by it, as Review shows it decided, and no longer BLOCKING (answeredBy,
|
|
63
|
-
with --json). None of it stops the clone. With --dry-run --json,
|
|
64
|
-
adminChanges lists, for whoever administers the target, the changes to its
|
|
65
|
-
metadata that would let the rows go in as they are \u2014 a picklist value to
|
|
66
|
-
add to a record type, a field to lengthen, a rule to turn off \u2014 grouped by
|
|
67
|
-
object and record type, each with its step in Setup; the clone makes none.
|
|
68
|
-
|
|
69
|
-
Once every row is read and before the first is written, the clone counts
|
|
70
|
-
the records it is about to write, per object, and the data storage they
|
|
71
|
-
take by the sizes Salesforce documents, and the daily API requests they
|
|
72
|
-
take, with those of a checkpoint taken first and of the record types read
|
|
73
|
-
back after. It writes nothing past --max-total, nor more than the target's
|
|
74
|
-
data storage or its daily API requests have left. It says the emails the
|
|
75
|
-
target's flows send as the records go in, against the daily limits it has
|
|
76
|
-
left \u2014 a Developer Edition's email alerts counted against its single emails
|
|
77
|
-
too \u2014 and writes nothing past them: a record whose flow fails in the save
|
|
78
|
-
is refused there, and the org's own emails stop for the day. What sends
|
|
79
|
-
and could not be read \u2014 a flow's definition refused or past the read's
|
|
80
|
-
bound, a flow a package installed, which the org lets no one read \u2014 is
|
|
81
|
-
said not counted (with --dry-run --json, under writePlan.emailsUncounted),
|
|
82
|
-
and refuses nothing: --accept-automation already covers it.
|
|
83
|
-
|
|
84
|
-
Required:
|
|
85
|
-
--record <id> Source record ID (any object type \u2014 prefix detected automatically);
|
|
86
|
-
may come from --template instead; --query (below)
|
|
87
|
-
clones the records a query chooses, --object whole
|
|
88
|
-
tables
|
|
89
|
-
--source <alias> sf CLI alias of the source org
|
|
90
|
-
--target <alias> sf CLI alias of the target sandbox
|
|
91
|
-
|
|
92
|
-
Clone records and what each reaches, in place of one --record:
|
|
93
|
-
--query "<SOQL>" the records a query chooses, each cloned with what the
|
|
94
|
-
clone of that record copies: a record they share is
|
|
95
|
-
read and written once, and a record of the query's
|
|
96
|
-
object they name comes as a parent, as a clone of one
|
|
97
|
-
record brings it. The query is SELECT Id FROM <Object>
|
|
98
|
-
[WHERE \u2026] [ORDER BY \u2026] [LIMIT n]; its WHERE chooses
|
|
99
|
-
the records and filters no other read. They are read
|
|
100
|
-
by their ids first, ORDER BY Id unless the query
|
|
101
|
-
orders them: a LIMIT without an order would choose
|
|
102
|
-
other records each time. A GROUP BY, HAVING, OFFSET,
|
|
103
|
-
FOR, WITH, USING SCOPE, UPDATE or an aggregate would
|
|
104
|
-
have the clone read other records than the query
|
|
105
|
-
returns, and is refused (ROOTS_QUERY_REFUSED), exit 2.
|
|
106
|
-
Not with --record, --object, --where, --depth all, or
|
|
107
|
-
--fit and the flags a sample is drawn by.
|
|
108
|
-
--record <id> --record <id>...
|
|
109
|
-
records named one by one, of one object, each cloned
|
|
110
|
-
with what the clone of that record copies
|
|
111
|
-
--max-roots <n> the most records a run takes this way, 1 to 2000
|
|
112
|
-
(default: 200)
|
|
113
|
-
A query that chooses more, without a LIMIT, is refused
|
|
114
|
-
before anything else is read (ROOTS_EXCEEDED), exit 1:
|
|
115
|
-
add ORDER BY CreatedDate DESC, Id DESC LIMIT <n> to
|
|
116
|
-
take the newest, narrow its WHERE, or raise
|
|
117
|
-
--max-roots; past
|
|
118
|
-
2000, copy a sample of the whole org (--depth all
|
|
119
|
-
--fit share) with a filter on its roots. A query that
|
|
120
|
-
chooses none is refused too (NO_ROOTS), exit 1.
|
|
121
|
-
--roots-plan <file> a dry run keeps there the records its query chose, in
|
|
122
|
-
place of what a dry run before it kept; a run given it
|
|
123
|
-
writes those records and no other: one the query
|
|
124
|
-
chooses after the dry run is not written, and one
|
|
125
|
-
deleted since is said gone. A plan of another org,
|
|
126
|
-
another query or records, or whose ids changed, is
|
|
127
|
-
refused (ROOTS_PLAN_MISMATCH), and one that is not
|
|
128
|
-
there (ROOTS_PLAN_GONE), exit 2; a plan a day old or
|
|
129
|
-
more has the query read again, and the run says so.
|
|
130
|
-
Not with --resume: a run taken up writes the records
|
|
131
|
-
its journal names.
|
|
132
|
-
--max-read-total <n> the most records the run reads in all before it
|
|
133
|
-
writes (default: 50000)
|
|
134
|
-
It holds every record it reads until it writes. Past
|
|
135
|
-
it, refused with nothing written
|
|
136
|
-
(READ_BOUND_EXCEEDED), exit 1: fewer records, a
|
|
137
|
-
shallower --depth, --exclude-object, or a higher bound.
|
|
138
|
-
The read of what the records reach is held besides to
|
|
139
|
-
a tenth of the requests the source has left today
|
|
140
|
-
(API_BUDGET_EXCEEDED), exit 1.
|
|
141
|
-
The run says where its records came from, what its
|
|
142
|
-
read came to in records and requests of the source,
|
|
143
|
-
per object how its rows came in \u2014 the records, those
|
|
144
|
-
read under them, those they name \u2014, and the records
|
|
145
|
-
written of those chosen; with --json, under roots,
|
|
146
|
-
reads and each object of readByObject (origin,
|
|
147
|
-
readUnder). --verify says how many of them the target
|
|
148
|
-
holds.
|
|
149
|
-
|
|
150
|
-
Clone whole tables, in place of --record:
|
|
151
|
-
--object <ApiName> a table to clone; repeat for more. The first is where
|
|
152
|
-
discovery starts, and each other must be in its graph
|
|
153
|
-
(--depth, --max-nodes): a parent one of them points at,
|
|
154
|
-
or a child that hangs from one. Every other object
|
|
155
|
-
discovery reaches is left out. A table no clone
|
|
156
|
-
writes \u2014 users and their access, setup, a record's
|
|
157
|
-
history, feed or sharing rows, a file \u2014 is refused
|
|
158
|
-
before a row is read (TABLE_NEVER_CLONED), exit 2.
|
|
159
|
-
--where <condition> the rows of the --object before it: a SOQL condition,
|
|
160
|
-
written without WHERE (default: every row)
|
|
161
|
-
It narrows that table alone: every other --object is
|
|
162
|
-
read whole, whatever rows the first keeps. For records
|
|
163
|
-
with what each of them reaches \u2014 the accounts of an
|
|
164
|
-
industry with their contacts, opportunities and cases
|
|
165
|
-
\u2014 give --query "SELECT Id FROM Account WHERE Industry
|
|
166
|
-
= 'Energy'" instead.
|
|
167
|
-
The run is the panel's run of a query: each table read
|
|
168
|
-
with the org's cursor in the order of its ids and
|
|
169
|
-
written a page at a time, so the run holds a page of
|
|
170
|
-
rows whatever a table holds, and keeps what it wrote in
|
|
171
|
-
its journal as it goes; --resume reads each table after
|
|
172
|
-
the last row the run wrote. Parents go before the tables
|
|
173
|
-
that point at them, their lookups given the records the
|
|
174
|
-
run created. With --upsert, every page of a table goes
|
|
175
|
-
by one external id, the first whose value each row
|
|
176
|
-
the run reads of it holds and no two share. A run that
|
|
177
|
-
copies files (--files) reads each table whole. Not
|
|
178
|
-
with --record, --expand-orphans or --rehearse. With
|
|
179
|
-
--template, the template's choices go with the
|
|
180
|
-
tables, its record or query aside.
|
|
181
|
-
|
|
182
|
-
Clone the whole org, in place of --record:
|
|
183
|
-
--depth all every object of the source the target can take, from
|
|
184
|
-
no record and no table, each read a page at a time in
|
|
185
|
-
the order of its ids and written ten thousand records
|
|
186
|
-
at a time: as a Bulk API job from 2000 of them, by REST
|
|
187
|
-
under that and for an object no job writes (an active
|
|
188
|
-
duplicate rule watches it, the Bulk API refuses it).
|
|
189
|
-
What it leaves out is said with why: setup, metadata,
|
|
190
|
-
what only the platform writes, what the target cannot
|
|
191
|
-
take, an empty table. Past 1950 objects or 20000 pairs
|
|
192
|
-
of related objects, discovery refuses it, never cuts it.
|
|
193
|
-
Its dry run stops at the write gate once the source is
|
|
194
|
-
counted, and reads no row: per object the records it
|
|
195
|
-
would insert and how many go in jobs, the API requests
|
|
196
|
-
of both orgs, the Bulk API batches, the data and file
|
|
197
|
-
storage, what it leaves out and why, the personal
|
|
198
|
-
fields it copies as they are, and each refusal a real
|
|
199
|
-
run would meet, exit 1 when there is one (with --json,
|
|
200
|
-
under wholeOrg and wouldBeRefused).
|
|
201
|
-
A real run asks before its first write, naming the
|
|
202
|
-
records and objects, the requests and batches, the
|
|
203
|
-
objects of managed packages (the mute reaches none of
|
|
204
|
-
what they run), the phone numbers it writes empty and
|
|
205
|
-
the personal fields it copies as they are: --yes writes
|
|
206
|
-
without the question; with no terminal to answer it,
|
|
207
|
-
the run is refused (CONFIRMATION_UNAVAILABLE). It keeps
|
|
208
|
-
its journal, which --resume takes it up from and
|
|
209
|
-
--remove takes it back from, and exits 3 when the
|
|
210
|
-
target refused part of it. --max-total holds it as any
|
|
211
|
-
run: give it what the dry run counted. --exclude-object
|
|
212
|
-
leaves an object out, --filter narrows one; --files,
|
|
213
|
-
off unless given, copies the org's files. Not with
|
|
214
|
-
--record, --object, --where, --template, --custom-depth,
|
|
215
|
-
--max-nodes, --max, --expand-orphans, --rehearse or
|
|
216
|
-
--upsert.
|
|
217
|
-
--no-anonymize with --depth all, copy the personal data as the source
|
|
218
|
-
holds it, a production org's too
|
|
219
|
-
--yes with --depth all, write without the question
|
|
220
|
-
|
|
221
|
-
Copy a sample of the whole org that fits the target, with --depth all:
|
|
222
|
-
--fit share rather than every record, a sample: roots drawn of
|
|
223
|
-
each object, each with its children and the records
|
|
224
|
-
it names, none without a record it cannot be written
|
|
225
|
-
without; the largest share of the roots that fits
|
|
226
|
-
what the target has left \u2014 80 % of the data storage
|
|
227
|
-
its /limits say, half a MB off for their rounding,
|
|
228
|
-
less what its automation still running creates
|
|
229
|
-
under the records \u2014 and --max-total, its default
|
|
230
|
-
of 10000 too: raise it to take more. The reference
|
|
231
|
-
data go whole. Small parents and the price catalog
|
|
232
|
-
go whole while they fit a quarter of the room the
|
|
233
|
-
target has, 80 % of what it has left once half a MB
|
|
234
|
-
is off, whatever --fit-within and --max-total ask;
|
|
235
|
-
a root that would bring in more than a tenth of that
|
|
236
|
-
room by itself is set aside and named (heavy roots
|
|
237
|
-
set aside:). Drawn before the gate, from ids,
|
|
238
|
-
lookups and the few values that decide what it
|
|
239
|
-
keeps \u2014 record types, creation dates \u2014, the plan
|
|
240
|
-
is kept on disk, the ids of each object and no
|
|
241
|
-
value: a dry run's in forge-samples/ under the
|
|
242
|
-
journal directory for a day, a run's beside its
|
|
243
|
-
journal. The gate counts the plan, and the run
|
|
244
|
-
writes its records and no other: a lookup to a
|
|
245
|
-
record outside it is written empty and said, a
|
|
246
|
-
record gone from the source since is said apart,
|
|
247
|
-
one whose parent changed since is held back and
|
|
248
|
-
failed. The dry run says the sample
|
|
249
|
-
(sample:), per object what it keeps and how, what
|
|
250
|
-
goes whole (whole:), the roots set aside (heavy
|
|
251
|
-
roots set aside:), what it leaves out and why (not
|
|
252
|
-
in the sample:), the lookups left empty (left
|
|
253
|
-
empty:) and its plan (sample plan: <folder>); with
|
|
254
|
-
--json under wholeOrg.sample, a run's under sample,
|
|
255
|
-
and what it wrote of the plan under result.sample.
|
|
256
|
-
Not with --files or --list-objects.
|
|
257
|
-
--fit-within <MB> take no more than this many MB of the target
|
|
258
|
-
--fit-seed <n> the seed the roots are drawn by (default: 1)
|
|
259
|
-
The same seed and setup draw the same records.
|
|
260
|
-
--fit-draw uniform|recent|oldest
|
|
261
|
-
uniform spreads the roots over each object, reading
|
|
262
|
-
the id of every root; recent takes the newest and
|
|
263
|
-
oldest the oldest by creation date, reading only
|
|
264
|
-
those it keeps (default: uniform)
|
|
265
|
-
--fit-window created|modified:<from>..<to> | created|modified:<n>d
|
|
266
|
-
draw only the roots made (or last modified) in the
|
|
267
|
-
window, UTC: a date alone starts at 00:00Z and, as
|
|
268
|
-
the end, takes the whole day; either end may be left
|
|
269
|
-
out; <n>d is the last n days, fixed when the sample
|
|
270
|
-
is drawn. The records under or above a root come
|
|
271
|
-
whatever their date.
|
|
272
|
-
--fit-where <Object>=<WHERE>
|
|
273
|
-
draw the roots of Object only among the records
|
|
274
|
-
that match (repeatable, one per object). Unlike
|
|
275
|
-
--filter, the records under or above the roots come
|
|
276
|
-
whatever it says, and no lookup is written empty for
|
|
277
|
-
it.
|
|
278
|
-
--fit-strata <Field>|<Object>.<Field>
|
|
279
|
-
keep the same share of the roots of each value of a
|
|
280
|
-
picklist, checkbox or lookup (RecordTypeId, OwnerId),
|
|
281
|
-
at least --fit-floor of each value (repeatable; Field
|
|
282
|
-
alone: every object that has it)
|
|
283
|
-
A draw told which roots to take names them under
|
|
284
|
-
its sample: line \u2014 roots:, per object the roots in
|
|
285
|
-
the draw of those of the source; strata:, the roots
|
|
286
|
-
and those kept of each value \u2014 and its share is of
|
|
287
|
-
the roots in the draw: all of them taken, it is
|
|
288
|
-
limited by the draw; widen them to take more.
|
|
289
|
-
Refused before any id is read, nothing written,
|
|
290
|
-
every problem named with its way out, exit 2: a
|
|
291
|
-
field that cannot stratify the roots, a condition
|
|
292
|
-
the source refuses, an object with no root of its
|
|
293
|
-
own or copied whole, more than two semi-joins with
|
|
294
|
-
its --filter (SAMPLE_DRAW_INVALID); exit 1, only
|
|
295
|
-
the counts read: no root left in the draw
|
|
296
|
-
(SAMPLE_DRAW_EMPTY).
|
|
297
|
-
--fit-parents all|required
|
|
298
|
-
all copies a record outside the sample that an
|
|
299
|
-
optional lookup names, without its children;
|
|
300
|
-
required writes such a lookup empty (default: all)
|
|
301
|
-
--fit-children <n>|all most children a record brings through each relation,
|
|
302
|
-
the newest; a master record brings every detail
|
|
303
|
-
(default: 100)
|
|
304
|
-
--fit-whole <Object> copy this object whole (repeatable)
|
|
305
|
-
--fit-floor <n> roots kept of each object whatever the share
|
|
306
|
-
(default: 1)
|
|
307
|
-
--fit-plan <folder> write the records of the plan a dry run drew, as its
|
|
308
|
-
line sample plan: printed it, within a day: refused
|
|
309
|
-
when drawn of another org or with other flags, or
|
|
310
|
-
changed since (SAMPLE_PLAN_MISMATCH), or not there
|
|
311
|
-
(SAMPLE_PLAN_GONE), exit 2. The run moves it beside
|
|
312
|
-
its journal; one that writes nothing puts it back.
|
|
313
|
-
Not with --resume, which writes the plan its journal
|
|
314
|
-
names: gone, SAMPLE_PLAN_GONE, exit 2.
|
|
315
|
-
Refused, exit 1: a target that would not say its
|
|
316
|
-
storage, with neither --fit-within nor --max-total
|
|
317
|
-
(SAMPLE_STORAGE_UNREAD); the objects copied whole
|
|
318
|
-
and the floors alone past what it may take, the
|
|
319
|
-
heaviest named (SAMPLE_CANNOT_FIT; with --json,
|
|
320
|
-
refused.sample names what held it, limitedBy, and
|
|
321
|
-
of a bound in MB the needMB and budgetMB); more
|
|
322
|
-
than a million records to hold (SAMPLE_TOO_LARGE); the
|
|
323
|
-
roots' ids past a tenth of the source's requests
|
|
324
|
-
left today (API_BUDGET_EXCEEDED); a target that has
|
|
325
|
-
less room than the plan was fitted to: simulate
|
|
326
|
-
again (STORAGE_EXCEEDED).
|
|
327
|
-
|
|
328
|
-
Options:
|
|
329
|
-
--depth <mode> direct | full | custom | all (default: custom)
|
|
330
|
-
--custom-depth <n> traversal depth when --depth is custom (default: 5)
|
|
331
|
-
--max <n> max records cloned per object (default: unlimited)
|
|
332
|
-
--list-objects print the objects discovery reached, then stop
|
|
333
|
-
Answers "why was my object not cloned?" \u2014 an object
|
|
334
|
-
absent from this list was never in the graph. With
|
|
335
|
-
--json, stdout carries them as JSON: each object's
|
|
336
|
-
record count, depth and whether it is included, and
|
|
337
|
-
whether the graph was truncated.
|
|
338
|
-
--max-nodes <n> objects discovery may reach (default: 50)
|
|
339
|
-
Raise it when the summary says TRUNCATED and an
|
|
340
|
-
object you expected is missing, e.g. the lines of an
|
|
341
|
-
Opportunity's quotes. The prices, products, price
|
|
342
|
-
books and selling models the lines use come whatever
|
|
343
|
-
the cap, as do the items of an activated order and
|
|
344
|
-
the schedules of an opportunity's products. Each
|
|
345
|
-
parent a record reached cannot be written without
|
|
346
|
-
takes the cap one object further, up to twice it.
|
|
347
|
-
An empty table takes no place under it, and nothing
|
|
348
|
-
is reached through it; discovery reads four times
|
|
349
|
-
the cap in objects at most.
|
|
350
|
-
--anonymize anonymize PII fields (default: off)
|
|
351
|
-
With --depth all, on unless --no-anonymize when the
|
|
352
|
-
source's Organization record says a production org.
|
|
353
|
-
--keep-contact-points write emails and phone numbers as read (default: off)
|
|
354
|
-
Off, every record is written with its email addresses
|
|
355
|
-
under .invalid and its phone numbers in a fictional
|
|
356
|
-
range, anonymized or not, so what the target's flows
|
|
357
|
-
and email alerts send to them reaches no one. On,
|
|
358
|
-
they may reach the real people the records name.
|
|
359
|
-
--dry-run skip writes, surface scoped queries (default: off)
|
|
360
|
-
It reads the automation and counts the records as a
|
|
361
|
-
real run does, and says what would stop that run,
|
|
362
|
-
each under the code that run is refused with: a real
|
|
363
|
-
run would be refused (CODE): ... With --json, under
|
|
364
|
-
wouldBeRefused, and the codes under wouldBeRefusedCodes.
|
|
365
|
-
--rehearse have the target judge the rows, keep none (default: off)
|
|
366
|
-
Reads and prepares every row as a real run would,
|
|
367
|
-
then creates a sample of them in the target \u2014 every
|
|
368
|
-
row up to 200, one per object, record type and set of
|
|
369
|
-
fields given a value past it, with the records they
|
|
370
|
-
name \u2014 in composite calls that each fail on purpose,
|
|
371
|
-
so that every write is rolled back. Prints each
|
|
372
|
-
refusal (status code, field, rows) and what could not
|
|
373
|
-
be judged (with --json, under rehearsal). The target's
|
|
374
|
-
automation runs inside each call: emails, @future and
|
|
375
|
-
Queueable jobs, platform events published after
|
|
376
|
-
commit and the asynchronous paths of Flows never
|
|
377
|
-
leave it; platform events published immediately and
|
|
378
|
-
callouts do. Refused against a production org, and,
|
|
379
|
-
like a real run, without --accept-automation when the
|
|
380
|
-
target runs automation on insert. Not with --dry-run,
|
|
381
|
-
--upsert, --files, --remap-csv or --list-objects.
|
|
382
|
-
--accept-automation write although the target runs flows or Apex
|
|
383
|
-
triggers as the clone inserts, or as it updates the
|
|
384
|
-
records it inserted, or could not say what it runs
|
|
385
|
-
(default: off)
|
|
386
|
-
--accept-emails write although the target delivers every email of
|
|
387
|
-
what still runs as the clone writes, or would not say
|
|
388
|
-
whether it does; --accept-automation never stands for
|
|
389
|
-
it. Asked only when what still runs sends one: flows,
|
|
390
|
-
processes and workflow rules with an email action,
|
|
391
|
-
those whose definition was not read, and the
|
|
392
|
-
assignment rules --apply-assignment-rules applies,
|
|
393
|
-
whatever --mute-automation leaves. Whether the org
|
|
394
|
-
delivers them is read with one line of anonymous Apex
|
|
395
|
-
that sends nothing,
|
|
396
|
-
Messaging.reserveSingleEmailCapacity(1), as the user
|
|
397
|
-
the run writes as, never in a production org; on
|
|
398
|
-
System email only or No access, none of them goes
|
|
399
|
-
out, the org still counts them against its daily
|
|
400
|
-
limits, and nothing is asked. What an Apex trigger
|
|
401
|
-
sends is read nowhere (default: off)
|
|
402
|
-
--mute-automation mute the target's automation for the run through its
|
|
403
|
-
own bypass: assign the user the run writes as, for the
|
|
404
|
-
run alone, the permission sets holding the custom
|
|
405
|
-
permissions its flows, processes and workflow rules
|
|
406
|
-
test to stay quiet, and take them back as it ends.
|
|
407
|
-
What no bypass keeps quiet (an Apex trigger, a managed
|
|
408
|
-
package's flow) still runs, and still needs
|
|
409
|
-
--accept-automation. Refused on a production org and
|
|
410
|
-
for a user who cannot assign permission sets, exit 1;
|
|
411
|
-
a dry run says what would be muted and assigns nothing
|
|
412
|
-
(default: off)
|
|
413
|
-
${jg({run:"the run",simulation:"--dry-run"})}
|
|
414
|
-
--max-total <n> most records the run may write in all (default: 10000)
|
|
415
|
-
Counted once every row is read: past it, nothing is
|
|
416
|
-
written. --max caps each object, this the whole run.
|
|
417
|
-
--max-records-per-object <n>
|
|
418
|
-
most records one read of an object takes
|
|
419
|
-
(default: 50000)
|
|
420
|
-
An object with more is read to it and said
|
|
421
|
-
TRUNCATED. A clone of a record holds what it reads,
|
|
422
|
-
so a higher number takes more memory; 1000000 at most.
|
|
423
|
-
--upsert use external Id upsert when available (default: insert)
|
|
424
|
-
Skips DUPLICATE_VALUE on re-runs of the same source records.
|
|
425
|
-
--expand-orphans single-hop expand orphan parent FKs (default: off)
|
|
426
|
-
Clones missing parents (out-of-graph) so child FKs resolve.
|
|
427
|
-
--max-orphans <n> with --expand-orphans, most parents from outside the
|
|
428
|
-
run it copies, 1 to 1000 (default: 20)
|
|
429
|
-
Past it, the rows that cannot be written without one
|
|
430
|
-
are refused, and the summary says how many parents
|
|
431
|
-
were left and of which objects.
|
|
432
|
-
--apply-assignment-rules
|
|
433
|
-
apply the target's assignment rules (default: off)
|
|
434
|
-
Off, every write says Sforce-Auto-Assign: FALSE and
|
|
435
|
-
keeps the owner the run sets. On, the target's active
|
|
436
|
-
assignment rules may give the Cases, Leads and
|
|
437
|
-
Accounts the run writes another owner, and mail them.
|
|
438
|
-
--skip-preflight skip pre-execute target row count (default: off)
|
|
439
|
-
The preflight queries each object on target so the user
|
|
440
|
-
can see existing volume before pressing through.
|
|
441
|
-
--json emit JSON summary on stdout (CI mode) (default: off)
|
|
442
|
-
stdout then carries the JSON alone, and every other
|
|
443
|
-
line goes to stderr. Saved to a file, the summary is
|
|
444
|
-
what --remove takes the run back from. With
|
|
445
|
-
--list-objects, the JSON is the objects of the graph.
|
|
446
|
-
A run refused before its first write prints
|
|
447
|
-
"refused": {"code", "message"} instead, the code its
|
|
448
|
-
line names: refused (MAX_TOTAL_EXCEEDED): ..., each
|
|
449
|
-
other reason under "alsoRefused", on a line of its own.
|
|
450
|
-
How a run ended is under result.status: success,
|
|
451
|
-
partial or failure, as its status: line says it.
|
|
452
|
-
--fail-on-partial exit 3, not 0, when the run wrote some records and
|
|
453
|
-
the target refused others (default: off)
|
|
454
|
-
--summary <file> write the summary to <file> as the run goes
|
|
455
|
-
The JSON --json prints, written after each object
|
|
456
|
-
with what the run has created so far ("running":
|
|
457
|
-
true), then whole once it ends. Ctrl-C stops the run
|
|
458
|
-
between two calls to the org and writes what it had
|
|
459
|
-
created by then ("interrupted": true), as --json then
|
|
460
|
-
prints it: --remove takes the run back from either.
|
|
461
|
-
A file already there is not overwritten. Not with
|
|
462
|
-
--list-objects or --rehearse.
|
|
463
|
-
--resume <journal|id> take up where it stopped a run that did not end \u2014 a
|
|
464
|
-
Ctrl-C, a failure, a process killed \u2014 from its journal:
|
|
465
|
-
its file, or its run id in the journal directory. Each
|
|
466
|
-
record that run wrote is linked to and never written
|
|
467
|
-
again, the lookups and statuses it still owed are
|
|
468
|
-
given, and the rest is written. The same record, orgs,
|
|
469
|
-
depth, choices and flags as the run it takes up, or it
|
|
470
|
-
is refused; a run that ended is refused too. Every run
|
|
471
|
-
that writes keeps its journal there (see
|
|
472
|
-
SANDFORGE_JOURNAL_DIR), and says where as it starts.
|
|
473
|
-
The calls the run had under way when it stopped are
|
|
474
|
-
looked for in the target first: a row found there is
|
|
475
|
-
kept as written by the run, never sent again; one the
|
|
476
|
-
target may hold already stops the resume before it
|
|
477
|
-
writes (see --write-uncertain).
|
|
478
|
-
Not with --dry-run, --rehearse or --list-objects.
|
|
479
|
-
--write-uncertain with --resume: write all the same the rows of a call
|
|
480
|
-
under way when the run stopped that the target may
|
|
481
|
-
already hold, records the resume cannot tell from
|
|
482
|
-
them being there \u2014 each may then be there twice.
|
|
483
|
-
--exclude <obj.field> skip a field on an object during clone (repeatable)
|
|
484
|
-
e.g. --exclude Account.Description --exclude Account.NumberOfEmployees
|
|
485
|
-
Matched whatever its case. One that names no object
|
|
486
|
-
or field of the source refuses the run before a row
|
|
487
|
-
is read, exit 2, naming the field nearest it
|
|
488
|
-
(FIELD_EXCLUSION_UNMATCHED); a dry run says it, as
|
|
489
|
-
the summary's result.fieldExclusionsUnmatched does.
|
|
490
|
-
--exclude-object <obj> leave an object out of the clone (repeatable)
|
|
491
|
-
e.g. --exclude-object PricebookEntry
|
|
492
|
-
Out whether discovery reaches it or the run would
|
|
493
|
-
add it past the cap. What it costs is said, not
|
|
494
|
-
written: the records that cannot be written without
|
|
495
|
-
one of its records, and the orders left drafts.
|
|
496
|
-
--owner-map <src=tgt> remap OwnerId from source User Id to target User Id (repeatable)
|
|
497
|
-
e.g. --owner-map 005AB...=005XY...
|
|
498
|
-
Useful when source records were authored by users
|
|
499
|
-
that don't exist on the target sandbox (ex-employees).
|
|
500
|
-
A target user the target holds inactive is refused
|
|
501
|
-
before anything is read (OWNER_MAP_INACTIVE), and
|
|
502
|
-
one it holds no user of (OWNER_MAP_UNKNOWN).
|
|
503
|
-
--filter <obj=where> per-object SOQL WHERE filter (repeatable)
|
|
504
|
-
e.g. --filter "Case=Status = 'Open' AND CreatedDate > LAST_N_DAYS:30"
|
|
505
|
-
Lets BAs narrow a clone to a subset without changing
|
|
506
|
-
graph topology. Filter is appended via AND (...) to
|
|
507
|
-
the scope-derived clause. Max 512 chars per filter,
|
|
508
|
-
max 50 filters total.
|
|
509
|
-
--map <obj.src=tgt> per-object source\u2192target field rename (repeatable)
|
|
510
|
-
e.g. --map Account.Region__c=Region__pc
|
|
511
|
-
Handles schema drift between source and target
|
|
512
|
-
(managed-package re-key, namespace change). The
|
|
513
|
-
source field is dropped and the value written to
|
|
514
|
-
the target field name on insert.
|
|
515
|
-
--config <file.json> the run's choices from a JSON file: the decisions
|
|
516
|
-
taken in Review's Gaps row (picklistValueMappings,
|
|
517
|
-
recordTypeMappings, defaultValues, truncateFields,
|
|
518
|
-
skippedRows, ignoredGaps), the fields and objects
|
|
519
|
-
left out (fieldExclusions, excludedObjects), the
|
|
520
|
-
filters (objectSoqlFilters) and the mappings
|
|
521
|
-
(ownerMappings, fieldMappings), as a Forge config
|
|
522
|
-
names them. Checked as the panel checks a run's
|
|
523
|
-
config; any other key is refused. The flags above
|
|
524
|
-
win over the file: their exclusions are added, their
|
|
525
|
-
filters and mappings replace the file's for the same
|
|
526
|
-
object, user or field.
|
|
527
|
-
--template <file.json> a template the Template tab exported: its decisions,
|
|
528
|
-
exclusions, filters and mappings, as --config takes
|
|
529
|
-
them, and its depth, caps, anonymization, contact
|
|
530
|
-
points and orphan parents, each unless its flag is
|
|
531
|
-
given. Its record is cloned when --record is not
|
|
532
|
-
given; a template of a query needs --record, or
|
|
533
|
-
--object. Not with --config.
|
|
534
|
-
--remap-csv <file> write the source\u2192target ID remap table to a CSV
|
|
535
|
-
file (header: sourceId,targetId). BA reconciliation:
|
|
536
|
-
"where did source X go on the target sandbox?"
|
|
537
|
-
--files copy the files of the cloned records (default: off)
|
|
538
|
-
Salesforce Files (the latest version of each) and
|
|
539
|
-
attachments, after the records they hang on. The
|
|
540
|
-
total is checked against the target's file storage
|
|
541
|
-
before anything is written: past it, refused
|
|
542
|
-
(FILE_STORAGE_EXCEEDED), as when that storage could
|
|
543
|
-
not be read (FILE_STORAGE_UNREAD) or the files not
|
|
544
|
-
all looked up (FILES_UNREAD).
|
|
545
|
-
--max-file-size <MB> largest file --files copies, 1 to 35 (default: 10)
|
|
546
|
-
A larger file is left out and listed, never cut.
|
|
547
|
-
--files-as-is accept that files are copied as they are: their
|
|
548
|
-
content cannot be anonymized. Required with --files
|
|
549
|
-
when --anonymize is on.
|
|
550
|
-
--audit <file> record the run in an audit trail kept in <file>
|
|
551
|
-
The entry the panel keeps in Reports -> Audit trail:
|
|
552
|
-
per object the records created, updated and lost,
|
|
553
|
-
the orgs, the outcome, the user as a hash of the
|
|
554
|
-
username, and, for a run refused before it wrote,
|
|
555
|
-
the code of what refused it. Counts only, never a
|
|
556
|
-
value of a record. Each run adds its entry to the
|
|
557
|
-
file; a dry run, --list-objects and --rehearse write
|
|
558
|
-
nothing, and add none.
|
|
559
|
-
-h, --help show this help and exit
|
|
560
|
-
|
|
561
|
-
Remove what a run created:
|
|
562
|
-
--remove <file> the summary a run printed with --json, saved to a file,
|
|
563
|
-
or the journal of a run: every part of it, the run it
|
|
564
|
-
took up and each time it was taken up
|
|
565
|
-
Deletes from --target the records that run created,
|
|
566
|
-
as the wizard removes a run from History: children
|
|
567
|
-
first, never a record the target already held, and a
|
|
568
|
-
record kept while records that stay depend on it. The
|
|
569
|
-
target must be the org the run wrote to. A dry run's
|
|
570
|
-
summary is refused: it created nothing. So is a run
|
|
571
|
-
that still writes its journal, from a terminal or
|
|
572
|
-
from VS Code, and the preview of its removal
|
|
573
|
-
(RUN_WRITING), the run named: stop it, or let it end.
|
|
574
|
-
The removal holds the journal while it deletes: a
|
|
575
|
-
--resume of it meanwhile is refused (RUN_WRITING).
|
|
576
|
-
What a removal wrote to the records it left is kept
|
|
577
|
-
beside the summary, clone-summary.removals.json for
|
|
578
|
-
clone-summary.json, and the next --remove of that
|
|
579
|
-
summary reads it: what a removal wrote is no change
|
|
580
|
-
since the run. Keep that file with the summary.
|
|
581
|
-
A summary of a run past 50 000 records keeps their ids
|
|
582
|
-
in its journal, which the removal reads them from.
|
|
583
|
-
Of a run stopped and taken up with --resume, one
|
|
584
|
-
summary per part, it is kept beside the journal too:
|
|
585
|
-
the removal of any part, or of the journal, reads what
|
|
586
|
-
the others wrote, and once a part's own records are
|
|
587
|
-
gone, takes what an earlier removal of another part
|
|
588
|
-
left. What the run wrote to a record of another part
|
|
589
|
-
is no change since the run. The journal's removal
|
|
590
|
-
takes the parts the last first, each read against
|
|
591
|
-
its own span: what someone changed, or made, between
|
|
592
|
-
two parts stays.
|
|
593
|
-
--include-changed remove also the records changed since the run, and
|
|
594
|
-
what was added to them since (default: kept)
|
|
595
|
-
--accept-automation delete although the target runs flows, Apex triggers,
|
|
596
|
-
processes or workflow rules as the records go, those
|
|
597
|
-
--sweep deletes included \u2014 before or after a delete,
|
|
598
|
-
or as an activated order is set back to Draft for
|
|
599
|
-
its delete \u2014 or could not say what it runs
|
|
600
|
-
(default: off)
|
|
601
|
-
--mute-automation mute the target's automation for the removal through
|
|
602
|
-
its own bypass, as for a run: the permission sets
|
|
603
|
-
holding the bypasses of what fires as the records go,
|
|
604
|
-
those --sweep deletes included, assigned to the user
|
|
605
|
-
it deletes as, for the removal alone, and taken back
|
|
606
|
-
as it ends; what no bypass keeps quiet still needs
|
|
607
|
-
--accept-automation (default: off)
|
|
608
|
-
--leave-undeletable remove the rest when the user the removal runs as
|
|
609
|
-
may not delete the records of some objects of the
|
|
610
|
-
run, leaving those with what they hang from; without
|
|
611
|
-
it the removal stops before its first delete and
|
|
612
|
-
names them (default: off)
|
|
613
|
-
--preview say what the removal would do, and do nothing: per
|
|
614
|
-
object the records it would delete, those gone
|
|
615
|
-
already, those changed since the run and who changed
|
|
616
|
-
them, those it could not see, and what a removal run
|
|
617
|
-
now would be refused for, each under the code it is
|
|
618
|
-
refused with: a removal would be refused (CODE): ...,
|
|
619
|
-
with --json the codes under "refusalCodes", in the
|
|
620
|
-
order of "refusals". It reads the records, as
|
|
621
|
-
the removal reads them before its first delete, and
|
|
622
|
-
writes nothing: not to the org, not beside the
|
|
623
|
-
summary. With --sweep, it lists what the sweep would
|
|
624
|
-
take, and reads what fires on it with the run's own.
|
|
625
|
-
Not with --sweep-list or --audit.
|
|
626
|
-
A removal takes no --dry-run: one that did not read
|
|
627
|
-
it would delete for real.
|
|
628
|
-
--sweep before the run's records go, delete too what the
|
|
629
|
-
target's automation made for the run, that the run's
|
|
630
|
-
id map does not hold: what the run's user created
|
|
631
|
-
under the run's records, what they point at, or what
|
|
632
|
-
hangs from those, three links at most, at most a
|
|
633
|
-
minute after the record it is tied to \u2014 in the
|
|
634
|
-
objects the run wrote and their children, tasks,
|
|
635
|
-
events, feed, email messages, notes, case comments,
|
|
636
|
-
and the objects the target's flows create. What a
|
|
637
|
-
record of the run points at by a lookup the org
|
|
638
|
-
refuses the delete for (an asset its case names)
|
|
639
|
-
goes once that record is gone. Listed and kept: what
|
|
640
|
-
is tied to the run but came later, up to 15 minutes,
|
|
641
|
-
or as the org's Automated Process user; and what the
|
|
642
|
-
run's user created in the run's window, a second
|
|
643
|
-
before its first write to a minute after its last,
|
|
644
|
-
tied to nothing of it.
|
|
645
|
-
What anyone changed more than 2 s after the run's
|
|
646
|
-
last write, and after its own creation, stays \u2014 the
|
|
647
|
-
run's user and its automation too \u2014 unless
|
|
648
|
-
--include-changed, and the sweep then ends partial,
|
|
649
|
-
exit 3; a change made before the run's last write
|
|
650
|
-
reads as unchanged. Runs alone when an earlier
|
|
651
|
-
--remove took every record of the run. Of a clone of
|
|
652
|
-
the whole org, the removal says the sweep is off
|
|
653
|
-
unless given: the run's window spans hours, and a
|
|
654
|
-
sweep looks at 300 objects at most
|
|
655
|
-
(default: off)
|
|
656
|
-
--sweep-late with --sweep, take too what it lists as made late;
|
|
657
|
-
with --sweep-list, say what it would take
|
|
658
|
-
--sweep-untied with --sweep, take too what it lists as tied to
|
|
659
|
-
nothing of the run; with --sweep-list, say what it
|
|
660
|
-
would take; refused when another run of this
|
|
661
|
-
machine wrote to the target in the run's window, or
|
|
662
|
-
when that user created records there on objects
|
|
663
|
-
neither the run nor the automation reaches (hand
|
|
664
|
-
work, likely)
|
|
665
|
-
--sweep-user <id> with --sweep or --sweep-list, the user the run wrote as,
|
|
666
|
-
for a run whose summary does not keep it: the sweep
|
|
667
|
-
reads it otherwise from the run's records, and is
|
|
668
|
-
refused when none is left or several users made them
|
|
669
|
-
--sweep-list list what --sweep would delete, per object with a few
|
|
670
|
-
names and how many it ties to the run, and delete
|
|
671
|
-
nothing, the run's records included; exit 3, as a
|
|
672
|
-
refused --sweep, when it says the sweep is refused
|
|
673
|
-
What a sweep leaves, and why: what another user
|
|
674
|
-
created, a colleague's or an integration's; what is
|
|
675
|
-
tied to nothing, unless --sweep-untied; what came
|
|
676
|
-
more than 15 minutes after its record, or after the
|
|
677
|
-
removal began, which cannot be told from work done
|
|
678
|
-
by hand; what anyone changed after the run's last
|
|
679
|
-
write, the run's own user included, unless
|
|
680
|
-
--include-changed; what the
|
|
681
|
-
automation changed or deleted rather than created,
|
|
682
|
-
which a checkpoint taken before the run takes back;
|
|
683
|
-
what left the org (emails, outbound messages); more
|
|
684
|
-
than 10 000 records of one object; and what the
|
|
685
|
-
panel, another machine or a CI wrote meanwhile, which
|
|
686
|
-
a sweep does not see
|
|
687
|
-
--json print what became of the records as JSON on stdout,
|
|
688
|
-
every other line on stderr; refused before its first
|
|
689
|
-
delete, "refused": {"code", "message"}, the code its
|
|
690
|
-
line names: refused (CODE): ... \u2014 a production org
|
|
691
|
-
(PRODUCTION_TARGET), what fires as it deletes
|
|
692
|
-
(AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
|
|
693
|
-
MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
|
|
694
|
-
delete (UNDELETABLE_NOT_LEFT), an org that is not the
|
|
695
|
-
one the run wrote to (OTHER_ORG, its --preview too)
|
|
696
|
-
--audit <file> record the removal, and the sweep, in the audit trail
|
|
697
|
-
kept in <file>
|
|
698
|
-
|
|
699
|
-
Verify what a run created:
|
|
700
|
-
--verify <file> the summary a run printed with --json, saved to a file,
|
|
701
|
-
or the journal of a run, every part of it
|
|
702
|
-
Reads back from --target every record the run created,
|
|
703
|
-
after a pause and again until two readings agree (three
|
|
704
|
-
at most, two seconds apart): those there, those in the
|
|
705
|
-
recycle bin, those neither, out of the user's sight;
|
|
706
|
-
checks on twenty records of each object that the
|
|
707
|
-
lookups the run set point at the ids their parents got,
|
|
708
|
-
reading the source records in --source; and lists the
|
|
709
|
-
records changed since the run, which --remove keeps
|
|
710
|
-
unless --include-changed. Only reads, from either org.
|
|
711
|
-
Exits 0 when VERIFIED, 3 when PARTIAL (a record not
|
|
712
|
-
there, a lookup that does not hold, or a part that could
|
|
713
|
-
not be checked) and 4 when UNSTABLE (no two readings
|
|
714
|
-
agreed: something still writes to the records).
|
|
715
|
-
--source <alias> the org the run read from (default: the summary's)
|
|
716
|
-
A lookup the clone left out with --exclude reads as
|
|
717
|
-
one left empty.
|
|
718
|
-
--json print the verification as JSON on stdout, every other
|
|
719
|
-
line on stderr; refused for an org that is not the
|
|
720
|
-
one the run wrote to, exit 1, "refused": {"code",
|
|
721
|
-
"message"}, the code its line names: refused
|
|
722
|
-
(OTHER_ORG): ...
|
|
723
|
-
--audit <file> record the verification in the audit trail kept in
|
|
724
|
-
<file>
|
|
725
|
-
|
|
726
|
-
Environment:
|
|
727
|
-
SANDFORGE_FORGE_PAGE_SIZE=<n>
|
|
728
|
-
a diagnostic: read every statement through the org's
|
|
729
|
-
cursor and hand it on in pages of <n> rows, as a run of
|
|
730
|
-
whole tables reads, to see a clone's paged read against
|
|
731
|
-
a real org. Not a setting: an org answers in pages of
|
|
732
|
-
200 to 2000 rows, and a page of <n> is cut from them.
|
|
733
|
-
SANDFORGE_JOURNAL_DIR=<dir>
|
|
734
|
-
where every run that writes keeps its journal, in
|
|
735
|
-
<dir>/forge-runs/ (default: ~/.sandforge)
|
|
736
|
-
What the run wrote, read and still owes, line by line
|
|
737
|
-
as it goes, ids only: what --resume takes a run up
|
|
738
|
-
from, and what --remove takes it back from however it
|
|
739
|
-
ended.
|
|
740
|
-
|
|
741
|
-
Exit codes:
|
|
742
|
-
0 the clone ran, a run the target refused some records of too unless
|
|
743
|
-
--fail-on-partial; the rehearsal ran, whatever it found refused; the removal
|
|
744
|
-
took every record it set out to take; the preview said what a removal
|
|
745
|
-
would do, refusals included
|
|
746
|
-
1 the clone or the removal could not run; the clone produced only failures,
|
|
747
|
-
or its files were refused; --resume could not take the run up
|
|
748
|
-
(RESUME_UNAVAILABLE, RESUME_TARGET_CHANGED, RESUME_CHANGED,
|
|
749
|
-
RESUME_UNCERTAIN); the target is a production org; the target
|
|
750
|
-
runs automation on insert or on the updates the clone makes after its
|
|
751
|
-
inserts, or the removal's deletes fire automation, and
|
|
752
|
-
--accept-automation was not given; the target delivers the emails of
|
|
753
|
-
what still runs, or would not say whether it does, and --accept-emails
|
|
754
|
-
was not given (EMAILS_NOT_ACCEPTED); the checkpoint asked first was
|
|
755
|
-
refused or could not be taken (CHECKPOINT_REFUSED); the run would write
|
|
756
|
-
more than --max-total records, more than the target's data storage
|
|
757
|
-
has left or more emails than it has left today, or would take more API
|
|
758
|
-
requests than it has left today (nothing is written or deleted then);
|
|
759
|
-
a clone of the whole org nobody answered the question of
|
|
760
|
-
(CONFIRMATION_UNAVAILABLE) or that was declined (WRITE_DECLINED), or
|
|
761
|
-
whose dry run says a real run would be refused; a sample of it that
|
|
762
|
-
could not be drawn (SAMPLE_STORAGE_UNREAD, SAMPLE_CANNOT_FIT,
|
|
763
|
-
SAMPLE_TOO_LARGE), or whose draw leaves no root (SAMPLE_DRAW_EMPTY);
|
|
764
|
-
a query that chooses no record (NO_ROOTS) or more than --max-roots
|
|
765
|
-
(ROOTS_EXCEEDED), records that reach more than --max-read-total
|
|
766
|
-
(READ_BOUND_EXCEEDED); a removal of a run that still
|
|
767
|
-
writes its journal, or its preview, and a --resume of it, or of a run
|
|
768
|
-
whose removal is under way (RUN_WRITING)
|
|
769
|
-
2 a bad command line, an --exclude that names no field of the source
|
|
770
|
-
(FIELD_EXCLUSION_UNMATCHED), an --object no clone writes
|
|
771
|
-
(TABLE_NEVER_CLONED), or a summary --remove cannot take a run back from, or
|
|
772
|
-
a file beside it that is not what a removal kept there; the plan of a
|
|
773
|
-
sample --fit-plan gives or --resume takes up gone, or drawn of another
|
|
774
|
-
org or setup (SAMPLE_PLAN_GONE, SAMPLE_PLAN_MISMATCH); a draw whose
|
|
775
|
-
--fit-window, --fit-where or --fit-strata the source cannot take
|
|
776
|
-
(SAMPLE_DRAW_INVALID); a query that cannot choose the records it
|
|
777
|
-
clones (ROOTS_QUERY_REFUSED); the plan of roots --roots-plan gives
|
|
778
|
-
gone, or of another org, query or records
|
|
779
|
-
(ROOTS_PLAN_GONE, ROOTS_PLAN_MISMATCH), and a run taken up whose journal
|
|
780
|
-
names none of the roots it read (ROOTS_PLAN_GONE)
|
|
781
|
-
3 the run was partial and --fail-on-partial was given, or was a clone of
|
|
782
|
-
the whole org; the removal left
|
|
783
|
-
records of the run in the org: kept, or refused, or found neither in the
|
|
784
|
-
org nor in its recycle bin, as the user it ran as sees them; or the sweep
|
|
785
|
-
was refused, or did not take all it was asked to (a --sweep-untied
|
|
786
|
-
refused included)
|
|
787
|
-
130 Ctrl-C stopped the clone: the summary says what it created by then
|
|
788
|
-
143 a SIGTERM stopped it \u2014 a CI job cancelled or timed out \u2014, 129 a SIGHUP:
|
|
789
|
-
as Ctrl-C does, the summary and the journal say what it created
|
|
790
|
-
`,pr=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,tt=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function xy(r,e){return r.verdict==="unread"?` API requests: about ${r.estimate}; what ${e} has left today could not be read (${r.unread})`:` API requests: about ${r.estimate}, of the ${r.remaining} ${e} has left of its ${r.max} a day`+(r.verdict==="exceeds"?": more than it has left":r.verdict==="near"?": it would leave less than a tenth of them":"")}var Py={"validation-rule":"a validation rule refused it","restricted-picklist":"a restricted picklist refused its value","lookup-filter":"a lookup filter refused the record it names","inactive-owner":"the target holds the owner it names inactive"},Fy={inputMode:"--record",recordId:"--record",depth:"--depth",customDepth:"--custom-depth",maxRecordsPerObject:"--max",sourceOrgId:"--source",targetOrgId:"--target",fieldExclusions:"--exclude",ownerMappings:"--owner-map",objectSoqlFilters:"--filter",fieldMappings:"--map",soqlQuery:"--object",sample:"--fit"},um=["fieldExclusions","excludedObjects","ownerMappings","objectSoqlFilters","fieldMappings","picklistValueMappings","recordTypeMappings","defaultValues","truncateFields","skippedRows","ignoredGaps"],Cy=M.strictObject(Lc.pick(Object.fromEntries(um.map(r=>[r,!0]))).shape);function Ny(r){let e=r;for(let t="";t!==e;)t=e,e=e.replace(/\([^()]*\)/g," ");return/\bFROM\s+([A-Za-z][A-Za-z0-9_]*)/i.exec(e)?.[1]}function My(r){let e=[];function t(n){process.stderr.write(`${n}
|
|
791
|
-
`),process.exit(2)}for(let n=0;n<r.length;n++){let o=r[n];if(o!=="--object"&&o!=="--where")continue;let s=r[n+1];if((s===void 0||s.startsWith("--"))&&t(o==="--object"?"--object takes the API name of a table to clone.":"--where takes a SOQL condition, written without WHERE."),n++,o==="--object"){tt.test(s)||t(`Invalid --object value "${s}" (must match SObject API name pattern)`),e.some(a=>a.objectApiName===s)&&t(`--object ${s} is named twice.`),e.push({objectApiName:s});continue}let i=e.at(-1);i?i.where!==void 0?t(`--object ${i.objectApiName} is given two --where: join them with AND.`):s.trim()===""?t(`--where for ${i.objectApiName} is empty.`):i.where=s.trim():t("--where filters the --object before it: name the table first.")}return e.length>0?e:void 0}function lm(r){let[e]=r;return`SELECT Id FROM ${e.objectApiName}${e.where?` WHERE ${e.where}`:""}`}function By(r,e){let t=new Set(e.map(n=>n.objectApiName));return r.nodes.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Ly(r,e){let t=new Set(r.nodes.map(n=>n.objectApiName));return e.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Wy(r){if(!xr(r))return;let e=Kt(),t=e?`the table ${r}`:`--object ${r}`;return Dc(r)?`${t}: a file goes with the record it hangs on, never as a table of its own. Leave it out${e?"":", and give --files to copy the files of the records cloned"}.`:`${t}: no clone writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Leave it out.`}var Dy=10;function _y(r,e){let t=r.filter(i=>Ao(i)&&!xr(i)),n=r.filter(i=>!t.includes(i)),o=i=>e.env?`the table${i.length===1?"":"s"} ${i.join(", ")}`:`--object ${i.join(", ")}`,s=[];if(n.length>0){let i=n.length===1,d=[...e.depth!=="custom"||e.customDepth<Dy?[e.env?"the resource's depth":"--depth"]:[],...e.truncated?[e.env?"the resource's maxNodes":"--max-nodes"]:[]],c=e.depth==="custom"?String(e.customDepth):e.depth;s.push(`${o(n)}: discovery from ${e.root} did not reach ${i?"it":"them"} (${e.objects} object(s), depth ${c}${e.truncated?", cut at its cap":""}): name first a table it hangs from or points at`+(d.length>0?`, or raise ${d.join(" or ")}.`:`; no lookup joins ${i?"it":"them"} to ${e.root} within the deepest walk, so clone ${i?"it":"them"} in a run of ${i?"its":"their"} own.`))}return t.length>0&&s.push(`${o(t)}: discovery does not walk into the objects of a managed package's namespace, whose configuration hangs off standard records: name ${t.length===1?"it":"one of them"} first, the table discovery starts from, or clone it in a run of its own.`),s.join(`
|
|
792
|
-
`)}function qy(r,e,t){return r==="record"?"--template: the template clones from a record it does not name: give --record.":`--template: the template clones from a query, which the command runs as whole tables: give ${e!==void 0?`--object ${e}${t!==void 0?` --where "${t}"`:""}`:"--object <ApiName> --where <condition>"} with --template, its root under the query's condition, and an --object for each other table to clone; or --record to clone one record with its choices.`}function Uy(r){return`Missing ${[...r.includes("what to clone")?["what to clone: --record <id> for one record, --object <ApiName> for whole tables, or --depth all for the whole org"]:[],...r.filter(t=>t.startsWith("--")).map(t=>`${t} <alias>`)].join("; ")}. Run with --help for usage.`}var Ng=1e3;function Gy(r,e){if(!e.given)return;e.expands||(process.stderr.write(`--max-orphans goes with --expand-orphans: it bounds the parents from outside the run that one copies.
|
|
793
|
-
`),process.exit(2));let t=Number(r);return(r===void 0||!/^\d{1,4}$/.test(r)||t<1||t>Ng)&&(process.stderr.write(`--max-orphans takes a whole number of parents, 1 to ${Ng}, not "${r??""}".
|
|
794
|
-
`),process.exit(2)),t}function zy(r,e){let t=r.tables??[],n=[...new Set([...r.excludedObjects,...By(e,t)])];return{inputMode:"soql",soqlQuery:lm(t),depth:r.depth,...r.depth==="custom"?{customDepth:r.customDepth}:{},sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...n.length>0?{excludedObjects:n}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions}}function Hy(r,e,t,n,o){let s=Dd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}},o)??{};return r.upsert?{...s,upsertMode:"auto"}:s}function tc(r){return r.depth==="all"?{inputMode:"org"}:r.roots?.query?{inputMode:"soql",soqlQuery:r.roots.query.soql,queryScope:"records",maxRoots:r.roots.cap}:r.tables?{inputMode:"soql",soqlQuery:lm(r.tables)}:{inputMode:"record",recordId:r.record}}function Ky(r){return r.depth==="all"?"the whole org":r.roots?.query?`query=${r.roots.query.soql}`:r.roots?.ids?`records=${r.roots.ids.join(", ")}`:r.tables?`tables=${r.tables.map(e=>e.where?`${e.objectApiName} (${e.where})`:e.objectApiName).join(", ")}`:`record=${r.record??""}`}var Hd=12;function Vy(r){let{roots:e,result:t,...n}=r;return{...n.record!==void 0?{record:n.record}:{},...n.objects?{objects:n.objects}:{},...n.wholeOrg?{wholeOrg:!0}:{},...e?{roots:{...e,...t.roots!==void 0?{count:t.roots.read}:{}}}:{}}}function Jy(r){if(r.roots){let{objectApiName:n,from:o,count:s}=r.roots;return s!==void 0?`${s} ${n} record${s===1?"":"s"} (${o==="query"?"query":"named"})`:`the ${n} records ${o==="query"?"a query chose":"named"}`}if(r.record)return r.record;let e=(r.objects??[]).map(n=>n.objectApiName),t=e.length<=Hd?e.join(", "):`${e.slice(0,Hd).join(", ")} and ${e.length-Hd} more object(s)`;return r.wholeOrg?e.length>0?`the whole org (${t})`:"the whole org":e.length>0?t:"the run"}function Qy(r){return{inputMode:"org",depth:"all",sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...r.excludedObjects.length>0?{excludedObjects:r.excludedObjects}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions,...r.sample?{sample:fm(r.sample)}:{}}}function fm(r){let e={...r.options};return delete e.plan,e}function Yy(r,e,t,n,o,s){return Dd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{wholeReadBound:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{},...s?{sample:s}:{}}},o)??{}}function Xy(r,e){return e.size===0?r:{...r,nodes:r.nodes.map(t=>e.has(t.objectApiName)?{...t,included:!1,leftOutByUser:!0}:t)}}var Mg=1e6;function Zy(r,e){if(e.length>Mg)return{refusal:[`${r}: the file is larger than ${Mg} bytes`]};let t;try{t=JSON.parse(e.replace(/^\uFEFF/,""))}catch{return{refusal:[`${r}: the file is not JSON`]}}let n=s=>s.issues.map(i=>{let a=i.path.map(String).join(".");return`${r}${a?` (${a})`:""}: ${i.message}`});if(r==="--template"){let s=Wc.safeParse(t);return s.success?{file:{kind:"template",template:s.data}}:{refusal:n(s.error)}}let o=Cy.safeParse(t);return o.success?{file:{kind:"config",config:o.data}}:{refusal:[...n(o.error),`${r} takes ${um.join(", ")}; the other choices have flags of their own.`]}}var ei=["--fit-within","--fit-seed","--fit-draw","--fit-window","--fit-where","--fit-strata","--fit-parents","--fit-children","--fit-whole","--fit-floor","--fit-plan"],eb={switches:["--list-objects","--anonymize","--keep-contact-points","--dry-run","--rehearse","--accept-automation","--accept-emails","--mute-automation","--upsert","--expand-orphans","--apply-assignment-rules","--skip-preflight","--json","--fail-on-partial","--write-uncertain","--files","--files-as-is","--no-anonymize","--yes",..._d.switches,"--include-changed"],values:["--record","--source","--target","--object","--where","--depth","--custom-depth","--max","--max-nodes","--max-total","--max-records-per-object","--max-orphans","--summary","--resume","--exclude","--exclude-object","--owner-map","--filter","--map","--config","--template","--remap-csv","--max-file-size","--audit","--fit",...ei,"--query","--max-roots","--roots-plan","--max-read-total",..._d.values]},tb=[["--record","it starts from no record"],["--object","it starts from no table: --exclude-object leaves one out"],["--where","it starts from no table: --filter narrows an object, and --fit-where, with --fit share, draws the roots of a sample among the records that match"],["--template","a template holds the choices of a walk from its record or query: give them with --config"],["--custom-depth","it walks no depth"],["--max-nodes","it takes every object it can, and is refused past 1950 rather than cut"],["--max","it copies every row of what it takes: --filter narrows an object, and --fit share copies a sample of the org that fits the target, none of its records without those they name"],["--expand-orphans","every parent it reaches is in the org it copies"],["--max-orphans","every parent it reaches is in the org it copies"],["--rehearse","a rehearsal holds every row it prepares: --dry-run counts what a real run would write and says what would refuse it, writing nothing"],["--upsert",`its writes go as Bulk API jobs that insert. To copy the org again without its records twice: --resume <journal> takes up a run that stopped, writing nothing it wrote; --remove <summary> takes back a run that ended before the copy is made again; or ${Ut("empty")} --target <alias> --objects <A,B> --dry-run says what emptying the target's objects would delete, every record of them`]];function nb(r,e){if(!e){let n=["--yes","--no-anonymize"].filter(o=>r(o));if(n.length===0)return;process.stderr.write(`${n.join(" and ")} ${n.length===1?"goes":"go"} with --depth all: no other clone asks before it writes, and none anonymizes unless --anonymize is given.
|
|
795
|
-
`),process.exit(2)}let t=tb.filter(([n])=>r(n));if(r("--anonymize")&&r("--no-anonymize")&&t.push(["--anonymize","it is given --no-anonymize too: give one of them"]),t.length!==0){for(let[n,o]of t)process.stderr.write(`--depth all clones the whole org, and does not go with ${n}: ${o}.
|
|
796
|
-
`);process.exit(2)}}var rb=["--fit-whole","--fit-where","--fit-strata"],ob=ei.filter(r=>!rb.includes(r)),sb={created:"CreatedDate",modified:"LastModifiedDate"},ib=`--fit-window takes created or modified, a colon, then <from>..<to>, each a date, as 2025-06-30, or an instant in UTC, as 2025-06-30T12:00:00Z, either left out but not both; or <n>d, the last n days, 1 to ${po}`;function ab(r){let e=r.indexOf(":"),t=e>0?sb[r.slice(0,e)]:void 0,n=r.slice(e+1),o=l=>({refusal:`${ib}, not "${r}"${l}.`});if(t===void 0)return o("");let s=/^(\d{1,6})d$/.exec(n);if(s){let l=Number(s[1]);return l<1||l>po?o(`: ${l} days is out of 1 to ${po}`):{field:t,lastDays:l}}let i=n.indexOf("..");if(i<0)return o("");let a=n.slice(0,i),d=n.slice(i+2);if(a===""&&d==="")return o(": give a start, an end or both");let c=a===""?void 0:bi(a,!1),u=d===""?void 0:bi(d,!0);return a!==""&&c===void 0?o(`: "${a}" is no such date`):d!==""&&u===void 0?o(`: "${d}" is no such date`):c!==void 0&&u!==void 0&&c>=u?o(`: it starts at ${c} and ends before ${u}, so no root is made in it; the end is left out of the window, a date there taking the whole day`):{field:t,...c!==void 0?{from:c}:{},...u!==void 0?{to:u}:{}}}function db(r,e){let t={},n=new Set;for(let d of r){let c=d.indexOf("="),u=c>0?d.slice(0,c):"",l=c>0?d.slice(c+1):"";if(!tt.test(u)||l.trim()==="")return{refusal:`Invalid --fit-where value "${d}": it takes <Object>=<WHERE>, the condition the roots of Object are drawn among, as Account=BillingCountry = 'France'.`};if(!xc.safeParse(l).success)return{refusal:l.length>512?`--fit-where condition for "${u}" exceeds 512 chars`:`--fit-where condition for "${u}" contains forbidden tokens (--, /*, */, trailing ;)`};if(n.has(u.toLowerCase()))return{refusal:`--fit-where names ${u} twice: give one condition of its roots, the two joined with AND or OR.`};n.add(u.toLowerCase()),t[u]=l}let o=Object.keys(t);if(o.length>yi)return{refusal:`--fit-where filters the roots of ${yi} objects at most, not ${o.length}.`};let s=d=>{let c=new Set(d.map(u=>u.toLowerCase()));return o.filter(u=>c.has(u.toLowerCase()))},i=s(e.whole);if(i.length>0)return{refusal:`--fit-where filters the roots of ${i.join(", ")}, which --fit-whole copies whole: every record of it comes, whatever the condition. Leave it out of --fit-whole, or narrow the object itself with --filter, which leaves records out of the copy.`};let a=s(e.excludedObjects);return a.length>0?{refusal:`--fit-where and --exclude-object both name ${a.join(", ")}: the run would leave out an object whose roots it draws. Give each to one of them.`}:{where:t}}function cb(r){let e=[];for(let n of r){if(!Mc.test(n))return{refusal:`Invalid --fit-strata value "${n}": it takes a field, as RecordTypeId, of every object drawn that has it, or an object and its field, as Account.RecordTypeId.`};if(e.some(o=>o.toLowerCase()===n.toLowerCase()))return{refusal:`--fit-strata ${n} is given twice: give it once.`};e.push(n)}if(e.length>wi)return{refusal:`--fit-strata stratifies the roots by ${wi} fields at most, not ${e.length}.`};let t=Bc.safeParse(e);return t.success?{strata:e}:{refusal:`--fit-strata ${t.error.issues.map(n=>n.message).join("; ")}: give each object one field, its own (Object.Field) or the one every object takes (Field).`}}var Bg=1e4,Lg=1e6,Wg=1e6,ub="sample.json";function lb(r,e){let t=w=>(process.stderr.write(`${w}
|
|
797
|
-
`),process.exit(2)),n=w=>r.flatMap((A,S)=>A===w&&S+1<r.length?[r[S+1]]:[]),o=w=>r.includes(w),s=ei.filter(w=>o(w));if(!o("--fit"))return s.length===0?void 0:t(`${s.join(", ")} ${s.length===1?"goes":"go"} with --depth all --fit share: ${s.length===1?"it sets":"they set"} how a sample of the whole org is drawn, and the line asks for none.`);let i=n("--fit");if(i.length!==1||i[0]!=="share")return t(`--fit takes share, once, not "${i.join(" ")}".`);if(!e.wholeOrg)return t("--fit share goes with --depth all: it copies a sample of the whole org that fits the target. A clone of a record or of tables reads what it reaches: --max caps each object.");if(o("--files"))return t("--fit share copies no files: the sample goes without the files of its records, and --files does not go with it. Leave out --files.");if(o("--list-objects"))return t("--list-objects lists the objects of the graph and draws no sample: leave out --fit share.");if(o("--fit-plan")&&o("--resume"))return t("--fit-plan does not go with --resume: a run taken up writes the plan its journal names, the one it began with.");for(let w of ob)n(w).length>1&&t(`${w} is given twice: give it once.`);let a=w=>n(w)[0],d={maxTotal:e.maxTotal},c=a("--fit-within");if(c!==void 0){let w=Number(c);(!/^\d+(?:\.\d+)?$/.test(c)||w<=0||w>Wg)&&t(`--fit-within takes a number of MB above 0, up to ${Wg}, not "${c}".`),d.withinMB=w}let u=a("--fit-seed");u!==void 0&&(/^\d{1,15}$/.test(u)||t(`--fit-seed takes a whole number, 0 or more, not "${u}".`),d.seed=Number(u));let l=a("--fit-draw");l!==void 0&&(l!=="uniform"&&l!=="recent"&&l!=="oldest"&&t(`--fit-draw takes uniform, the roots spread over each object by the seed, recent, the newest by their creation date, or oldest, the oldest by it, not "${l}".`),d.draw=l);let f=a("--fit-window");if(f!==void 0){let w=ab(f);"refusal"in w?t(w.refusal):d.window=w}let p=a("--fit-parents");p!==void 0&&(p!=="all"&&p!=="required"&&t(`--fit-parents takes all, the records an optional lookup names copied without their children, or required, such a lookup left empty, not "${p}".`),d.parents=p);let h=a("--fit-children");if(h!==void 0){let w=Number(h);h==="all"?d.children="all":/^\d{1,7}$/.test(h)&&w>=1&&w<=Lg?d.children=w:t(`--fit-children takes a whole number of children from 1 to ${Lg}, or all, not "${h}".`)}let g=[];for(let w of n("--fit-whole"))tt.test(w)||t(`Invalid --fit-whole value "${w}" (must match SObject API name pattern)`),g.includes(w)||g.push(w);let m=g.filter(w=>e.excludedObjects.includes(w));m.length>0&&t(`--fit-whole and --exclude-object both name ${m.join(", ")}: the sample would copy whole an object the run leaves out. Give each to one of them.`),g.length>0&&(d.whole=g);let y=db(n("--fit-where"),{whole:g,excludedObjects:e.excludedObjects});"refusal"in y?t(y.refusal):Object.keys(y.where).length>0&&(d.rootWhere=y.where);let k=cb(n("--fit-strata"));"refusal"in k?t(k.refusal):k.strata.length>0&&(d.strata=k.strata);let O=a("--fit-floor");if(O!==void 0){let w=Number(O);(!/^\d{1,5}$/.test(O)||w>Bg)&&t(`--fit-floor takes a whole number of records from 0 to ${Bg}, not "${O}".`),d.floor=w}let R=a("--fit-plan");if(R!==void 0){let w=Dt(R);d.plan=lc(w)===ub?Ey(w):w}return{options:d,maxTotalGiven:e.maxTotalGiven}}var fb=["--query","--max-roots","--roots-plan","--max-read-total"],pb=["--record","--object","--where","--fit",...ei];function hb(r){let e=k=>r.includes(k),t=k=>r.flatMap((O,R)=>O===k?[r[R+1]]:[]),n=k=>(process.stderr.write(`${k}
|
|
798
|
-
`),process.exit(2)),o=t("--query"),s=t("--record");if(o.length===0&&s.length<2){let k=fb.filter(O=>e(O));k.length>0&&n(`${k.join(", ")} ${k.length===1?"goes":"go"} with --query, or with --record given more than once: a clone of one record, of tables or of the whole org takes no roots of its own.`);return}let i=(k,O,R)=>{let w=Number(O);return O===void 0||O.startsWith("--")||!Number.isInteger(w)||w<1||w>R?n(`${k} takes a whole number, 1 to ${R.toLocaleString("en-US")}.`):w},a=k=>{let O=t(k);return O.length>1&&n(`${k} is given ${O.length} times: give it once.`),O[0]},d=a("--max-roots"),c=d===void 0&&!e("--max-roots")?kr:i("--max-roots",d,wn),u=a("--max-read-total"),l=u===void 0&&!e("--max-read-total")?void 0:i("--max-read-total",u,Number.MAX_SAFE_INTEGER),f=a("--roots-plan");if(e("--roots-plan")){(f===void 0||f.startsWith("--"))&&n("--roots-plan takes the file a dry run keeps the records it chooses in.");let O=[["--resume","a run taken up writes the roots its journal names"],["--list-objects","it reads no record"],["--rehearse","a rehearsal keeps nothing of what it reads"]].filter(([R])=>e(R));O.length>0&&n(`--roots-plan does not go with ${O.map(([R,w])=>`${R}: ${w}`).join("; ")}.`)}let p=f!==void 0?Dt(f):void 0,h={cap:c,...p!==void 0?{plan:p}:{},...l?{readTotal:l}:{}};if(o.length>0){let k=[...pb.filter(A=>e(A)),...t("--depth").includes("all")?["--depth all"]:[]];k.length>0&&n(`--query clones the records a query chooses, each with what the clone of that record copies: it does not go with ${k.join(", ")} (--record names records one by one, --object reads whole tables, --depth all copies the whole org or a sample of it).`);let O=a("--query");if(O===void 0||O.trim()===""||O.startsWith("--"))return n("--query takes a SOQL query, as SELECT Id FROM Account WHERE \u2026");let R=Pc(O),w=Ic(O);return R!==void 0||!w?n(Ot({code:"ROOTS_QUERY_REFUSED",message:`${Fc(R??{kind:"noObject"})}. Nothing was read or written.`})):(w.limit!==null&&w.limit>c&&n(`--query: its LIMIT ${w.limit} is past the ${c} records a run clones: give --max-roots ${w.limit} (up to ${wn.toLocaleString("en-US")}), or a lower LIMIT.`),{query:{soql:O.trim(),objectApiName:w.objectApiName,roots:{...w.where!==null?{where:w.where}:{},...w.orderBy!==null?{orderBy:w.orderBy}:{},...w.limit!==null?{limit:w.limit}:{}}},...h})}let g=[],m=new Set;for(let k of s){(k===void 0||!pr.test(k))&&n(`--record takes the 15- or 18-character id of a record: "${k??""}" is none.`);let O=(k??"").slice(0,15);m.has(O)||(m.add(O),g.push(k??""))}let y=[...new Set(g.map(k=>k.slice(0,3)))];return y.length>1&&n(`--record names records of ${y.length} objects (${y.map(k=>`${k}\u2026`).join(", ")}): a clone from records takes the records of one object; clone each object\u2019s apart, or choose them with --query.`),g.length>c&&n(`--record names ${g.length} records, past the ${c} a run clones: give --max-roots ${Math.min(g.length,wn)} (up to ${wn.toLocaleString("en-US")}), or name fewer.`),{ids:g,...h}}function gb(r,e=process.env){let t=r.slice(2);(t.includes("-h")||t.includes("--help"))&&(process.stdout.write(fc),process.exit(0)),Xc(t,eb);let n=(E,W)=>{let q=t.indexOf(E);return q>=0&&q+1<t.length?t[q+1]:W},o=E=>t.includes(E);o("--config")&&o("--template")&&(process.stderr.write(`--config and --template: give one of them.
|
|
799
|
-
`),process.exit(2));let s=o("--template")?"--template":o("--config")?"--config":void 0,i=s?n(s):void 0,a;if(s){(!i||i.startsWith("--"))&&(process.stderr.write(`${s} takes the path of a JSON file.
|
|
800
|
-
`),process.exit(2));let E;try{E=pn(i,"utf8")}catch(q){process.stderr.write(`${s}: cannot read ${i}: ${V(q)}
|
|
801
|
-
`),process.exit(2)}let W=Zy(s,E);if("refusal"in W){for(let q of W.refusal)process.stderr.write(`${q}
|
|
802
|
-
`);process.exit(2)}a=W.file}let d=a?.kind==="template"?a.template:void 0,c=hb(t),u=n("--depth")==="all";nb(o,u);let l=a?.kind==="template"?{...a.template.config}:a?.config??{},f=d?.config.soqlQuery!==void 0?Ny(d.config.soqlQuery):void 0,p=f!==void 0?l.objectSoqlFilters?.[f]:void 0;if(f!==void 0&&l.objectSoqlFilters?.[f]!==void 0){let E={...l.objectSoqlFilters};delete E[f],l.objectSoqlFilters=E}let h=My(t);if(h){let E=["--record","--expand-orphans","--max-orphans","--rehearse"].filter(W=>o(W));if(E.length>0){let W=E.includes("--rehearse")?" --dry-run reads the tables and counts what a real run would write, and says what would refuse it, writing nothing.":"";process.stderr.write(`--object clones whole tables, as the panel runs a query: it does not go with ${E.join(", ")}, which ${E.length===1?"goes":"go"} with a clone of one record (--record).${W}
|
|
803
|
-
`),process.exit(2)}d?.config.expandOrphanParents===!0&&(process.stderr.write(`--template: the template brings orphan parents (expandOrphanParents), which go with a clone of one record (--record), not with --object.
|
|
804
|
-
`),process.exit(2))}let g=d?.config.inputMode==="record"?d.config.recordId:void 0;d&&!h&&!c?.query&&!o("--record")&&!g&&(process.stderr.write(`${qy(d.config.inputMode,f,p)}
|
|
805
|
-
`),process.exit(2));let m=h||u||c?.query?void 0:n("--record")??g,y=n("--source"),k=n("--target"),O=[...!m&&!h&&!u&&!c?["what to clone"]:[],...y?[]:["--source"],...k?[]:["--target"]];(O.length>0||!y||!k)&&(process.stderr.write(`${Uy(O)}
|
|
806
|
-
`),process.exit(2)),o("--include-changed")&&(process.stderr.write(`--include-changed goes with --remove.
|
|
807
|
-
`),process.exit(2));let R=["--dry-run","--upsert","--files","--remap-csv","--list-objects"].filter(E=>o(E));o("--rehearse")&&R.length>0&&(process.stderr.write(`--rehearse does not go with ${R.join(", ")}.
|
|
808
|
-
`),process.exit(2));let w=jb(t),A=$g(t,[{flag:"--rehearse",why:"a rehearsal keeps nothing it creates in the target, and there is nothing to take back."},{flag:"--list-objects",why:"it lists the objects of the graph, and writes nothing."},{flag:"--resume",why:"a run taken up is the run its first part began, and a checkpoint taken now would hold what that part wrote: rewind to the one it took, if it took one."}]),S=n("--depth")??d?.config.depth??"custom",v=n("--custom-depth")??(d?.config.customDepth!==void 0?String(d.config.customDepth):"5"),j=n("--max")??(d?.config.maxRecordsPerObject!==void 0?String(d.config.maxRecordsPerObject):void 0),P=n("--max-nodes")??(d?.config.maxNodes!==void 0?String(d.config.maxNodes):void 0),B=n("--max-total"),I=n("--max-records-per-object"),z=E=>{let W=[];for(let q=0;q<t.length;q++)t[q]===E&&q+1<t.length&&W.push(t[q+1]);return W},Z=Object.fromEntries(Object.entries(l.fieldExclusions??{}).map(([E,W])=>[E,[...W]]));for(let E of z("--exclude")){let W=E.indexOf(".");(W<=0||W===E.length-1)&&(process.stderr.write(`Invalid --exclude value "${E}" (expected Object.field)
|
|
809
|
-
`),process.exit(2));let q=E.slice(0,W),ge=E.slice(W+1);(!tt.test(q)||!tt.test(ge))&&(process.stderr.write(`Invalid --exclude name in "${E}" (must match SObject API name pattern)
|
|
810
|
-
`),process.exit(2));let ee=Z[q]??=[];ee.includes(ge)||ee.push(ge)}let H=[...l.excludedObjects??[]];for(let E of z("--exclude-object"))tt.test(E)||(process.stderr.write(`Invalid --exclude-object value "${E}" (must match SObject API name pattern)
|
|
811
|
-
`),process.exit(2)),H.includes(E)||H.push(E);let U={...l.ownerMappings};for(let E of z("--owner-map")){let W=E.indexOf("=");(W<=0||W===E.length-1)&&(process.stderr.write(`Invalid --owner-map value "${E}" (expected sourceId=targetId)
|
|
812
|
-
`),process.exit(2));let q=E.slice(0,W),ge=E.slice(W+1);(!pr.test(q)||!pr.test(ge))&&(process.stderr.write(`Invalid --owner-map IDs in "${E}" (must be 15 or 18 char Salesforce IDs)
|
|
813
|
-
`),process.exit(2)),U[q]=ge}let J={...l.objectSoqlFilters};for(let E of z("--filter")){let W=E.indexOf("=");(W<=0||W===E.length-1)&&(process.stderr.write(`Invalid --filter value "${E}" (expected Object=where-clause)
|
|
814
|
-
`),process.exit(2));let q=E.slice(0,W),ge=E.slice(W+1);ge.length>512&&(process.stderr.write(`--filter where-clause for "${q}" exceeds 512 chars
|
|
815
|
-
`),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(ge)&&(process.stderr.write(`--filter where-clause for "${q}" contains forbidden tokens (--, /*, */, trailing ;)
|
|
816
|
-
`),process.exit(2)),J[q]=ge}let je=new Set(z("--filter").map(E=>E.slice(0,E.indexOf("="))));for(let E of h??[])E.where!==void 0&&(je.has(E.objectApiName)&&(process.stderr.write(`--where and --filter both filter ${E.objectApiName}: give one of them.
|
|
817
|
-
`),process.exit(2)),E.where.length>512&&(process.stderr.write(`--where for "${E.objectApiName}" exceeds 512 chars
|
|
818
|
-
`),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(E.where)&&(process.stderr.write(`--where for "${E.objectApiName}" contains forbidden tokens (--, /*, */, trailing ;)
|
|
819
|
-
`),process.exit(2)),J[E.objectApiName]=E.where);let pe=Object.fromEntries(Object.entries(l.fieldMappings??{}).map(([E,W])=>[E,{...W}]));for(let E of z("--map")){let W=E.indexOf("."),q=E.indexOf("=");(W<=0||q<=W+1||q===E.length-1)&&(process.stderr.write(`Invalid --map value "${E}" (expected Object.sourceField=targetField)
|
|
820
|
-
`),process.exit(2));let ge=E.slice(0,W),ee=E.slice(W+1,q),te=E.slice(q+1);(!tt.test(ee)||!tt.test(te))&&(process.stderr.write(`Invalid --map field name in "${E}" (must match SObject API name pattern)
|
|
821
|
-
`),process.exit(2)),(pe[ge]??={})[ee]=te}let ae=v?Number(v):5,K=j?Number(j):void 0,X=P?Number(P):void 0;X!==void 0&&(!Number.isInteger(X)||X<1)&&(process.stderr.write(`--max-nodes takes a whole number of objects, 1 or more.
|
|
822
|
-
`),process.exit(2));let ce=Gy(n("--max-orphans"),{given:o("--max-orphans"),expands:o("--expand-orphans")||d?.config.expandOrphanParents===!0}),Te=B===void 0?Wn:Number(B);(!Number.isInteger(Te)||Te<1)&&(process.stderr.write(`--max-total takes a whole number of records, 1 or more.
|
|
823
|
-
`),process.exit(2));let we=I===void 0?fo:Number(I);(!Number.isInteger(we)||we<1||we>mi)&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${mi}.
|
|
824
|
-
`),process.exit(2));let de=e.SANDFORGE_FORGE_PAGE_SIZE,_=de===void 0||de===""?void 0:Number(de);_!==void 0&&(!Number.isInteger(_)||_<1)&&(process.stderr.write(`SANDFORGE_FORGE_PAGE_SIZE takes a whole number of rows, 1 or more.
|
|
825
|
-
`),process.exit(2));let L=o("--anonymize")||d?.config.anonymizePII===!0,Re=o("--keep-contact-points")||d?.config.keepContactPoints===!0,Ie=vb(t,L),Ne=Jo(l),he=lb(t,{wholeOrg:u,maxTotal:Te,maxTotalGiven:B!==void 0,excludedObjects:H}),ve=(u?Ri:Ri.safeExtend({depth:Nc})).safeParse({...tc({record:m,tables:h,depth:u?"all":void 0,roots:c}),depth:S,customDepth:S==="custom"?ae:void 0,sourceOrgId:y,targetOrgId:k,anonymizePII:L,keepContactPoints:Re,skipEmpty:!0,batchSize:"auto",maxRecordsPerObject:K,fieldExclusions:Z,excludedObjects:H,ownerMappings:U,objectSoqlFilters:J,fieldMappings:pe,...Ne,...he?{sample:he.options}:{}});if(!ve.success){for(let E of ve.error.issues){let[W,...q]=E.path.map(String),ge=Fy[W??""]??(s&&W?`${s} ${W}`:W??"arguments"),ee=q.length>0?` (${q.join(".")})`:"";process.stderr.write(`Invalid ${ge}${ee}: ${E.message}
|
|
826
|
-
`)}process.exit(2)}return{record:m,...c?{roots:c}:{},tables:h,source:y,target:k,depth:ve.data.depth,customDepth:ae,maxNodes:X,maxRecordsPerObject:K,anonymize:L,anonymizeGiven:o("--anonymize")||o("--no-anonymize"),yes:o("--yes"),keepContactPoints:ve.data.keepContactPoints===!0,dryRun:o("--dry-run"),listObjects:o("--list-objects"),upsert:o("--upsert"),expandOrphans:o("--expand-orphans")||d?.config.expandOrphanParents===!0,...ce!==void 0?{maxOrphans:ce}:{},applyAssignmentRules:o("--apply-assignment-rules")||d?.config.applyAssignmentRules===!0,skipPreflight:o("--skip-preflight"),json:o("--json"),failOnPartial:o("--fail-on-partial"),summary:w,fieldExclusions:Z,excludedObjects:H,ownerMappings:U,objectSoqlFilters:J,fieldMappings:pe,remapCsv:$b(t),files:Ie,acceptAutomation:o("--accept-automation"),acceptEmails:o("--accept-emails"),muteAutomation:o("--mute-automation"),...A!==void 0?{checkpointFirst:A}:{},maxTotal:Te,readCeiling:we,..._!==void 0?{pageSize:_}:{},rehearse:o("--rehearse"),decisions:Ne,anonymizationRules:{...d?.anonymization?.rules},anonymizeFields:d?.anonymization?.fields,choicesFrom:s&&i?{flag:s,path:i}:void 0,audit:pc(t),resume:bb(t),writeUncertain:mb(t),...he?{sample:he}:{}}}function mb(r){return r.includes("--write-uncertain")?(r.includes("--resume")||(process.stderr.write(`--write-uncertain goes with --resume: it writes the rows of a call under way when the run stopped that the target may already hold.
|
|
827
|
-
`),process.exit(2)),!0):!1}function wb(r,e){let t=As(r),n=u=>(u??[]).reduce((l,f)=>l+f.rows,0),o=r.uncertain.map(({objectApiName:u,rows:l})=>`${l} ${u}`).join(", "),s=r.underway??[],i=n(r.untold),a=n(r.ofEndedJobs)-i,d=t-n(s)-i-a,c=[`${t} row(s) may already be in ${e} (${o}), sent by insert calls the run had under way when it stopped, their answer never kept.`];for(let u of s){let l=`${u.rows} of them went in Bulk API job ${u.jobId} (${u.objectApiName}), which ${e} holds ${u.state??"not ended"}`+(u.processed!==void 0?`, ${u.processed} row(s) processed`:"");c.push(u.state==="Open"?`${l}: the run stopped before it closed it, and closed, it would still write them.`:`${l}: ${e} writes it to its end whatever became of the run.`)}i>0&&c.push(`${i} of them went in a Bulk API job that wrote records the journal cannot tell apart, several rows under one fingerprint: none of those records is linked to a row, and each is kept as written by the run, for --remove to take back.`),a>0&&c.push(`${a} of them went in a Bulk API job that wrote records whose values are not what the run sent: none is taken for one of them, and each is kept as written by the run.`),d>0&&c.push(`${d} of them went in calls whose records ${e} holds and the resume cannot tell from them, or could not read.`),c.push("Nothing was written.");for(let u of s)c.push(u.state==="Open"?`Run the same --resume again ${u.openUntil!==void 0?`from ${u.openUntil}`+(u.graceLeftMs!==void 0?`, in about ${Math.max(1,Math.ceil(u.graceLeftMs/6e4))} minute(s)`:""):"an hour after the job was opened"}: it aborts job ${u.jobId} if it is open still, then writes its rows.`:`Run the same --resume again once job ${u.jobId} has ended: it reads what the job wrote, row by row.`);return i+a+d>0&&c.push(`Look at the records of those objects the run's user created in ${e} as the run stopped; run the same --resume with --write-uncertain to write those rows all the same (one already there is then there twice), or --remove the run.`),c.join(" ")}function yb(r,e=Date.now()){let t=r.underway??[];if(t.length===0)return;let n=s=>(s??[]).reduce((i,a)=>i+a.rows,0);if(As(r)>n(t))return;let o=e;for(let s of t){let i;if(s.state==="Open"){let a=s.openUntil!==void 0?Date.parse(s.openUntil):Number.NaN;if(Number.isFinite(a))i=a;else if(s.graceLeftMs!==void 0)i=e+s.graceLeftMs;else return}else{let a=Math.max(0,s.rows-(s.processed??0));i=e+Math.ceil(Zu(a,"save")*1e3)}o=Math.max(o,i)}return new Date(o).toISOString()}function bb(r){let e=r.indexOf("--resume");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--resume takes the journal of the run to take up, or its run id.
|
|
828
|
-
`),process.exit(2));let n=["--dry-run","--rehearse","--list-objects"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--resume takes a run up and writes: it does not go with ${n.join(", ")}.
|
|
829
|
-
`),process.exit(2)),t}function Dg(r,e){return r.endsWith(".ndjson")||/[\\/]/.test(r)?Dt(r):e.pathOf(r)}function _g(r,e,t={}){return{...r.sample?{sample:Gp(r.sample.options,t.planSha256),...t.sourceOrgId?{sourceOrgId:t.sourceOrgId.slice(0,15)}:{}}:{},source:r.source,targetOrgId:e.slice(0,15),record:r.record,...r.tables?{tables:r.tables}:{},...r.roots?.query?{query:{objectApiName:r.roots.query.objectApiName,...r.roots.query.roots}}:{},...r.roots?.ids?{records:[...r.roots.ids].sort()}:{},...r.roots?{maxRoots:r.roots.cap}:{},depth:r.depth,customDepth:r.depth==="custom"?r.customDepth:null,maxNodes:r.maxNodes??null,maxRecordsPerObject:r.maxRecordsPerObject??null,anonymize:r.anonymize,keepContactPoints:r.keepContactPoints,upsert:r.upsert,expandOrphans:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphans:r.maxOrphans}:{},applyAssignmentRules:r.applyAssignmentRules,fieldExclusions:r.fieldExclusions,excludedObjects:r.excludedObjects,ownerMappings:r.ownerMappings,objectSoqlFilters:r.objectSoqlFilters,fieldMappings:r.fieldMappings,decisions:r.decisions??null,anonymizationRules:r.anonymizationRules,anonymizeFields:r.anonymizeFields??null,files:r.files??null,readCeiling:r.depth==="all"?null:r.readCeiling}}async function Rb(r,e,t){let n=await r.headAt(e);if(!n)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: there is no journal of a run there. Every run that writes says its journal as it starts (journal: \u2026), under SANDFORGE_JOURNAL_DIR when it is set: give that file, or its run id. Nothing was written.`};if(!n.resume)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the journal does not say how its run was set up, and the run cannot be taken up: --remove ${e} takes back what it wrote, then run the clone again. Nothing was written.`};if((await r.lastEndAt(e))?.status==="success")return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the run ended, and there is nothing of it to take up.`};if(n.targetOrgId.slice(0,15)!==t.targetOrgId.slice(0,15))return{code:"RESUME_TARGET_CHANGED",message:`${t.target} is not the org the run to take up wrote to (${n.targetOrgId}): it is taken up there only. Nothing was written.`};let s=t.setup,i=Tb(r,e),a=t.sample?.asked===!0;if(i===void 0&&a)return{code:ls,message:`--resume ${e}: the run to take up copied every record of the whole org, not a sample: take it up without --fit share and its --fit-* flags. Nothing was written.`};if(i!==void 0&&!a)return{code:ls,message:`--resume ${e}: the run to take up copied a sample of the whole org: take it up with --fit share and the --fit-* flags it ran with. Nothing was written.`};if(i!==void 0&&t.sample){let d;try{d=await sr.open(i.dir,{sha256:i.sha256})}catch(c){let u=fs(c,"resume");if(!u)throw c;return{code:u.code,message:u.message.replace(/ Nothing was written\.$/,` It was in ${i.dir}. Nothing was written.`)}}d.manifest.drawnBy==="dryRun"&&(s=t.sample.setupWith(d.sha256))}if(!zp(n.resume.fingerprint,t.graph,s))return{code:"RESUME_CHANGED",message:`The clone is set up otherwise than the run to take up: ${Sb(n.resume,t)}. Give the same record or tables, orgs, depth, choices and flags it ran with; or take back what it wrote with --remove ${e}, and run the clone again as it is now. Nothing was written.`}}var Ob={sourceOrgId:"--source",depth:"--depth",customDepth:"--custom-depth",soqlQuery:"the first --object and its --where",anonymizePII:"--anonymize",keepContactPoints:"--keep-contact-points",maxRecordsPerObject:"--max",objectSoqlFilters:"--filter or --where",excludedObjects:"--exclude-object",fieldExclusions:"--exclude",fieldMappings:"--map",ownerMappings:"--owner-map",applyAssignmentRules:"--apply-assignment-rules",sample:"--fit and its --fit-* flags",picklistValueMappings:"the decisions of --config or --template",recordTypeMappings:"the decisions of --config or --template",defaultValues:"the decisions of --config or --template",truncateFields:"the decisions of --config or --template",skippedRows:"the decisions of --config or --template",ignoredGaps:"the decisions of --config or --template"},kb=new Set(["inputMode","targetOrgId","skipEmpty","batchSize","dryRun"]);function Sb(r,e){let t=[];r.recordId!==void 0&&e.record!==void 0&&r.recordId.slice(0,15)!==e.record.slice(0,15)&&t.push(`--record (${r.recordId} then, ${e.record} now)`);let n=r.startedWith;if(n&&e.config){let o={...n.config},s={...e.config},i=[...new Set([...Object.keys(o),...Object.keys(s)])].filter(p=>!kb.has(p)&&p!=="recordId"),a=new Set;for(let p of i)JSON.stringify(o[p]??null)!==JSON.stringify(s[p]??null)&&a.add(Ob[p]??p);a.size>0&&t.push(`${[...a].join(", ")} differ`);let d=p=>new Set(p.nodes.filter(h=>h.included||$r(h)).map(h=>h.objectApiName)),c=d(n.graph),u=d(e.graph),l=[...c].filter(p=>!u.has(p)),f=[...u].filter(p=>!c.has(p));l.length>0&&t.push(`it took ${fn(l)}, which this one leaves`),f.length>0&&t.push(`this one takes ${fn(f)}, which it left`)}return t.length>0?t.join("; "):"what differs is among what its journal does not keep: --upsert, --expand-orphans, --max-orphans, --max-nodes, --max-records-per-object, --files, --keep-contact-points, --exclude, --exclude-object, --owner-map, --map and the choices of --config or --template"}function Tb(r,e){let t=r.openAt(e);try{return t.samplePlan}finally{t.close()}}function pc(r){let e=r.indexOf("--audit");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--audit takes the file the audit trail is kept in.
|
|
830
|
-
`),process.exit(2));try{Ga(t)}catch(n){process.stderr.write(`--audit ${t} is not an audit trail the command can add to (${V(n)}): give another file, or move it.
|
|
831
|
-
`),process.exit(2)}return t}function Ab(r,e){return{configStore:Ga(r),orgManager:{getOrg:t=>e.get(t)},log:t=>process.stderr.write(`${t}
|
|
832
|
-
`)}}function Vs(r,e,t){if(!r){pu(t);return}try{gu(Ab(r,e),t)}catch(n){process.stderr.write(`The run's entry could not be added to the audit trail in ${r} (${V(n)}).
|
|
833
|
-
`)}}function jb(r){let e=r.indexOf("--summary");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--summary takes the file to write the summary to.
|
|
834
|
-
`),process.exit(2));let n=["--list-objects","--rehearse"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--summary does not go with ${n.join(", ")}.
|
|
835
|
-
`),process.exit(2)),Yt(t)&&(process.stderr.write(`--summary ${t} exists, and is not overwritten: it may be the summary of an earlier run, which --remove takes that run back from. Give another file, or move it.
|
|
836
|
-
`),process.exit(2)),t}function $b(r){let e=r.indexOf("--remap-csv");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--remap-csv takes the .csv file to write the id table to.
|
|
837
|
-
`),process.exit(2));let n=Dt(process.cwd(),t),o=Dt(process.cwd());return n===o||n.startsWith(o+Iy)||(process.stderr.write(`--remap-csv must stay inside cwd: "${t}" resolves outside ${o}
|
|
838
|
-
`),process.exit(2)),n.toLowerCase().endsWith(".csv")||(process.stderr.write(`--remap-csv must use a .csv extension: "${t}"
|
|
839
|
-
`),process.exit(2)),Yt(n)&&(process.stderr.write(`--remap-csv refuses to overwrite existing file: "${n}". Give another file, or move it.
|
|
840
|
-
`),process.exit(2)),n}function vb(r,e){let t=r.includes("--files"),n=r.includes("--files-as-is"),o=r.indexOf("--max-file-size"),s=o>=0?r[o+1]:void 0;if(!t){(n||o>=0)&&(process.stderr.write(`--files-as-is and --max-file-size go with --files.
|
|
841
|
-
`),process.exit(2));return}let i=o>=0?Number(s):10;return(!Number.isInteger(i)||i<1||i>35)&&(process.stderr.write(`--max-file-size takes a whole number of MB from 1 to ${35}, the most one call to Salesforce carries.
|
|
842
|
-
`),process.exit(2)),uo(e,n)&&(process.stderr.write(`--anonymize anonymizes the records, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, or leave out --files.
|
|
843
|
-
`),process.exit(2)),{maxFileSizeMB:i,acceptedAsIs:n}}function Eb(r){let e=Au(r.fields);return r.fields.map(t=>({name:t.name,type:t.type,queryable:!0,createable:t.createable??!1,isReference:t.type==="reference",referenceTo:(t.referenceTo??[]).filter(n=>typeof n=="string"),nillable:t.nillable??!0,picklistValues:(t.picklistValues??[]).filter(n=>n?.active!==!1&&typeof n?.value=="string").map(n=>n.value),restrictedPicklist:t.restrictedPicklist===!0,...t.controllerName?{controllerName:t.controllerName}:{},defaultedOnCreate:t.defaultedOnCreate===!0,externalId:t.externalId===!0,updateable:t.updateable!==!1,...t.length>0?{length:t.length}:{},...ju(t,e),...typeof t.groupable=="boolean"?{groupable:t.groupable}:{},...typeof t.sortable=="boolean"?{sortable:t.sortable}:{},...typeof t.aggregatable=="boolean"?{aggregatable:t.aggregatable}:{}}))}function Ib(r){return{name:r.name,fields:r.fields.map(e=>({name:e.name,type:String(e.type),referenceTo:(e.referenceTo??[]).filter(t=>typeof t=="string"),relationshipName:e.relationshipName??null,isMasterDetail:e.cascadeDelete===!0,nillable:e.nillable!==!1,createable:e.createable!==!1,updateable:e.updateable!==!1})),childRelationships:r.childRelationships.map(e=>({childSObject:e.childSObject,field:e.field,relationshipName:e.relationshipName??"",isCascadeDelete:!!e.cascadeDelete}))}}async function xb(r,e,t){let n="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",o=async u=>(await vo({query:async l=>u.query(l),queryMore:async l=>u.queryMore(l)},n)).records,[s,i]=await Promise.all([o(r),o(e)]),a=u=>({id:u.Id,name:u.Name,developerName:u.DeveloperName,namespacePrefix:u.NamespacePrefix?u.NamespacePrefix:null,sobjectType:u.SobjectType}),[d,c]=[s.map(a),i.map(a)];for(let u of qf(d,c))t?.(Uf(u));return new ms().buildMapping(d,c)}function Pb(r){let e=new Map;return(t,n)=>{let o=`${t}::${n}`,s=e.get(o);if(s)return s;let i=r(t,n);return e.set(o,i),i.catch(()=>{e.get(o)===i&&e.delete(o)}),i}}async function Kd(r,e,t=!1){let n=t?await r.sobject(e).describe():await r.describe$(e);return{keyPrefix:n.keyPrefix??null,recordTypes:Cu(n.recordTypeInfos)}}function YA(r){return $o(r)==="failure"}var Vd={masterInSource:"on Master in the source",notRead:"whose record type the run does not write",decidedDefault:"sent to the default by your decision",dropped:"whose record type the target lacks or keeps from the user"};function nc({developerName:r,label:e}){return e!==""&&e!==r?`${r} (${e})`:r}function Jd(r,e){let{predicted:t}=r;if(!t)return`${e} on Master, which the target gives a record sent without one for the user the run writes as`;let n=nc(t);return t.basis==="userDefault"?`${e} as ${n}, the default record type of the user the run writes as`:`${e} as ${n}, the only other ${r.objectApiName} record type open to the user the run writes as, whose describe names Master the default`}function Fb(r,e){let t=e.read<r.rows?`${e.read} of ${r.rows}`:`${e.read}`,n=r.predicted?.developerName??"Master",[o,...s]=e.types;if(o&&s.length===0&&o.developerName===n)return`went in as ${nc(o)}, read back on ${t}`;if(!o)return`none of them found as they were read back (asked of ${t})`;let i=e.types.map(a=>`${a.rows} ${nc(a)}`).join(", ");return`read back on ${t}: ${i}; the describe said ${n}: an automation of the target sets the record type`}function Cb(r,e){if(r.length===0)return[];let t=[`record types the target ${e?"would give":"gave"} the records created without one (${r.length} object(s)):`];for(let n of r){let o=Object.keys(Vd).filter(d=>(n.why[d]??0)>0),s=o.length===1?` ${Vd[o[0]]}`:o.length>1?` (${o.map(d=>`${n.why[d]} ${Vd[d]}`).join(", ")})`:"",{readBack:i}=n,a=e?Jd(n,"would go in"):i?i.unread!==void 0?`${Jd(n,"went in, its describe says,")}; the record types they hold could not be read back: ${i.unread}`:Fb(n,i):Jd(n,"went in, its describe says,");t.push(` ${n.objectApiName} ${n.rows} record(s)${s}: ${a}`)}return t}function Nb(r,e){let t=Qn(r.maxFileBytes),n=[`files (up to ${t} each):`];r.lookupFailure&&n.push(` ${r.lookupFailure}`," A real run stops here, before writing anything.");for(let o of r.objects){let s=Qn(o.plannedBytes);n.push(e?` ${o.objectApiName} ${o.planned} would be copied (${s}, dry run, nothing written)`:` ${o.objectApiName} ${o.copied} of ${o.planned} copied (${s})`+(o.failed>0?`, ${o.failed} failed`:""))}if(r.objects.length===0&&!r.lookupFailure&&n.push(" none to copy"),e&&r.wouldCopy&&r.wouldCopy.length>0){n.push(` would copy (${r.wouldCopy.length}):`);for(let o of r.wouldCopy)n.push(` ${o.objectApiName} ${o.name} ${Qn(o.bytes)}`)}if(r.links>0&&n.push(` links to other cloned records: ${r.links}`),r.remainingStorageBytes!==void 0&&n.push(` target file storage left: ${Qn(r.remainingStorageBytes)}`),r.leftOut.length>0){n.push(` left out (${r.leftOut.length}):`);for(let o of r.leftOut){let s=o.reason==="too-large"?`larger than ${t}`:o.reason==="external"?"kept outside Salesforce":"its records were not created by this run";n.push(` ${o.objectApiName} ${o.name} ${Qn(o.bytes)} \u2014 ${s}`)}}return n}function pm(r,e){let t=r.truncatedObjects??[];if(t.length!==0)return{...e!==void 0?{perObject:e}:{},objects:[...t]}}function Mb(r,e=!1){let t=new Map;for(let{objectApiName:a,rows:d}of r.writtenByThePlatform??[]){let c=Bn(a);t.set(c,(t.get(c)??0)+d)}let n=[...t.values()].reduce((a,d)=>a+d,0),o=r.linkedToCreatedCount??0;if(n===0&&o===0)return`linked: ${r.linkedCount} (already in the target, not created)`;let s=r.linkedCount-n-o,i=[...s>0?[`${s} already in the target, not created`]:[],...o>0?[e?`${o} to records the run would create: the target would refuse them as copies of those`:`${o} to records the run created, the target refusing them as copies of those`]:[],...[...t].map(([a,d])=>`${d} written by the platform with ${a}`)];return`linked: ${r.linkedCount} (${i.join("; ")})`}var Qd="FIELD_EXCLUSION_UNMATCHED";function hm(r){let e=`${Tn("--exclude","the exclusion")} ${r.objectApiName}.${r.field}`;return r.missing==="object"?`${e}: the source has no object ${r.objectApiName}`:`${e}: ${r.objectApiName} has no field ${r.field}`+(r.nearest!==void 0?` (${r.nearest}?)`:"")}function Bb(r){return[`left nothing out, naming no field of the source (${r.length}):`,...r.map(e=>` ${hm(e)}`)]}function qg(r,e){let t=Kt()?" of the template the resource names":e?` of --exclude, or of the fieldExclusions of ${e.flag} ${e.path}`:"";return`${r.map(hm).join("; ")}: ${r.length===1?"it leaves":"they leave"} nothing out, and the field the run was asked to keep back would be written with every row. Name the field as the source does \u2014 whatever its case \u2014 or leave the exclusion out${t}. Nothing was read or written.`}async function Lb(r,e,t){let n=Object.keys(r);if(n.length===0)return[];let o=e.nodes.map(i=>i.objectApiName),s=new Map;for(let i of n){let a=o.find(d=>d.toLowerCase()===i.toLowerCase())??i;if(!s.has(a))try{s.set(a,await t(a))}catch(d){s.set(a,nr(d)?void 0:null)}}return ns(r,o,i=>s.has(i)?s.get(i):null).unmatched}function Wb(r){let e=Kt()?"":" (--max-orphans raises it)";return`parents from outside the run not copied: ${r.notCopied} past the ${r.cap} --expand-orphans copies at most${e}, of ${r.objects.join(", ")}; the rows that cannot be written without one were refused`}function Ug(r,e=!1,t,n=!1){let o=[`success: ${r.successCount}`,...r.wouldInsertCount>0?[`would be inserted: ${r.wouldInsertCount} (dry run, nothing written)`]:[],...r.updatedCount>0?[`updated: ${r.updatedCount} (matched by their external id, not created)`]:[],Mb(r,e),`failed: ${r.failedCount}`+(r.failedReads.length>0?` (read failed: ${r.failedReads.join(", ")})`:""),`skipped: ${r.skippedCount}`,`remaps: ${r.remapCount}`,...r.apiCalls!==void 0?[`calls: ${r.apiCalls} (requests the run sent to both orgs)`]:[]];if(r.existingRecords.length>0){o.push("",`already in the target (${r.existingRecords.length} object(s)):`);for(let h of r.existingRecords){let g=h.linkedToCreated??0,m=[...h.linked-g>0||g===0?[`${h.linked-g} linked`]:[],...g>0?[e?`${g} linked to records the run would create (the target would refuse them as copies of those)`:`${g} linked to records the run created (refused as copies of those)`]:[]];h.unidentified>0&&m.push(`${h.unidentified} not identified \u2014 their children lost the link`),o.push(` ${h.objectApiName} ${m.join(", ")}`)}}if(r.cappedObjects){let{perObject:h,objects:g}=r.cappedObjects;o.push("",`stopped at ${h} records per object (${Tn("--max","maxRecordsPerObject")}), the source holding more, which were not cloned (${g.length} object(s)):`,...g.map(m=>` ${m}`))}let s=pm(r,t);if(s){let h=s.perObject!==void 0?`${s.perObject} `:"",g=Kt()?"":" (--max-records-per-object)";o.push("",`TRUNCATED at ${h}records per object${g}, the source holding more, which were not cloned (${s.objects.length} object(s)):`,...s.objects.map(m=>` ${m}`))}let i=r.fieldExclusionsUnmatched??[];i.length>0&&o.push("",...Bb(i)),r.orphanParentsCapped&&o.push("",Wb(r.orphanParentsCapped)),r.files&&o.push("",...Nb(r.files,e));let a=r.fileContentFieldsLeftOut??[];if(a.length>0){o.push("",`left empty, as they hold a file's content (${a.length} object(s)):`);for(let{objectApiName:h,fields:g}of a)o.push(` ${h} ${g.join(", ")}`)}let d=r.encryptedFieldsLeftOut??[];if(d.length>0){o.push("",`left out, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied (${d.length} object(s)):`);for(let{objectApiName:h,fields:g}of d)o.push(` ${h} ${g.join(", ")}`)}let c=r.picklistValuesChanged??[];if(c.length>0){let h=new Set(c.map(g=>g.objectApiName)).size;o.push("",`picklist values not written as read (${h} object(s)):`);for(let g of c)o.push(` ${g.objectApiName} ${Tl(g)}`)}let u=r.currenciesReplaced??[];if(u.length>0){let h=new Set(u.map(g=>g.objectApiName)).size;o.push("",`written in another currency (${h} object(s)):`);for(let g of u)o.push(` ${g.objectApiName} ${Fu(g)}`)}let l=Cb(r.recordTypesGiven??[],e);l.length>0&&(o.push("",...l),e&&n&&o.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"));let f=r.writtenWithoutFields??[];if(f.length>0){o.push("",`written again without a field the target refused (${f.length} object(s)):`);for(let{objectApiName:h,fields:g}of f)for(let{field:m,refusedBy:y="validation-rule",reason:k,rows:O}of g)o.push(` ${h}.${m} ${O} record(s) \u2014 ${Py[y]} \u2014 ${k}`)}r.contactPoints&&o.push("",...Vb(r.contactPoints,e));let p=r.mayHaveBeenWritten??[];if(p.length>0){o.push("",`may be in the target, under ids the run never learned (${Tn("--remove","destroy")} cannot reach them):`);for(let{objectApiName:h,sourceIds:g}of p)o.push(` ${h} ${g.length} record(s)`)}if(r.decisionsApplied&&r.decisionsApplied.length>0&&o.push("",...Kb(r.decisionsApplied)),r.gaps&&o.push("",...zb(r.gaps)),r.errors.length>0){o.push("",`errors (${r.errors.length} object(s)):`);for(let h of r.errors){o.push(` [${h.stage}] ${h.objectApiName} ${h.failedCount}/${h.attemptedCount}`);for(let g of h.samples){o.push(` ${g.recordSummary}`);for(let m of g.messages)o.push(` \u2514 ${m}`)}}}return o}function Db(r,e){return{objectApiName:(e.nodes.find(n=>n.level===0)??e.nodes[0])?.objectApiName??r.query?.objectApiName??"",from:r.query?"query":"records",...r.query?{query:r.query.soql}:{ids:[...r.ids??[]]},cap:r.cap,...r.plan!==void 0?{plan:r.plan}:{},...r.readTotal!==void 0?{readTotal:r.readTotal}:{}}}var Yr=10;function _b(r){let e=r.length-Yr;return`${r.slice(0,Yr).join(", ")}${e>0?` and ${e} more`:""}`}function vn(r,e){return`${r.toLocaleString("en-US")} ${e}${r===1?"":"s"}`}function qb(r,e){let t=r.roots;if(!t)return[];let n=t.objectApiName,o=t.query?`ORDER BY ${t.query.orderBy??"Id"}${t.query.limit!==void 0?`, LIMIT ${t.query.limit}`:""}; `:"",s=e.resumed?"the journal of the run taken up":`the dry run's plan${e.plan!==void 0?` ${e.plan}`:""}`,i=[t.from==="plan"?`roots: ${vn(t.read,`${n} record`)} taken from ${s} (sha256 ${t.sha256.slice(0,12)}\u2026, read ${t.readAt}; at most ${t.cap})`:t.from==="query"?`roots: ${vn(t.read,`${n} record`)} the query returns (${o}at most ${t.cap})`:`roots: ${vn(t.read,`${n} record`)} named (at most ${t.cap})`];t.from!=="plan"&&e.dryRun&&e.plan!==void 0&&i.push(`roots: kept in ${e.plan} (sha256 ${t.sha256.slice(0,12)}\u2026): the run given --roots-plan with it writes these records, and none the query chooses after`),t.readAgain&&i.push(`roots: the dry run's plan of ${t.readAgain.readAt} (${vn(t.readAgain.roots,"record")}) was a day old or more: the query was read again in its place`),t.gone.length>0&&i.push(`roots gone from ${e.source} since they were chosen: ${t.gone.length} (${_b(t.gone)}), none written`);let a=r.readByObject.filter(l=>l.read>0),d=a.reduce((l,f)=>l+f.read,0);i.push(`read: ${vn(d,"record")} of ${vn(a.length,"object")}`+(r.reads?`, ${vn(r.reads.source,"request")} of ${e.source}`:""));for(let l of a)i.push(...Ub(l));let c=t.linked>0?`, ${t.linked} linked to records ${e.target} already held`:"",u=(t.withTheirAccount??0)>0?`, ${t.withTheirAccount} of them with their person account`:"";if(i.push(`${e.dryRun?"roots that would be written":"roots written"}: ${t.written} of ${t.read}${u}${c}`),t.failed.length>0){i.push(`roots refused: ${t.failed.length}`);for(let{id:l,reason:f}of t.failed.slice(0,Yr))i.push(` ${l}: ${f}`);t.failed.length>Yr&&i.push(` and ${t.failed.length-Yr} more`)}return i}function Ub(r){let e=r.origin;if(!e)return[];let t=[...e.roots>0?[vn(e.roots,"root")]:[],...e.under>0?[`${e.under} under the clone's records`]:[],...e.named>0?[`${e.named} named by the clone's records`]:[]],n=r.readUnder&&r.readUnder.length>0?` (read under ${r.readUnder.join(", ")})`:"",o=t.length>1?`${r.read} = ${t.join(" + ")}`:t[0]??`${r.read}`;return[` ${r.objectApiName}: ${o}${n}`]}function Gb(r){let e=r.detail??{},t=[];typeof e.longest=="number"&&typeof e.length=="number"&&t.push(`longest ${e.longest} of ${e.length} characters`),typeof e.precision=="number"&&t.push(`precision ${e.precision}, scale ${String(e.scale??0)}`),typeof e.replacement=="string"&&t.push(`written as "${e.replacement}"`);let n=e.amountsConverted;Array.isArray(n)&&n.length>0&&t.push(`amounts converted into it: ${n.join(", ")}`),e.amountsAsRead===!0&&t.push("amounts written as read, no rate converts them"),typeof e.colliding=="number"&&t.push(`${e.colliding} value(s) already in the target`),e.linkedToTheRecordItNames===!0&&t.push("a real run links each row to the record the target holds");let o=e.mapTo;return Array.isArray(o)&&o.length>0&&t.push(`may map to ${o.join(", ")}`),e.ignored===!0&&t.push("ignored"),t.length>0?` (${t.join("; ")})`:""}function zb(r){return r.length===0?["gaps: none found (dry run: nothing the target would refuse or change)"]:[`gaps the target holds against the rows (${r.length}, dry run):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.value!==void 0?` "${e.value}"`:"",o=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` [${e.severity}] ${t} ${e.kind}${n}${o}: ${e.rows} record(s)${Gb(e)}`})]}function Hb(r){if(!r.choicesFrom)return[];let e=[Kt()?"choices from the resource in the file:":`choices from ${r.choicesFrom.flag} ${r.choicesFrom.path}, the flags over it:`],t=Object.entries(r.fieldExclusions).flatMap(([a,d])=>d.map(c=>`${a}.${c}`));t.length>0&&e.push(` fields left out: ${t.join(", ")}`),r.excludedObjects.length>0&&e.push(` objects left out: ${r.excludedObjects.join(", ")}`);for(let[a,d]of Object.entries(r.objectSoqlFilters))e.push(` filter ${a}: ${d}`);let n=Object.keys(r.ownerMappings).length;n>0&&e.push(` owners mapped: ${n}`);for(let[a,d]of Object.entries(r.fieldMappings))for(let[c,u]of Object.entries(d))e.push(` renamed: ${a}.${c} \u2192 ${u}`);let o=r.decisions,s=a=>a!==void 0?` (record type ${a})`:"",i=[...(o?.picklistValueMappings??[]).map(a=>` ${a.object}.${a.field} ${a.to===null?"leave_empty":"map_value"} "${a.from}"${a.to!==null?` \u2192 "${a.to}"`:""}${s(a.recordType)}`),...(o?.recordTypeMappings??[]).map(a=>` ${a.object} map_record_type "${a.from}" \u2192 ${a.to===null?"the default":`"${a.to}"`}`),...(o?.defaultValues??[]).map(a=>` ${a.object}.${a.field} set_default "${String(a.value)}"`),...(o?.truncateFields??[]).map(a=>` ${a.object}.${a.field} truncate`),...(o?.skippedRows??[]).map(a=>{let d=vc(a.gapId),c=Al(a);return` ${a.object}.${d?.field??"?"} skip_rows "${d?.value??""}"${s(d?.recordType)}`+(c!==void 0?`: ignored, ${c}`:"")}),...(o?.ignoredGaps??[]).map(a=>` ignore ${a}`)];return i.length>0&&e.push(` decisions (${i.length}):`,...i),e}function Kb(r){return[`decisions applied (${r.length}):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.from!==void 0?` "${e.from}"`:"",o=e.to!==void 0?` \u2192 "${e.to}"`:"",s=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` ${t} ${e.kind}${n}${o}${s}: ${e.rows} record(s)`})]}function Vb(r,e){if(!r.neutralized)return[`contact points: written as read (${Tn("--keep-contact-points","keepContactPoints")}): the target's flows and email alerts may reach the people the records name`];let t=e?"would be neutralized (dry run, nothing written)":"neutralized";return[`contact points: ${r.values} value(s) in ${r.fields.length} field(s) ${t} \u2014 emails under .invalid, phone numbers in a fictional range`,...r.fields.map(({objectApiName:n,field:o,values:s})=>` ${n}.${o} ${s}`),...r.numbersExhausted?[` ${r.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]}function Jb(r){return r.flatMap(({objectApiName:e,fields:t})=>t.flatMap(n=>{if(n.externalId!==!0||n.createable===!1)return[];let o=cl(n.name,String(n.type).toLowerCase());return o?[{objectApiName:e,field:n.name,kind:o}]:[]}))}function Qb(r,e){return r.length===0?[]:[`upsert keys: --upsert matches the records of ${e} by these external ids, which the run writes neutralized (emails under .invalid, phone numbers in a fictional range): a record of ${e} holding the real address or number is not matched, and the run creates another beside it; one an earlier run wrote neutralized is. --keep-contact-points matches the real ones`,...r.map(({objectApiName:t,field:n,kind:o})=>` ${t}.${n} (${o})`)]}function Yb(r,e,t,n){if(!r)return{};let o=Vc(Ec(e.gaps,t??[]).filter(s=>!lo(s,n)));return o.length>0?{adminChanges:o}:{}}function Xb(r,e){let t=pm(r,e);return{successCount:r.successCount,updatedCount:r.updatedCount,linkedCount:r.linkedCount,...r.linkedToCreatedCount?{linkedToCreatedCount:r.linkedToCreatedCount}:{},...r.writtenByThePlatform?{writtenByThePlatform:r.writtenByThePlatform}:{},wouldInsertCount:r.wouldInsertCount,failedCount:r.failedCount,skippedCount:r.skippedCount,remapCount:r.remapCount,existingRecords:r.existingRecords,errors:r.errors.map(n=>({objectApiName:n.objectApiName,stage:n.stage,failedCount:n.failedCount,attemptedCount:n.attemptedCount,samples:n.samples,...n.referenceData===!0?{referenceData:!0}:{},...n.skipped===!0?{skipped:!0}:{}})),remapTable:r.remapTable,existingSourceIds:r.existingSourceIds,updatedSourceIds:r.updatedSourceIds,createdByObject:r.createdByObject,...r.withTheirRecordSourceIds?{withTheirRecordSourceIds:r.withTheirRecordSourceIds}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},readByObject:r.readByObject,failedReads:r.failedReads,...r.cappedObjects?{cappedObjects:r.cappedObjects}:{},...t?{truncatedObjects:t}:{},...r.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:r.fieldExclusionsUnmatched}:{},...r.orphanParentsCapped?{orphanParentsCapped:r.orphanParentsCapped}:{},...r.files?{files:r.files}:{},...r.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:r.fileContentFieldsLeftOut}:{},...r.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:r.encryptedFieldsLeftOut}:{},...r.picklistValuesChanged?{picklistValuesChanged:r.picklistValuesChanged}:{},...r.currenciesReplaced?{currenciesReplaced:r.currenciesReplaced}:{},...r.recordTypesGiven?{recordTypesGiven:r.recordTypesGiven}:{},...r.writtenWithoutFields?{writtenWithoutFields:r.writtenWithoutFields}:{},...r.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:r.lookupsLeftEmptyByFilter}:{},...r.contactPoints?{contactPoints:r.contactPoints}:{},...r.apiCalls!==void 0?{apiCalls:r.apiCalls}:{},...r.gaps?{gaps:r.gaps}:{},...r.decisionsApplied?{decisionsApplied:r.decisionsApplied}:{},...r.mayHaveBeenWritten?{mayHaveBeenWritten:r.mayHaveBeenWritten}:{},...r.remapInJournal?{remapInJournal:!0}:{},...r.remapInJournal?{createdCountByObject:r.remapByObject.filter(({created:n})=>n>0).map(({objectApiName:n,created:o})=>({objectApiName:n,created:o}))}:{},...r.sample?{sample:TR(r.sample)}:{},...r.roots?{roots:r.roots}:{},...r.reads?{reads:r.reads}:{}}}function Zb(r){if(r.status==="running"&&r.message.startsWith("[dry-run] "))return` ${r.message}`;if(r.status==="scanning")return r.progress>0&&r.message?` ${r.message}`:void 0;if(!(r.status!=="done"&&r.status!=="error"&&r.status!=="skipped"&&r.status!=="stopped"))return r.message?` ${r.message}`:void 0}function eR(r){let e=new Set(r.nodes.filter($r).map(n=>n.objectApiName)),t=!1;return n=>{if(n.status==="skipped"&&e.size>1&&e.has(n.objectName)){if(t)return;t=!0;let o=St("--list-objects")?"; --list-objects names them":"";return` Skipped ${e.size} objects (excluded: empty tables${o})`}return Zb(n)}}function tR(r,e,t){let n=new Set(r.nodes.map(p=>p.objectApiName)),o=r.nodes.filter(p=>p.included).length,s=r.edges.filter(p=>n.has(p.sourceObject)&&n.has(p.targetObject)).length,i=r.nodes.length-r.nodes.filter(gf).length,a=i>0?` (${i} empty, taking no place under it)`:"",d=r.nodes.length-i>t?" (raised for the parents their records cannot be written without)":"",{refused:c,unanswered:u}=km(r),l=c.length>0?`, ${c.length} not counted (${fn(c)})`:"",f=u.length>0?`, ${u.length} of them kept though their count got no answer (${fn(u)})`:"";return`graph: ${r.nodes.length} objects at a cap of ${t}${a}${d}, ${o} included${f}${l}; ${r.edges.length} lookups, ${s} between these objects; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`+(r.truncated?" (TRUNCATED)":"")}var gm={missingInTarget:"missing in the target",notQueryable:"not queryable",empty:"empty",unreadable:"unreadable",notWritable:"not writable in the target",createOnly:"creatable but not editable or deletable in the target",setup:"setup",platformCreated:"written by the platform alone",metadata:"metadata",chatter:"Chatter",history:"history",sharing:"sharing",changeEvent:"change events",unsupportedKind:"of a kind no clone writes",customSetting:"custom settings",files:"files, copied with --files",excludedByUser:"left out by --exclude-object",notDescribed:"not described"};function nR(r,e,t){let n=r.nodes.filter(a=>a.included).length,{objects:o,counts:s}=us(r),i=s.map(({reason:a,count:d})=>`${d} ${gm[a]}`).join(", ");return`graph: the whole of ${t}, ${n} object(s) to copy, ${o.length} left out${i?` (${i})`:""}; ${r.edges.length} lookups; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`}var rR={listing:()=>"discovery: listing the objects of both orgs\u2026",counting:r=>`discovery: counting the records of ${r??"each"} object(s)\u2026`,describing:r=>`discovery: describing the ${r??""} object(s) that hold records\u2026`};async function oR(r,e,t){let n;try{return await r.discover(e,{onProgress:o=>{if(o.phase===n)return;n=o.phase;let s=rR[o.phase];s&&t(s(o.total))}})}catch(o){process.stderr.write(`The whole org could not be discovered: ${V(o)}
|
|
844
|
-
`),process.exit(1)}}function Yd(r,e,t){let{estimate:n,remaining:o,max:s}=e;return o===void 0||s===void 0?` ${r} of ${t}: about ${n}; what it has left today could not be read`+(e.unread?` (${e.unread})`:""):` ${r} of ${t}: about ${n}, of the ${o} it has left of its ${s} a day`+(e.near?": it would leave less than a tenth of them":"")}var Gg=10;function fn(r){let e=r.length-Gg;return e>0?`${r.slice(0,Gg).join(", ")} and ${e} more`:r.join(", ")}function sR(r,e,t,n=[]){let{source:o,bulk:s}=r,i=n.filter(({jobs:m})=>m>0),a=i.length>0?` (${fn(i.map(m=>`${m.objectApiName}: ${m.jobs} of ${m.jobRows}`))}; rows of a job carrying the same values go by REST instead)`:"",d=[` writes: ${s?.jobs??0} Bulk API job(s) of ${s?.jobRows??0} record(s) at most${a}, ${s?.restRows??0} record(s) by REST, ${r.restObjects.length} object(s) by REST alone; about ${Math.max(1,Math.round(r.durationSeconds/60))} minute(s) one after another`,Yd("API requests",r.targetApi,t),...s?.batches?[Yd("Bulk API batches",s.batches,t)]:[],Yd("API requests",r.sourceApi,o),...r.discovery?[` of them, sent already by discovery: ${r.discovery.target} of ${t}'s and ${r.discovery.source} of ${o}'s`]:[]],c=r.fileStorage;c&&d.push(` files: ${c.files} file(s), about ${Wt(c.estimateMB)} MB of file storage, of the ${c.remainingMB} MB ${t} has left of ${c.maxMB} MB`+(c.overCeiling>0?`; ${c.overCeiling} past the largest file copied, left out`:""));let u=e.map(({reason:m,count:y})=>`${y} ${gm[m]}`).join(", ");d.push(` left out of ${o}: ${r.leftOut} object(s)${u?`: ${u}`:""}`);let{carried:l}=r,f=l?[["read through a filter",l.filters],["left out by name",l.excluded],["with rows held back by a decision",l.heldBack],["copied without some of their fields",l.fieldsLeftOut]]:[];for(let[m,y]of f)y.length>0&&d.push(` ${m}: ${fn(y)}`);let p=r.personalAsIs??[],h=p.reduce((m,{fields:y})=>m+y.length,0);d.push(h>0?` personal data: ${h} field(s) of ${p.length} object(s) copied as ${o} holds them: `+fn(p.map(({objectApiName:m,fields:y})=>`${m} (${y.join(", ")})`)):" personal data: no personal field copied as it is");let g=r.managedPackages??[];return g.length>0&&d.push(` managed packages: ${g.length} object(s) written, whose triggers and flows no mute reaches: ${fn(g)}`),r.contactPointsBlanked!==void 0&&d.push(` phone numbers: up to ${r.contactPointsBlanked} past the fictional range go in empty`),d}function iR(r,e,t){return`discovery: ${r.source} API request(s) sent to ${e} and ${r.target} to ${t}, before any row is read`}function lr(r,e,t){let n=(o,s)=>{if(!o)return{sent:s};let{parts:i,...a}=o;return{...a,...i?{parts:i}:{},sent:s}};return{target:n(e.target,r.target),source:n(e.source,r.source),...t?{discovery:t}:{}}}function zg(r){return`Write ${r}?`}function Hg(r,e,t,n){let{source:o,bulk:s}=r,i=e.objects.filter(({rows:g})=>g>0).length,a=r.managedPackages??[],d=r.personalAsIs??[],c=d.reduce((g,{fields:m})=>g+m.length,0),u=r.sample,l=u?.roots?bm(u.roots):[],f=u?.roots?.window!==void 0||(u?.roots?.where??[]).length>0?" in the draw":"";return[(u&&n?`a sample of ${o}: ${e.totalRows} record(s) of ${i} object(s) (of ${u.sourceRows} in ${o}) into ${t}, about ${Wt(u.storageMB)} MB`+(hc(n.budget)?` of the ${Wt(u.budgetMB)} MB it may take`:"")+(u.automationMB!==void 0?`, ${Wt(u.automationMB)} MB of it for what the target's automation creates`:"")+`; ${[gc(u),...l].join("; ")}, ${ti(u.share)} % of the roots${f}; drawn at ${u.drawnAt} by ${u.drawnBy==="dryRun"?"a dry run":"this run"}; ${s?.jobs??0} Bulk API job(s) among them`:void 0)??`${e.totalRows} record(s) of ${i} object(s) of ${o} into ${t}, ${s?.jobs??0} Bulk API job(s) among them`,`about ${r.targetApi.estimate} of ${t}'s API requests`+(s?.batches?` and ${s.batches.estimate} of its Bulk API batches`:"")+` and ${r.sourceApi.estimate} of ${o}'s`,...a.length>0?[`${a.length} object(s) of managed packages, whose triggers and flows no mute reaches (${fn(a)})`]:[],...r.contactPointsBlanked!==void 0?[`up to ${r.contactPointsBlanked} phone number(s) written empty`]:[],c>0?`${c} personal field(s) of ${d.length} object(s) copied as they are`:"no personal field copied as it is"].join("; ")}function Kg(r,e=!1){let t=" \u2014 or leave objects out (--exclude-object), narrow them (--filter)"+(e?".":", or copy a sample of the org that fits the target (--fit share, its dry run first).");return r.replaceAll("turn the copy of files off on Review","leave out --files").replaceAll("leave the object out on Review","leave it out with --exclude-object").replaceAll("the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting","--max-records-per-object lets a run hold at once: raise it").replaceAll(" \u2014 or leave objects out.",t).replaceAll(" \u2014 or write fewer records.",t)}var aR=[[/--fit-where "([A-Za-z0-9_]+)=([^"]*)"/g,'fit.where.$1: "$2"'],[/--fit-where ([A-Za-z0-9_]+)=…/g,"fit.where.$1"],[/--fit-strata ([A-Za-z0-9_]+)\.<Field>/g,"fit.strata: [$1.<Field>]"],[/--fit-draw (uniform|recent|oldest)\b/g,"fit.draw: $1"],[/--fit-within(?![\w-])/g,"fit.withinMB"],[/--fit-(window|where|strata|draw|seed)(?![\w-])/g,"fit.$1"],[/--max-total(?![\w-])/g,"maxTotal"]];function Xr(r){return Kt()?aR.reduce((e,[t,n])=>e.replace(t,n),r):r}function dR(r,e,t){let n=r.personAccountsAsBusiness??0;if(!(n<=0))return` person accounts: ${n} of ${e}'s go in as business accounts, ${t} having none, and their contacts as contacts of their own`}function cR(r,e,t=!1,n=!1){return!St("--max-total")&&ys()?wc(r,e,n).replace(/^The run /,"The clone of the whole org "):`The clone of the whole org would write ${r} records, more than the ${e} --max-total holds it to: give --max-total the count its dry run says, `+(t?"":"copy a sample of the org that fits the target and --max-total (--fit share, its dry run first), ")+"or leave objects out (--exclude-object) or narrow them (--filter)."}function mm(r){let{objectApiName:e,count:t,query:n,fits:o,each:s}=r,i=n?"the query chooses":"named";if(o<1)return;let a=`the ${t} ${e} records ${i} take ${s} each, and about ${o} of them fit`;if(!n)return`${a}: name ${o} of them at most`;let d=n.orderBy===void 0?`the newest ${o}`:`the first ${o} in its order`;return`${a}: ${at("--query")} "${xl(e,n,o)}" clones ${d}, its dry run first, or narrow its WHERE`}function wm(r){return`one of the ${r.count} ${r.objectApiName} records ${r.query?"the query chooses":"named"} takes ${r.each} on average, more than ${r.past} by itself`}function uR(r,e,t,n=!1){if(ys())return wc(r,e,n);let o=mm(t),s=`leave objects out (${at("--exclude-object")}) or narrow them (${at("--filter")})`;return`The run would write ${r} records, more than the ${e} ${at("--max-total")} holds it to: `+(o!==void 0?`${o}; or ${s}, or raise ${at("--max-total")}.`:`${wm(t)}: ${s}, clone less deep (${at("--depth")} direct), or raise ${at("--max-total")}.`)}function lR(r,e,t){if(r.verdict!=="exceeds")return;let n=mm(t),o=`leave objects out (${at("--exclude-object")})`;return`The records to write take ${ka(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB${Oa(ds(r),e)}: `+(n!==void 0?`${n}; or ${o}, or free data storage in ${e}.`:`${wm(t)}: ${o}, clone less deep (${at("--depth")} direct), or free data storage in ${e}.`)}function Vg(r,e,t){let n=r.roots;if(!n||n.count<1)return;let o=n.from!=="records";return{objectApiName:n.objectApiName,count:n.count,...o&&e?{query:e}:{},fits:Il(n.count,t.taken,t.room),each:t.each(t.taken/n.count),past:t.past}}function fR(r,e){if(r.verdict==="exceeds")return`The records to write take ${ka(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB${Oa(ds(r),e)}: copy a sample of the org that fits it (--fit share, its dry run first), leave objects out (--exclude-object) or narrow them (--filter), or free data storage in ${e}.`}var pR=2*1024;function hR(r){let{storage:e,sample:t,target:n}=r,{withinMB:o}=t.options,s=t.options.maxTotal??Wn,i=xf({storage:e,bounds:rc(t),target:n});if(i)throw Pe.of(i);let a=r.automation?{automation:r.automation}:{},d=r.allowances?{allowances:r.allowances}:{},c=nd({storage:e,...o!==void 0?{withinMB:o}:{},...a,...d});if(c)return{...c,budget:{...c.budget,maxTotal:s}};let u=nd({storage:{maxMB:0,remainingMB:0},...a,...d});return{budget:{bytes:Number.MAX_SAFE_INTEGER,maxTotal:s,limitedBy:"maxTotal"},bytesLimit:"within",roomBytes:s*pR,...u?.automationBytes?{automationBytes:u.automationBytes}:{},...u?.requests?{requests:u.requests}:{}}}function rc(r){let{withinMB:e}=r.options;return{...e!==void 0?{withinMB:e}:{},...r.maxTotalGiven?{maxTotal:r.options.maxTotal??Wn}:{}}}function hc(r){return r.remainingMB!==void 0||r.withinMB!==void 0}function ti(r){return String(Number((r*100).toPrecision(2)))}function gc(r){switch(r.draw){case"recent":return"the newest by creation date";case"oldest":return"the oldest by creation date";case"uniform":return`seed ${r.seed}, spread over the org`}}function ym(r){let e=r.field==="LastModifiedDate"?"last modified":"created";if(r.lastDays!==void 0)return`roots ${e} in the last ${r.lastDays} day(s)`+(r.from!==void 0?`, from ${r.from}`:"");let t=r.from!==void 0?` from ${r.from}`:"",n=r.to!==void 0?` to before ${r.to}`:"";return`roots ${e}${t}${n}`}function bm(r){return[...r.window?[ym(r.window)]:[],...(r.where??[]).map(({objectApiName:e,where:t})=>`${e} where ${t}`),...(r.strata??[]).map(({objectApiName:e,field:t,values:n})=>`${e} stratified by ${t} (${n} value(s))`)]}function gR(r){return(r??[]).map(({objectApiName:e,field:t,values:n,more:o})=>({objectApiName:e,field:t,values:n.length+(o??0)}))}function Rm(r){return r?.window!==void 0||(r?.where??[]).length>0}function mR(r,e,t){let{budget:n}=r;switch(n.limitedBy){case"heavyRoots":return`every root fits but ${r.heavyRoots.length} heavy root(s) set aside below, each past a tenth of the room ${t} has: they alone keep the sample from every root`;case"storage":return`limited by the data storage ${t} has left`;case"within":return`limited by --fit-within ${n.withinMB??""}`.trimEnd();case"maxTotal":return`limited by --max-total ${n.maxTotal??Wn}`;case"targetRequests":return`limited by the daily API requests ${t} has left`;case"bulkBatches":return`limited by the daily Bulk API batches ${t} has left`;case"sourceRequests":return`limited by the daily API requests ${e} has left`;case"whole":return"every record of the org fits: leave out --fit share to copy the whole org";case"draw":return Xr("limited by the draw: every root --fit-window and --fit-where leave is in the sample; widen them to take more")}}function wR(r){let e=`${r.details} records (${r.details}.${r.field})`;return r.asParents!==void 0?`the ${r.asParents} brought in as parents keep only the ${e} drawn on their own: if they total them (an amount, a roll-up summary), the total counts only those`:`keeps ${r.kept??0} of its ${r.sourceRows??0} ${e} in the sample: if it totals them (an amount, a roll-up summary), the total counts only those`}function yR(r,e){let{budget:t}=r,n=`about ${Wt(r.storageBytes/1048576)} MB`;if(!hc(t))return`${n}, held to ${t.maxTotal??Wn} records (--max-total): ${e} would not say its data storage`;let o=`${n} of the ${Wt(t.bytes/1048576)} MB the sample may take`;if(t.remainingMB===void 0)return`${o} (--fit-within ${t.withinMB}; ${e} would not say its data storage)`;let s=[`${ti(t.share??0)} % of the ${t.remainingMB} MB ${e} has left`+(t.maxMB!==void 0?` of ${t.maxMB} MB`:""),...t.roundingMB!==void 0?[`${t.roundingMB} MB off for rounding`]:[],...t.uncountedMB!==void 0&&t.uncountedMB>0?[`${Wt(t.uncountedMB)} MB off for what runs from this machine wrote to it that Salesforce has not counted yet`]:[],...t.automationMB!==void 0&&t.automationMB>0?[`${Wt(t.automationMB)} MB for what its automation creates`]:[],...t.withinMB!==void 0?[`--fit-within ${t.withinMB}`]:[]];return`${o} (${s.join(", ")})`}var Om={referenceData:"reference data, matched by name",catalog:"the price catalog",smallParent:"a small parent",asked:"--fit-whole"};function bR(r,e,t){switch(r){case"noParentInSource":return`a lookup they may not leave empty names a record ${e} does not hold`;case"outsideFilter":return"a lookup they may not leave empty names a record outside its object's filter";case"excludedObject":return"a lookup they may not leave empty names a record of an object left out";case"withoutParent":return"a record they cannot be written without is left out itself";case"heldBack":return"their record type is closed to the user the run writes as";case"recordTypeNotInTarget":return`their record type is one ${t} has none of`}}function RR(r,e){if(r.whole){let t=e.find(n=>n.objectApiName===r.objectApiName)?.why;return`copied whole${t?` (${Om[t]})`:""}`}return`${r.roots} drawn, ${r.below} under a parent, ${r.asParents} as parents`}function OR(r){return r.label!==void 0?r.label:r.value===null?"(no value)":String(r.value)}function kR(r,e){let t=r.roots;if(!t)return[];let n=[];if(Rm(t)){let s=new Set(t.notWindowed??[]),i=[...r.objects.flatMap(a=>a.rootsInTheDraw===void 0?[]:[`${a.objectApiName} ${a.rootsInTheDraw} in the draw`+(a.rootsInTheSource!==void 0?` of ${a.rootsInTheSource} root(s) in ${e}`:"")]),...r.noRecordDrawn.filter(({objectApiName:a,noRootInTheDraw:d})=>d&&!s.has(a)).map(({objectApiName:a,sourceRows:d})=>`${a} none in the draw (${d} record(s) in ${e})`),...s.size>0&&t.window?[`not windowed (no ${t.window.field}): ${[...s].join(", ")}`]:[]];i.length>0&&n.push(`roots: ${i.join("; ")}`)}let o=t.strata??[];if(o.length>0){let s=o.map(({objectApiName:i,field:a,values:d,more:c})=>`${i} by ${a}: `+d.map(u=>`${OR(u)} ${u.kept} of ${u.roots} root(s)`).join(", ")+(c!==void 0&&c>0?`, and ${c} more value(s)`:""));n.push(`strata: ${s.join("; ")} (the records under the roots are not stratified)`)}return n}function SR(r,e){let{source:t,target:n}=e,o=r.objects.reduce((c,u)=>c+u.sourceRows,0)+r.noRecordDrawn.reduce((c,u)=>c+u.sourceRows,0),s=r.roots?bm({...r.roots,strata:gR(r.roots.strata)}):[],i=[`sample: ${r.rows} of ${o} record(s) of ${t}, of ${r.objects.length} object(s): ${ti(r.share)} % of the roots ${Rm(r.roots)?"in the draw ":""}of each object (${[gc(r),...s].join("; ")}), with the records they reach and name; ${yR(r,n)}; ${mR(r,t,n)}`];for(let c of r.objects){let u=(c.childrenCut??[]).map(({field:f,rows:p})=>`${f} ${p}`),l=(r.partialMasters??[]).filter(f=>f.objectApiName===c.objectApiName);i.push(` ${c.objectApiName}: ${c.kept} of ${c.sourceRows} (${RR(c,r.whole)})`+(u.length>0?`; left by the cap of ${r.children} children a record, by the lookup naming their parent: ${u.join(", ")}`:"")+l.map(f=>`; ${wR(f)}`).join(""))}if(i.push(...kR(r,t)),r.whole.length>0&&i.push(`whole: ${r.whole.map(({objectApiName:c,why:u})=>`${c} (${Om[u]})`).join(", ")}`),r.newestByIds&&r.newestByIds.length>0&&i.push(`newest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.newestByIds.join(", ")}`),r.oldestByIds&&r.oldestByIds.length>0&&i.push(`oldest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.oldestByIds.join(", ")}`),r.heavyRoots.length>0){i.push(`heavy roots set aside, each bringing in more than a tenth of the room ${n} has:`);for(let{objectApiName:c,id:u,rows:l,relation:f}of r.heavyRoots)i.push(` ${c} ${u}: ${l} record(s) through ${f.objectApiName}.${f.field}`)}if(r.dropped.length>0){i.push("not in the sample, never sent:");for(let{objectApiName:c,rows:u,reason:l}of r.dropped)i.push(` ${c}: ${u}, ${bR(l,t,n)}`)}if(r.leftEmpty.length>0){i.push("left empty, their record outside the sample:");for(let{objectApiName:c,field:u,rows:l}of r.leftEmpty)i.push(` ${c}.${u}: ${l} record(s)`)}if(r.noRecordDrawn.length>0){i.push(`no record drawn, ${t} holding some:`);for(let{objectApiName:c,sourceRows:u,noRootInTheDraw:l}of r.noRecordDrawn)i.push(` ${c}: ${u} in ${t}`+(l?", none of its roots in the draw":""))}let{plan:a}=r,d=a.drawnBy==="run"?"by this run":e.dryRun?e.replayed===!0?"by a dry run, said again by this one (--fit-plan)":"by this dry run":"by a dry run, written by this run (--fit-plan)";return i.push(`sample plan: ${a.path} (sha256 ${a.sha256}, drawn ${a.drawnAt} ${d})`,` drawing it sent ${r.planRequests.source} request(s) to ${t}`+(e.dryRun&&a.drawnBy==="dryRun"?`; --fit-plan ${a.path} writes these records, within a day`:"")),i}function Jg(r){let{budget:e,plan:t}=r;return{seed:r.seed,draw:r.draw,share:r.share,floor:r.floor,parents:r.parents,children:r.children,budget:{bytes:hc(e)?e.bytes:null,...e.remainingMB!==void 0?{remainingMB:e.remainingMB}:{},...e.maxMB!==void 0?{maxMB:e.maxMB}:{},...e.share!==void 0?{share:e.share}:{},...e.roundingMB!==void 0?{roundingMB:e.roundingMB}:{},...e.automationMB!==void 0?{automationMB:e.automationMB}:{},...e.withinMB!==void 0?{withinMB:e.withinMB}:{},...e.maxTotal!==void 0?{maxTotal:e.maxTotal}:{},limitedBy:e.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(n=>({objectApiName:n.objectApiName,sourceRows:n.sourceRows,kept:n.kept,roots:n.roots,below:n.below,asParents:n.asParents,...n.whole?{whole:!0}:{},...n.childrenCut&&n.childrenCut.length>0?{childrenCut:n.childrenCut.map(({field:o,rows:s})=>({field:o,rows:s}))}:{},...n.rootsInTheSource!==void 0?{rootsInTheSource:n.rootsInTheSource}:{},...n.rootsInTheDraw!==void 0?{rootsInTheDraw:n.rootsInTheDraw}:{}})),whole:r.whole.map(({objectApiName:n,why:o})=>({objectApiName:n,why:o})),heavyRoots:r.heavyRoots.map(({objectApiName:n,id:o,rows:s,relation:i})=>({objectApiName:n,id:o,rows:s,relation:{objectApiName:i.objectApiName,field:i.field}})),dropped:r.dropped.map(({objectApiName:n,rows:o,reason:s})=>({objectApiName:n,rows:o,reason:s})),leftEmpty:r.leftEmpty.map(({objectApiName:n,field:o,rows:s})=>({objectApiName:n,field:o,rows:s})),noRecordDrawn:r.noRecordDrawn.map(({objectApiName:n,sourceRows:o,noRootInTheDraw:s})=>({objectApiName:n,sourceRows:o,...s?{noRootInTheDraw:!0}:{}})),...r.roots?{roots:{...r.roots.window?{window:{...r.roots.window}}:{},...r.roots.notWindowed?{notWindowed:[...r.roots.notWindowed]}:{},...r.roots.where?{where:r.roots.where.map(({objectApiName:n,where:o})=>({objectApiName:n,where:o}))}:{},...r.roots.strata?{strata:r.roots.strata.map(({objectApiName:n,field:o,values:s,more:i})=>({objectApiName:n,field:o,values:s.map(a=>({...a})),...i!==void 0?{more:i}:{}}))}:{}}}:{},partialMasters:(r.partialMasters??[]).map(n=>({...n})),...r.newestByIds&&r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{},...r.oldestByIds&&r.oldestByIds.length>0?{oldestByIds:[...r.oldestByIds]}:{},planRequests:{source:r.planRequests.source},plan:{path:t.path,sha256:t.sha256,drawnAt:t.drawnAt,drawnBy:t.drawnBy,...t.drawnAgain?{drawnAgain:t.drawnAgain}:{}}}}function TR(r){return{seed:r.seed,draw:r.draw,share:r.share,sha256:r.sha256,drawnAt:r.drawnAt,...r.roots?{roots:structuredClone(r.roots)}:{},objects:r.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:!0}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...r.leftEmpty&&r.leftEmpty.length>0?{leftEmpty:r.leftEmpty.map(({objectApiName:e,field:t,rows:n})=>({objectApiName:e,field:t,rows:n}))}:{}}}function AR(r,e){let t=r.roots,n=t?[...t.window?[ym(t.window)]:[],...t.whereObjects&&t.whereObjects.length>0?[`the roots of ${t.whereObjects.join(", ")} filtered`]:[],...t.strataFields&&t.strataFields.length>0?[`stratified by ${t.strataFields.join(", ")}`]:[]]:[],o=t?.window!==void 0||(t?.whereObjects??[]).length>0?"in the draw ":"",s=[`sample (${[gc(r),...n].join("; ")}, ${ti(r.share)} % of the roots ${o}of each object; plan sha256 ${r.sha256}, drawn ${r.drawnAt}):`];for(let i of r.objects){let a=i.whole?"copied whole":`${i.roots} drawn, ${i.below} under a parent, ${i.asParents} as parents`;s.push(` ${i.objectApiName}: ${i.written} written of ${i.kept} in the sample (${a}) of ${i.sourceRows} in ${e}`+(i.goneSinceTheSample>0?`; ${i.goneSinceTheSample} gone from ${e} since the sample, not written`:"")+(i.changedSinceTheSample>0?`; ${i.changedSinceTheSample} changed since the sample: a record they cannot be written without is no longer the one the plan named, held back (failed)`:""))}for(let{objectApiName:i,field:a,rows:d}of r.leftEmpty??[])s.push(` left empty, their record outside the sample: ${i}.${a} ${d}`);return s}function jR(r,e,t){let n=e.draw??yn.draw,o=e.maxTotal??Wn,s=new Set(Object.keys(e.rootWhere??{}).map(l=>l.toLowerCase())),i=l=>e.window!==void 0||s.has(l.toLowerCase()),a=0;for(let l of r.nodes){if(!l.included||l.recordCount<=0)continue;let f=n==="uniform"?l.recordCount:Math.min(l.recordCount,o);a+=1+(i(l.objectApiName)?1:0)+Math.ceil(f/$R)}let d=n==="uniform"?"every root's id, spread over the org":`the ${n==="recent"?"newest":"oldest"} by creation date, those it may keep`,c=e.window!==void 0||s.size>0,u=n!=="uniform"&&(e.strata??[]).length>0;return Xr(`sample: drawing it reads at most about ${a} request(s) of ${t} for the roots, by discovery's counts (${d}`+(c?"; of the roots --fit-window and --fit-where leave, fewer than discovery's counts, each object they hold counted again without them":"")+")"+(u?", and a statement per value of each stratum, said once they are counted":"")+"; the records they reach and name are read on top, and said once drawn")}var $R=2e3,vR={counting:"counting the roots of each object",drawing:"reading the ids of the roots",closing:"closing the sample over the records they reach and name",fitting:"cutting it to what the target may take",saving:"keeping its plan"};function ER(r){let e;return t=>{t.step!==e&&(e=t.step,r(`sampling: ${vR[t.step]}\u2026 (${t.requests} request(s) so far)`))}}var IR=new Set([If,ls,"SAMPLE_DRAW_INVALID","ROOTS_QUERY_REFUSED","ROOTS_PLAN_MISMATCH","ROOTS_PLAN_GONE"]);function Qg(r){return IR.has(r)?2:1}function xR(r){let e=0,t=0,n=0,o=0;for(let s of r.nodes)s.included?e++:$r(s)?t++:s.status==="error"||s.errors.length>0?n++:o++;return{included:e,emptyTables:t,notCounted:n,leftOut:o}}function km(r){let e=[],t=[];for(let n of r.nodes)n.included&&n.recordCountUnknown===!0?t.push(n.objectApiName):!n.included&&!$r(n)&&(n.status==="error"||n.errors.length>0)&&e.push(n.objectApiName);return{refused:e,unanswered:t}}function _s(r,e){let{refused:t,unanswered:n}=km(r);return{nodes:r.nodes.length,...xR(r),...t.length>0?{notCountedObjects:t}:{},...n.length>0?{uncountedObjects:n}:{},edges:r.edges.length,waves:e.waves.length,cycles:e.cycleResolutions.length,truncated:r.truncated??!1}}function PR(r){return[...r.nodes].sort((e,t)=>e.objectApiName.localeCompare(t.objectApiName)).map(e=>({objectApiName:e.objectApiName,recordCount:e.recordCount,depth:e.level,included:e.included}))}function Yg(r,e,t,n,o={}){let s=FR(r,e,o);return{...s?{roots:s}:{rootRecordId:r.record},rootObjectApiName:s?.objectApiName??e.nodes[0]?.objectApiName??"",dryRun:r.dryRun,recordTypeMappings:t,maxRecordsPerObject:r.maxRecordsPerObject,referenceFallback:"nullify",upsertMode:r.upsert?"auto":void 0,expandOrphanParents:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphanParentExpansions:r.maxOrphans}:{},fieldExclusions:Object.keys(r.fieldExclusions).length>0?r.fieldExclusions:void 0,excludedObjects:r.excludedObjects.length>0?r.excludedObjects:void 0,ownerMappings:Object.keys(r.ownerMappings).length>0?r.ownerMappings:void 0,objectSoqlFilters:Object.keys(r.objectSoqlFilters).length>0?r.objectSoqlFilters:void 0,fieldMappings:Object.keys(r.fieldMappings).length>0?r.fieldMappings:void 0,anonymization:Os(r.anonymize,e,r.anonymizationRules,n),keepContactPoints:r.keepContactPoints,decisions:r.decisions,files:r.files?{maxFileBytes:r.files.maxFileSizeMB*1048576,acceptedAsIs:r.files.acceptedAsIs}:void 0,stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}}}function FR(r,e,t={}){let n=r.roots;return n?{objectApiName:(e.nodes.find(s=>s.level===0)??e.nodes[0])?.objectApiName??n.query?.objectApiName??"",...n.query?{query:{...n.query.roots}}:{ids:[...n.ids??[]]},cap:n.cap,...n.readTotal!==void 0?{readTotal:n.readTotal}:{},...t.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t.plan?{plan:t.plan}:{},...t.keepAt!==void 0?{keepAt:t.keepAt}:{},...t.chosen&&n.query?{chosen:t.chosen}:{}}:void 0}async function CR(r,e,t){let n=r.roots?.query;if(!n||r.resume!==void 0||t||r.listObjects)return;let{objectApiName:o,roots:s}=n,i=r.roots?.cap??kr,a;try{a=await e(Qo(o,s,r.objectSoqlFilters[o],i))}catch{return}let d=[...new Set(a.flatMap(u=>typeof u.Id=="string"?[u.Id]:[]))],c=d.length>i?Br(o,i,"query",s):d.length===0?Xo(o,s,i):void 0;return c?{refused:{code:c.code,message:c.message}}:{chosen:{ids:d,readAt:new Date().toISOString()}}}function NR(r,e){return e?{...r,stream:{...r.stream,store:e,summaryBound:Wp}}:r}function MR(r,e){if(!e)return r;let t=new Map(e.map(n=>[n.objectApiName,n.fieldNames]));return{...r,nodes:r.nodes.map(n=>{let o=t.get(n.objectApiName);if(!o)return n;let s=new Set(n.piiFields);return{...n,anonymizeFields:o.filter(i=>s.has(i))}})}}function ni(r){return new lf({query:async(e,t)=>Ln({query:async n=>r.query(n),queryMore:async n=>r.queryMore(n)},t),toolingQuery:async(e,t)=>Ln({query:async n=>r.tooling.query(n),queryMore:async n=>r.tooling.queryMore(n)},t),toolingQueries:async(e,t)=>uf(await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(cf(`/services/data/v${r.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length),toolingRetrieves:(e,t)=>ma(r)(t)})}function BR(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return new af({query:async(o,s)=>Ln({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s),toolingQuery:async(o,s)=>Ln({query:async i=>n(o).tooling.query(i),queryMore:async i=>n(o).tooling.queryMore(i)},s),describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`),a=await e(o,s);return{sent:i,createable:a.createable!==!1,fields:a.fields.map(ha)}},readDuplicateRules:async(o,s)=>{let i=await n(o).metadata.read("DuplicateRule",s);return Array.isArray(i)?i:[i]},readLimits:async o=>n(o).request({method:"GET",url:"/limits"}),toolingQueries:async(o,s)=>sf(n(o))(s),toolingRetrieves:(o,s)=>ma(n(o))(s)})}async function un(r){let t=(await r.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof t?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(t.IsSandbox===!0)return{id:t.Id,sandbox:!0};try{let o=(await r.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof o=="string"&&o!==""?{id:t.Id,sandbox:!1,edition:o}:{id:t.Id,sandbox:!1}}catch{return{id:t.Id,sandbox:!1}}}function Zr(r,e,t){if(e.sandbox||Uc(e.edition))return;let n=t==="clone"?"sandforge clone writes to sandboxes and Developer Edition orgs only. Nothing was written; --dry-run, which only reads, runs against it.":"sandforge clone removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.",o=e.edition?`IsSandbox false, edition ${e.edition}`:"IsSandbox false, and no edition";return`${r} is a production org (its Organization record says ${o}): ${n}`}var LR={parent_refused:"a record it names was refused",beyond_a_call:"the records it needs are more, or deeper, than one call holds",call_budget:"the calls ran out before its turn"};function WR(r,e){let t=r.updates.reduce((n,o)=>n+o.updates,0);return[`rehearsal: ${r.sampled} of the ${r.rows} record(s) the run would create, created in ${e} and rolled back with each call`,...t>0?[` and ${t} update(s) the run makes after its inserts, each in the call that creates its record: ${r.updates.map(n=>`${n.objectApiName} ${n.updates}`).join(", ")}`]:[],` ${r.calls} composite call(s), ${r.maxCalls} at most if a call stops at a refused record`,...r.objects.map(({objectApiName:n,rows:o})=>` ${n.padEnd(40)} ${o}`)]}function DR(r,e,t={}){let n=r.updatesJudged>0?`; ${r.updatesJudged} update(s) judged, ${r.updatesPassed} would save, ${r.updatesJudged-r.updatesPassed} refused`:"",o=r.linked??0,s=o>0?`${o} linked to a record the target holds, `:"",i=[`rehearsed in ${e}: ${r.judged} judged, ${r.passed} would save, ${s}${r.judged-r.passed-o} refused, ${r.notJudged} not judged${n} (${r.calls} call(s), every write rolled back)`];for(let a of r.gaps){let d=typeof a.detail?.statusCode=="string"?a.detail.statusCode:a.value,c=a.field?`.${a.field}`:"",u=a.kind==="picklist_value_refused"&&a.value?` "${a.value}"`:"",l=a.recordType?` (record type ${a.recordType})`:"",f=a.detail?.rowsOfTheRun,p=typeof f=="number"&&f>a.rows?`, ${f} in the run`:"";if(a.kind==="rehearsal_update_refusal"){i.push(` refused on update ${a.objectApiName}${c}: ${d}, ${a.rows} update(s)${p} (the record goes in without what the update gives it)`);continue}let h=lo(a,t.lifted);if(h){i.push(` refused ${a.objectApiName}${c}: ${d}, ${a.rows} row(s)${p}, validation rule "${String(a.detail?.rule)}": the mute lifts it (${h.permission}, in ${h.permissionSet}), which the rehearsal ran without; a real run under it writes the row whole`);continue}i.push(` ${a.severity==="blocking"?"REFUSED":"refused"} ${a.objectApiName}${c}${u}${l}: ${d}, ${a.rows} row(s)${p}`+(a.detail?.writtenWithoutTheField===!0?" (a real run writes it again without the field)":"")+(a.detail?.linkedToTheRecordItNames===!0?" (a real run links it to the record the target holds)":""))}for(let{objectApiName:a,rows:d,reason:c}of r.notJudgedWhy)i.push(` not judged ${a}: ${d} row(s), ${LR[c]}`);return r.updatesNotRehearsed>0&&i.push(` not rehearsed: ${r.updatesNotRehearsed} of the ${r.updates} update(s) the run makes after its inserts`),i}function _R(r,e){return{...r,gaps:r.gaps.map(t=>{let n=lo(t,e);return n?{...t,detail:{...t.detail,liftedByPermission:n.permission,liftedByPermissionSet:n.permissionSet}}:t})}}var qR=new Set(["--remove","--target","--preview","--include-changed","--json","--accept-automation","--leave-undeletable","--sweep","--sweep-list","--sweep-late","--sweep-untied","--audit","--mute-automation","--sweep-user"]),UR=new Set(["--remove","--target","--audit","--sweep-user"]);function GR(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(fc),process.exit(0));let t=c=>{let u=e.indexOf(c),l=u>=0?e[u+1]:void 0;return l!==void 0&&!l.startsWith("--")?l:void 0},n=c=>e.includes(c);for(let c=0;c<e.length;c++){let u=e[c];if(UR.has(u)){e[c+1]!==void 0&&!e[c+1].startsWith("--")&&c++;continue}u==="--dry-run"&&(process.stderr.write(`--remove does not take --dry-run: a removal that did not read it would delete for real. --preview says what the removal would do, and writes nothing. Run with --help for usage.
|
|
845
|
-
`),process.exit(2)),qR.has(u)||(process.stderr.write(`--remove takes --target, --preview, --include-changed, --accept-automation, --mute-automation, --leave-undeletable, --sweep, --sweep-late, --sweep-untied, --sweep-list, --sweep-user, --json and --audit, not "${u}". Run with --help for usage.
|
|
846
|
-
`),process.exit(2))}let o=t("--remove"),s=t("--target");(!o||!s)&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, and --target the org the run wrote to. Run with --help for usage.
|
|
847
|
-
`),process.exit(2)),n("--sweep")&&n("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help for usage.
|
|
848
|
-
`),process.exit(2));let i=["--sweep-list",...n("--sweep")?[]:Pm,"--audit"].filter(c=>n(c));n("--preview")&&i.length>0&&(process.stderr.write(`--preview writes nothing: give it without ${i.join(", ")}. Run with --help for usage.
|
|
849
|
-
`),process.exit(2));let a=lO(e);"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help for usage.
|
|
850
|
-
`),process.exit(2));let d=zR(t("--sweep-user"),n("--sweep-user"),{sweeps:n("--sweep")||n("--sweep-list")});return{summaryPath:o,target:s,includeChanged:n("--include-changed"),json:n("--json"),acceptAutomation:n("--accept-automation"),muteAutomation:n("--mute-automation"),leaveUndeletable:n("--leave-undeletable"),sweep:n("--sweep"),sweepList:n("--sweep-list"),...a,audit:pc(e),...n("--preview")?{preview:!0}:{},...d!==void 0?{sweepUser:d}:{}}}function zR(r,e,t){if(e)return t.sweeps||(process.stderr.write(`--sweep-user goes with --sweep or --sweep-list: it names the user the run wrote as, whose records the sweep looks for. Run with --help for usage.
|
|
851
|
-
`),process.exit(2)),(r===void 0||!pr.test(r)||!r.startsWith("005"))&&(process.stderr.write(`--sweep-user takes the id of a user, 005 and 12 or 15 more letters and digits, not "${r??""}". Run with --help for usage.
|
|
852
|
-
`),process.exit(2)),r}function oc(r,e){if(!(r===void 0||e.kept||e.given)&&/user the run wrote as|different users/.test(r))return` --sweep-user <id> names the user the run wrote as, which its summary does not keep: "sf org display user --target-org ${e.target}" gives the id of the user sf signs in as, the one a run of this machine wrote as`}var ut=M.string().regex(pr,"not a Salesforce id"),Us=M.iso.datetime(),Xg=M.object({objectApiName:M.string().regex(tt,"not an API name"),kind:M.enum(["flow","trigger","process","workflowRule"]),name:M.string().max(255)}),HR=M.object({silenced:M.array(Xg.extend({permission:M.string().max(255)})),stillRan:M.array(Xg.extend({why:M.enum(["noBypass","managedPackage","notRead","noPermissionSet"])}))});function XA(...r){for(let e of r)if(typeof e=="string"&&pr.test(e))return e}var Sm=M.object({tool:M.literal("sandforge-clone"),version:M.literal(1),source:M.string(),target:M.string().min(1),targetOrgId:ut.optional(),record:M.string().optional(),objects:M.array(M.object({objectApiName:M.string().regex(tt,"not an API name"),where:M.string().max(512).optional()})).max(2e3).optional(),wholeOrg:M.literal(!0).optional(),roots:M.object({objectApiName:M.string().regex(tt,"not an API name"),from:M.enum(["query","records"])}).optional().catch(void 0),dryRun:M.literal(!1),elapsedMs:M.number().transform(r=>Math.max(0,r)),finishedAt:Us.optional(),journal:M.string().min(1).max(4096).optional(),part:M.number().int().nonnegative().optional(),result:M.object({remapInJournal:M.literal(!0).optional(),roots:M.object({read:M.number().int().nonnegative()}).optional().catch(void 0),remapTable:M.record(ut,ut),existingSourceIds:M.array(ut),updatedSourceIds:M.array(ut),createdByObject:M.array(M.object({objectApiName:M.string().regex(tt,"not an API name"),sourceIds:M.array(ut)})),withTheirRecordSourceIds:M.array(ut).optional(),unattributed:M.array(M.object({objectApiName:M.string().regex(tt,"not an API name"),ids:M.array(ut)})).optional(),writtenBetween:M.object({first:Us,last:Us}).optional(),mayHaveBeenWritten:M.array(M.object({objectApiName:M.string().regex(tt,"not an API name"),sourceIds:M.array(ut)})).optional(),runUserId:ut.optional()}),mutedAutomation:HR.optional().catch(void 0)});async function sc(r,e,t,n=Pt(kt())){let o=e.indexOf(`
|
|
853
|
-
`),s=o>=0?e.slice(0,o):e;if(/^\{"run":/.test(s))return KR(r,t,n);let i=VR(e);if("refusal"in i)return i;let{journal:a,part:d}=i.summary,c=a!==void 0&&d!==void 0?await n.readAt(a,d):void 0;if(!c){if(!i.summary.result.remapInJournal)return i;let u=(i.summary.objects??[]).map(l=>l.objectApiName);return a===void 0||d===void 0?{refusal:"keeps the ids of its records in a journal it does not name. "+Zg(t,u)}:{refusal:`keeps the ids of its records in ${a}, which cannot be read. `+Zg(t,u)}}return{summary:{...i.summary,result:{...i.summary.result,remapTable:c.remap.table,existingSourceIds:c.remap.linked,updatedSourceIds:[],createdByObject:c.remap.createdByObject,...c.remap.withTheirRecord?{withTheirRecordSourceIds:c.remap.withTheirRecord}:{},...c.unattributed?{unattributed:c.unattributed}:{}}}}}function Zg(r,e=[]){let t=e.length>0?e.join(","):"<its objects>";return`Its records can no longer be removed or verified from here. A checkpoint taken before the run takes ${r} back: ${Ut("checkpoint")} list --org ${r} names them, ${Ut("checkpoint")} rewind --org ${r} --checkpoint <id> rewinds to one. Without one, ${Ut("empty")} --target ${r} --objects ${t} --dry-run says what emptying its objects would delete: every record of them, not only the run's.`}async function KR(r,e,t){let n=await t.readAt(r,"all");if(!n)return{refusal:"is not the journal of a run."};let s=(await t.lastEndAt(r))?.at??dm(r).mtime.toISOString(),i=Date.parse(s)-Date.parse(n.startedAt),a=n.resume?.startedWith,d=n.resume?.recordId??a?.config.recordId,c=n.roots??(a?.config.queryScope==="records"?{}:void 0),u=n.roots?.objectApiName??a?.graph.nodes.find(g=>g.level===0)?.objectApiName,l=c&&u!==void 0?{objectApiName:u,from:a?.config.inputMode==="soql"||n.roots?.query!==void 0?"query":"records"}:void 0,f=!d&&a?.config.inputMode==="org",p=!d&&!c&&a&&(a.config.inputMode==="soql"||f)?a.graph.nodes.filter(g=>g.included).map(({objectApiName:g})=>{let m=a.config.objectSoqlFilters?.[g];return m!==void 0?{objectApiName:g,where:m}:{objectApiName:g}}):void 0,h=Sm.safeParse({tool:"sandforge-clone",version:1,source:n.resume?.sourceOrgId??"",target:e,targetOrgId:n.targetOrgId,record:d??(p?void 0:""),...p?{objects:p}:{},...f?{wholeOrg:!0}:{},...l?{roots:l}:{},dryRun:!1,elapsedMs:Number.isFinite(i)&&i>0?i:0,finishedAt:s,journal:r,result:{...n.roots?{roots:{read:n.roots.ids.length}}:{},remapTable:n.remap.table,existingSourceIds:n.remap.linked,updatedSourceIds:[],createdByObject:n.remap.createdByObject,...n.remap.withTheirRecord?{withTheirRecordSourceIds:n.remap.withTheirRecord}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.unattributed?{unattributed:n.unattributed}:{}}});return h.success?{summary:h.data}:{refusal:`is a journal the command cannot take a run back from: ${h.error.issues.slice(0,5).map(m=>`${m.path.map(String).join(".")||"the journal"}: ${m.message}`).join("; ")}.`}}function VR(r){let e;try{e=JSON.parse(r)}catch(a){return{refusal:`is not JSON (${a instanceof Error?a.message:String(a)}).`}}let n=M.object({tool:M.literal("sandforge-clone"),dryRun:M.boolean()}).safeParse(e);if(!n.success)return{refusal:"is not a summary sandforge clone printed with --json."};if(n.data.dryRun)return{refusal:"is the summary of a dry run, which wrote nothing to the target: there is nothing of it to remove."};let o=$i(e,"sandforge-clone");if(o)return{refusal:vi(o)};if(!M.object({result:M.object({createdByObject:M.array(M.unknown())})}).safeParse(e).success)return{refusal:"does not say which records the run created (createdByObject): it was printed before the summary said so, and the records the run created cannot be told from those the target already held. sandforge cleanup remains for such a run."};let i=Sm.safeParse(e);return i.success?{summary:i.data}:{refusal:`is not a summary a removal can read: ${i.error.issues.slice(0,5).map(d=>`${d.path.map(String).join(".")||"the summary"}: ${d.message}`).join("; ")}.`}}function mc(r){let{result:e}=r,t=zc({idRemapTable:e.remapTable,idRemapExisting:[...e.existingSourceIds,...e.updatedSourceIds],idRemapCreated:e.createdByObject});return Dp(t,e.unattributed)}function Tm(r){return`${Am(r)} record(s) the target already held, which the run linked to or wrote over, stay`}function Am(r){return Hc({idRemapTable:r.result.remapTable,idRemapExisting:r.result.existingSourceIds,idRemapCreated:r.result.createdByObject,idRemapWithTheirRecord:r.result.withTheirRecordSourceIds}).length+r.result.updatedSourceIds.length}function JR(r,e,t){let n=e.reduce((s,i)=>s+i.ids.length,0),o=r.result.writtenBetween?.last??r.finishedAt;return[`the clone of ${Jy(Vy(r))} wrote to ${t.target}${o?` until ${o}`:""}; a removal deletes the ${n} record(s) it created, children first:`,...e.map(s=>` ${s.objectApiName}: ${s.ids.length}`),...YR(e),Tm(r),t.includeChanged?"records changed since the run go too, and what was added to them since":`records changed since the run stay, as do those records added since depend on (${at("--include-changed","removal")} takes them)`]}function QR(r){return r.flatMap(({part:e,plan:t})=>[`then the ${qn(t).length} record(s) of the run's part ${e.part} (its summary's "part") an earlier --remove of that part left, once these are gone:`,...t.map(n=>` ${n.objectApiName}: ${n.ids.length}`)])}function YR(r){let e=new Set(r.filter(n=>n.ids.length>0).map(n=>n.objectApiName)),t=e.has("QuoteLineItem")||e.has("OpportunityLineItem");return!e.has("Quote")||!t?[]:[" and the lines the platform copied between a quote the run synced and its opportunity, read as the removal begins and counted apart (--preview counts them)"]}function jm(r){let e=r.platformCopies??0;if(e<=0)return"";let t=r.planned-e;return r.objectApiName===_o?` (${t>0?`${t} the run wrote, and `:""}${e} the target's duplicate rules made of the run's records)`:` (${t} the run wrote, and ${e} the platform copied between the quote the run synced and its opportunity)`}function XR(r,e="run"){let t=r.tookAlong,n=r.cameAlong;return[...t&&t.count>0?[` took along ${t.count} record(s) that were not the ${e}'s, added or changed since it: ${t.objects.join(", ")}`]:[],...n&&n.count>0?[` took along ${n.count} record(s) the ${e} did not write that came with its records, made as it wrote: ${n.objects.join(", ")}`]:[]]}function ZR(r){return[r.deleted>0?`${r.deleted} deleted`:"",r.alreadyGone>0?`${r.alreadyGone} already gone`:"",(r.notVisible??0)>0?`${r.notVisible} not visible to this user (neither found nor in the recycle bin)`:"",r.keptChanged>0?`${r.keptChanged} kept, changed since the run`:"",r.keptDependents>0?`${r.keptDependents} kept for records that stay`+(r.heldBy.length>0?` (${r.heldBy.join(", ")})`:""):"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean).join(", ")}function eO(r){let e=r.count>r.names.length?", \u2026":"";return`${r.count} file(s) attached to them stay in the org, as the run did not create them: ${r.names.join(", ")}${e}`}function tO(r,e,t=0){let n=[...new Set(e.flatMap(o=>o.unchecked))];return[`removal: ${r.toUpperCase()}`,...e.flatMap(o=>[` ${o.objectApiName}: ${ZR(o)||"nothing"} of ${o.planned}${jm(o)}`,...XR(o),...o.reasons.map(s=>` ${s}`),...o.filesLeft&&o.filesLeft.count>0?[` ${eO(o.filesLeft)}`]:[]]),...n.length>0?[`not checked, deleted with their parent: ${n.join(", ")}`]:[],...t>0?[`not reachable: ${t} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned`]:[]]}function $m(r){let e=r.automationGaps;return e?[...e.error?[` the target's automation could not all be read (${e.error}): what it creates may be missed`]:[],...e.flowsNotRead>0?[` ${e.flowsNotRead} flow(s) on the run's objects not read: what they create is not looked at`]:[],...e.triggers>0?[` ${e.triggers} Apex trigger(s) on the run's objects: what they create no metadata says`]:[]]:[]}function vm(r){return[...r.unread.map(e=>` not looked at: ${e.objectApiName}: ${e.reason}`),...r.handWork.map(e=>` created by the run's user in the window, where neither the run nor its automation writes: ${e.objectApiName}: ${e.count} (left)`)]}var em=10;function wc(r,e,t=!1){return St("--max-total")?`The run would write ${r} records, more than --max-total ${e}: narrow the clone (--max, --exclude-object, --filter), or raise --max-total.`:ys()?t&&Kt()?`The run would write ${r} records, more than the ${e} the resource's maxTotal holds it to: narrow the resource in the file, or raise its maxTotal.`:`The run would write ${r} records, more than the ${e} its plan counted: the source holds more records than when it was planned. Plan again.`:`The run would write ${r} records, more than the ${e} ${at("--max-total")} holds it to: narrow the clone with this script's own --max, --exclude-object or --filter, or raise its --max-total.`}function ln(r){return St(r)?r:`this script's own removal with ${r==="--sweep-list"||r==="--sweep"?"":"--sweep "}${r}`}function ic(r){let e=Ua();return e===void 0?`${r} takes them`:`${e} keeps them; ${ln(r)} takes them`}function Js(r){let e=r.length-em;return`${r.slice(0,em).join(", ")}${e>0?` and ${e} more`:""}`}function Hn(r){return r.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}function nO(r,e){let t=r.changed??0;return[r.made>0?`${r.made} made for the run`+((r.sameSave??0)>0?` (${r.sameSave} in the same save)`:""):"",r.madeOver>0?`${r.madeOver} under records the run wrote over`:"",r.late>0?`${r.late} late`:"",r.untied>0?`${r.untied} tied to nothing of the run`:"",t>0?`${t} of them changed since the run${e.includeChanged===!0?"":", kept"}`:""].filter(Boolean).join(", ")}function Qr(r,e,t){return r[e]-(t.includeChanged===!0?0:r.changedIn?.[e]??0)}function rO(r,e){let t=e.sweepUntied===!0&&r.untied?.refusal===void 0;return r.found.reduce((n,o)=>{let s=o.classes;return s?n+Qr(s,"made",e)+Qr(s,"madeOver",e)+(e.sweepLate===!0?Qr(s,"late",e):0)+(t?Qr(s,"untied",e):0):n},0)}function tm(r,e,t,n){return t.flatMap(o=>{let s=r.found.find(a=>a.objectApiName===o.objectApiName)?.classes,i=s?Math.min(o.count,Qr(s,e,n)):o.count;return i>0?[{objectApiName:o.objectApiName,count:i}]:[]})}function oO(r,e,t){let n=[],o=r.late??[];if(o.length>0&&e.sweepLate!==!0)n.push(`kept, made late \u2014 tied to the run but created more than a minute after the record it hangs from, or by the org's Automated Process user: ${Hn(o)} (${ic("--sweep-late")})`);else if(t&&e.sweepLate===!0){let i=tm(r,"late",o,e);n.push("of what it would delete, made late, which --sweep-late takes: "+(i.length>0?Hn(i):o.length>0?"none":"none found"))}let s=r.untied;if(s&&s.objects.length>0){if(s.refusal!==void 0)n.push(`kept, tied to nothing of the run: ${Hn(s.objects)} \u2014 --sweep-untied is refused: ${s.refusal}`);else if(e.sweepUntied!==!0)n.push(`kept, created as the run's user in its window but tied to nothing of it: ${Hn(s.objects)} (${ic("--sweep-untied")})`);else if(t){let i=tm(r,"untied",s.objects,e);n.push("of what it would delete, tied to nothing of the run, which --sweep-untied takes: "+(i.length>0?Hn(i):"none"))}}else t&&e.sweepUntied===!0&&n.push(s?.refusal!==void 0?`with --sweep-untied, it would delete nothing tied to nothing of the run: --sweep-untied is refused: ${s.refusal}`:"of what it would delete, tied to nothing of the run, which --sweep-untied takes: none found");if(r.notLooked&&r.notLooked.length>0&&n.push(`not looked at, past the ${rd} objects a sweep counts: `+Js(r.notLooked)),r.muted){let{silenced:i,stillRan:a}=r.muted;n.push(`the run's mute kept ${i.length} automation(s) quiet; `+(a.length>0?`what still ran may have made what is listed: ${Js(a.map(d=>`${d.name} (${d.objectApiName})`))}`:"nothing of what the run fired still ran"))}return t&&n.push(...sO(r,e)),n}function sO(r,e){let t=s=>r.found.some(i=>!i.overBound&&(i.classes?.[s]??0)>0),n=t("made")||t("madeOver"),o=[n?Em:"",e.sweepLate===!0&&t("late")?`under ${n?"them":"the run's records"} within a quarter of an hour with --sweep-late`:"",e.sweepUntied===!0&&r.untied?.refusal===void 0&&t("untied")?"anywhere in the run's window with --sweep-untied":""].filter(Boolean);return o.length===0?[]:[`${Im(`${o.join(", or ")}${o.length>1?",":""}`)}: check the names before a --sweep`]}var Em="under the run's records within a minute of them";function Im(r){return`a record made by hand as the run's user ${r} reads as the automation's, and one changed by hand before the run's last write as unchanged`}function Gs(r,e,t,n=t===void 0){let o=rO(r,t??{}),s=r.found.reduce((a,d)=>a+d.count,0),i=r.found.some(a=>a.overBound)?" or more":"";return[r.window?`a sweep looks in ${e} for what the run's user created from ${r.window.from} to ${r.window.to} that the run's id map does not hold, in: ${Js(r.looked)}`:`a sweep of ${e} cannot tell the window the run wrote in`,...r.found.length>0?[`it found ${s}${i} record(s) and would delete `+(o>0?`${o} of them, children first`:"none of them")+"; per object, all it found:",...r.found.map(a=>` ${a.objectApiName}: ${a.count}`+(a.overBound?" or more (over the bound: none would be deleted)":"")+(a.classes?` \u2014 ${nO(a.classes,t??{})}`:"")+(a.names.length>0?` (${a.names.join(", ")}${a.count>a.names.length?", \u2026":""})`:""))]:r.window?["it finds nothing to delete"]:[],...oO(r,t??{},n),...$m(r),...vm(r),...r.refusal?[`sweep refused: ${r.refusal}`]:[]]}function iO(r,e){let t=r?.listing;return e===void 0&&t?.refusal===void 0?t:void 0}function Xd(r,e){let t=r.reduce((g,m)=>g+(m.heldByAutomation??0),0);if(t===0)return[];let n=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAfterRun??0),0)),o=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAlong??0),0)),s=aO(t,o),i=[...new Set(r.flatMap(g=>g.automationHolders??[]))],a=i.length>0?` (${Js(i)})`:"",d=`likely by the target's automation${a}`,c=`delete them by hand, then remove the run again; ${at("--preview","removal")} says what of it their delete leaves changed since, which ${at("--include-changed","removal")} takes`;if(e.part===void 0&&e.sweep!==!0&&e.windowUntold===!0)return[`${t} record(s) of the run kept for records created under them as its user, within a minute of them, ${d}: a sweep cannot take them, as it cannot tell the window the run wrote in now \u2014 ${c}`];let u=e.part!==void 0?"that part's last write":e.inParts===!0?"the last write of the run's part that wrote them":"the run's last write",l=n===0?"during the run, as its user":n===t?`as its user after ${u}, within a minute of them`:`as its user during the run or, under ${n} of them, after ${u}, within a minute of them`,f=e.part===void 0?"of the run":`of the run's part ${e.part} (its summary's "part")`,p=`${t} record(s) ${f} kept for records created under them ${l}, `+(n===0?d:`by the target's automation or by hand${a}`),h=Im(Em);if(e.part!==void 0){let g=m=>`${Ua()===void 0?"--remove":"this script's own removal"} of part ${e.part}'s summary with ${m}`;return[`${p}: `+(e.sweep===!0?"this removal's sweep looked in its own part's window alone, and did not see them; ":"a sweep of this summary looks in its own part's window alone, and leaves them; ")+`${g("--sweep")} ${s} (${g("--sweep-list")} shows them; ${h}: check the names before it), or ${c}`]}return[e.sweep===!0?`${p}: the sweep left them \u2014 ${ln("--sweep-list")} says why; ${ln("--sweep-late")} takes those it lists as late, ${at("--include-changed","removal")} those changed after the run's last write`:`${p}: ${ln("--sweep")} ${s} (${ln("--sweep-list")} shows them); ${h}: check the names before `+(St("--sweep")?"a --sweep":ln("--sweep"))]}function aO(r,e){let t="the removal deletes those, and the org takes them along";return e<=0?"takes them first":e>=r?`takes them with the run's records they hang from: ${t}`:`takes them first, but for those under ${e} of the run's records, which go with them: ${t}`}var xm={late:"made late",untied:"tied to nothing of the run"};function dO(r){return r.map(({class:e,objects:t,option:n,refusal:o})=>{let s=` left, ${xm[e]}: ${Hn(t)}`;return o!==void 0?`${s} \u2014 ${n} is refused: ${o}`:`${s} (${ic(n)})`})}function cO(r){return[`sweep: ${r.status.toUpperCase()}`,...r.objects.flatMap(e=>{let t=e.afterRemoval??0,n=Math.min(e.afterRemovalUnder??0,t),o=e.withRemoval??0,s=[t-n>0?`${t-n} once the records of the run that point at them were gone`:"",n>0?`${n} once the removal was through: the org had not taken them along with the records of the run they hung from`:""].filter(Boolean),i=[e.deleted>0?`${e.deleted} deleted`+(s.length>0?` (${s.join("; ")})`:""):"",e.alreadyGone>0?`${e.alreadyGone} already gone`+(o>0?` (${o} with the records of the run they hung from, as the removal deleted those: the org took them along)`:""):"",e.keptChanged>0?`${e.keptChanged} kept, changed since the run`:"",(e.keptDependents??0)>0?`${e.keptDependents} kept for records that stay`+((e.heldBy??[]).length>0?` (${(e.heldBy??[]).join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:""].filter(Boolean).join(", ");return[` ${e.objectApiName}: ${i||"nothing"} of ${e.found}`,...e.reasons.map(a=>` ${a}`)]}),...dO(r.left??[]),...(r.goneAlong??[]).map(({class:e,objects:t})=>` ${xm[e]}, no longer in the org once the records of the run were gone: ${Hn(t)}`),...$m(r),...vm(r),...r.refusal?[` ${r.refusal}`]:[]]}function uO(r){return ri(r).flatMap(e=>[...qn(e.created),...e.linked])}function ri(r){let e=r?.part;return e===void 0?[]:(r?.parts??[]).filter(t=>t.part!==e)}function zs(r,e){let t=new Set(r?.earlier?.partsRemoved??[]);return ri(r).flatMap(n=>{let o=(e?.otherParts??[]).filter(({part:i})=>i===n.part).flatMap(({objects:i})=>i).reduce((i,a)=>i+a.count,0),s=qn(sn(n.created,r?.earlier?.removalLeft)).length+o;return s===0?[]:[`a sweep of this summary leaves the ${s} record(s) of the run's part ${n.part} (its summary's "part"), the run's own, never the target's automation's: `+(t.has(n.part)?"an earlier --remove of that part left them, which the removal of this summary takes up once its own records are gone":"--remove of that part's summary takes them")]})}async function ac(r,e,t,n,o,{signal:s,ofTheRun:i,user:a}={}){let d;try{d=await ni(r).read(e,n.map(l=>l.objectApiName))}catch(l){d={error:V(l)}}let c=t.result.runUserId??a,u=ri(i).map(({part:l,created:f})=>({part:l,created:f}));return{writtenBetween:t.result.writtenBetween,created:n,remap:new Set([...Object.values(t.result.remapTable),...uO(i)].map(l=>l.slice(0,15))),...u.length>0?{otherParts:u}:{},automation:sh(d),...c?{runUserId:c}:{},ties:o,...s?{signal:s}:{}}}var Pm=["--sweep-late","--sweep-untied"];function lO(r){let e=Pm.filter(t=>r.includes(t));return e.length>0&&!r.includes("--sweep")&&!r.includes("--sweep-list")?{refusal:`${e.join(" and ")} ${e.length===1?"takes":"take"} more of what --sweep lists: give ${e.length===1?"it":"them"} with --sweep, or with --sweep-list to see what ${e.length===1?"it":"they"} would take.`}:{...r.includes("--sweep-late")?{sweepLate:!0}:{},...r.includes("--sweep-untied")?{sweepUntied:!0}:{}}}function fO(r){return{...r.sweepLate?{sweepLate:!0}:{},...r.sweepUntied?{sweepUntied:!0}:{}}}function pO(r){return r?{sweep:e=>r.first(e),automationMade:r.automationMade,afterRemoval:e=>r.afterRemoval(e)}:{}}function dc(r,e,t){let n=Zn(r,e),o=Object.create(n);return o.counts=ih(bl(yl(r),t)),o}function ZA(r){let e=Date.parse(r.firstWrittenAt??r.startedAt),t=Date.parse(r.end?.at??r.lastWriteAt??r.lastWrittenAt??"");return Number.isFinite(e)&&Number.isFinite(t)?{from:e,to:Math.max(e,t)}:void 0}function Zd(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}async function hO(r){let e=r.journalDir??kt(),t=new Set(r.own.ids.map(c=>c.slice(0,15))),n=(c,u)=>!r.span||!Number.isFinite(c)||!Number.isFinite(u)||c<=r.span.to+oh&&u>=r.span.from-rh,o=[],s=c=>{c.length===0||c.some(u=>t.has(u.slice(0,15)))||o.push({ids:[...c]})},i=Ks(e,"forge-runs"),a=[];try{a=vy(i).filter(c=>c.endsWith(".ndjson"))}catch{}let d=Pt(e);for(let c of a){let u=Ks(i,c);if(!(r.own.journal!==void 0&&Dt(r.own.journal)===Dt(u)))try{let l=await d.headAt(u);if(!l||!Zd(l.targetOrgId,r.organizationId))continue;let f=await d.lastEndAt(u),p=Date.parse(f?.at??"")||dm(u).mtimeMs;if(!n(Date.parse(l.startedAt),p))continue;let h=await d.readAt(u,"all");s(h?.created.flatMap(g=>g.ids)??[])}catch{}}for(let c of r.own.otherParts??[])n(c.from,c.to)&&s(c.ids);for(let c of[Zi(e),Zi(e,fh)]){let u=[];try{u=await c.list()}catch{continue}for(let l of u){if(r.own.runId!==void 0&&l.runId===r.own.runId||!(Zd(l.targetOrganizationId,r.organizationId)||l.targetOrganizationId===void 0&&(Zd(l.targetOrgId,r.organizationId)||r.alias!==void 0&&l.targetOrgId===r.alias)))continue;let p=Date.parse(l.firstWrittenAt??l.startedAt),h=l.end?Date.parse(l.end.at):Date.parse(l.lastWriteAt??l.lastWrittenAt??"")||Date.now();n(p,h)&&s([...l.created,...l.overwritten??[]].flatMap(g=>g.ids))}}return o}function gO(r){let e=r.removalSpans?.map(t=>t.first).filter(t=>Number.isFinite(Date.parse(t))).sort((t,n)=>Date.parse(t)-Date.parse(n))[0];return{otherRuns:r.otherRuns,...r.muted?{muted:{silenced:r.muted.silenced,stillRan:r.muted.stillRan}}:{},...e!==void 0?{removalBegan:e}:{},...r.made&&r.made.length>0?{madeEarlier:r.made}:{},...r.late&&r.late.length>0?{lateEarlier:r.late}:{}}}async function Fm(r,e,t,n,o,s){let i=Date.parse(t.finishedAt??""),a=ri(s).map(d=>({ids:qn(d.created),from:Date.parse(d.startedAt??""),to:Date.parse(d.endedAt??"")}));return gO({otherRuns:await hO({organizationId:r,alias:e,span:Number.isFinite(i)?{from:i-t.elapsedMs,to:i}:void 0,own:{...t.journal!==void 0?{journal:t.journal}:{},ids:n.flatMap(d=>d.ids),...a.length>0?{otherParts:a}:{}}}),...t.mutedAutomation?{muted:t.mutedAutomation}:{},...o?{removalSpans:o.removalSpans}:{},...o?.made?{made:o.made}:{},...o?.late?{late:o.late}:{}})}var nm=3;function oi(r){return/\.json$/i.test(r)?r.replace(/\.json$/i,".removals.json"):`${r}.removals.json`}function si(r){let e=r.flatMap(t=>t.ids.map(n=>n.slice(0,15))).sort();return $y("sha256").update(e.join(",")).digest("hex")}var ec=M.string().refine(r=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/.test(r)&&Number.isFinite(Date.parse(r)),"not a date"),mO=M.object({tool:M.literal("sandforge-clone"),version:M.literal(1),run:M.string(),removalStamps:M.record(ut,ec),removalSpans:M.array(M.object({first:ec,last:ec,userId:ut})),removalLeft:M.array(ut).optional(),sweep:M.object({sweptAt:Us,deleted:M.number().int().nonnegative(),keptChanged:M.number().int().nonnegative(),refused:M.number().int().nonnegative()}).optional(),made:M.array(ut).max(1e4*100).optional(),late:M.array(ut).max(1e4*100).optional(),partsRemoved:M.array(M.number().int().nonnegative()).max(1e4).optional()});function ii(r,e){if(r===void 0)return{};let t;try{t=JSON.parse(r)}catch{}let n=M.object({tool:M.literal("sandforge-clone"),run:M.string()}).safeParse(t);if(!n.success)return{refusal:"is not the record of removals sandforge clone keeps there, and is not overwritten: move it, as the removal keeps there what it leaves on the records of the run."};if(n.data.run!==e)return{otherRun:!0};let o=mO.safeParse(t);if(!o.success)return{refusal:`is not a record of removals a removal can read: ${o.error.issues.slice(0,5).map(p=>`${p.path.map(String).join(".")||"the file"}: ${p.message}`).join("; ")}.`};let{removalStamps:s,removalSpans:i,removalLeft:a,sweep:d,made:c,late:u,partsRemoved:l}=o.data;return{earlier:{removalStamps:s,removalSpans:i,...a?{removalLeft:a}:{},...d?{sweep:d}:{},...c?{made:c}:{},...u?{late:u}:{},...l?{partsRemoved:l}:{}}}}function wO(r,e,t,n=[],o,s=[],i=[],a=[]){let d=new Set(t.gone??[]),c=[...a],u=Qi(e?.made,s,c),l=Qi(e?.late,i,c),f=u.join()!==(e?.made??[]).join()||l.join()!==(e?.late??[]).join();if(Object.keys(t.stamps).length===0&&!t.span&&d.size===0&&!o&&!f)return;let p=o??e?.sweep,h=d.size>0?n.flatMap(({ids:g})=>g.filter(m=>!d.has(m))):e?.removalLeft;return{tool:"sandforge-clone",version:1,run:r,removalStamps:{...e?.removalStamps,...t.stamps},removalSpans:[...e?.removalSpans??[],...t.span?[t.span]:[]],...h?{removalLeft:h}:{},...p?{sweep:p}:{},...u.length>0?{made:u}:{},...l.length>0?{late:l}:{},...e?.partsRemoved?{partsRemoved:e.partsRemoved}:{}}}async function Cm(r,e=Pt(kt())){let t=r.journal;if(t===void 0||!Yt(t))return;let n=await Sh(t,e),o=n.length>1?await e.readAt(t,"all"):void 0;if(!o)return;let s=oi(t),i;try{i=pn(s,"utf8")}catch(c){if(c?.code!=="ENOENT")return{refusal:`${s} cannot be read: ${c instanceof Error?c.message:String(c)}`}}let a=si(o.created),d=ii(i,a);return"refusal"in d?{refusal:`${s} ${d.refusal}`}:{parts:n,...r.part!==void 0?{part:r.part}:{},file:s,key:a,created:o.created,...d.earlier?{earlier:d.earlier}:{}}}function Nm(r){let e=new Set(r.earlier?.partsRemoved??[]);return r.parts.flatMap(t=>{if(t.part===r.part||!e.has(t.part))return[];let n=sn(t.created,r.earlier?.removalLeft);return n.length>0?[{part:t,plan:n}]:[]})}function Mm(r,e){if(!(r.parts.length<2))return[...r.parts].sort((t,n)=>n.part-t.part).flatMap(t=>{let n=sn(e,qn(t.created));return n.length>0?[{part:t,plan:n}]:[]})}function yO(r,e){let t=[...new Set(e.flatMap(s=>s.keptDependents>0?s.heldBy:[]))],n=new Set(r.earlier?.partsRemoved??[]),o=s=>sn(s.created,r.earlier?.removalLeft).map(i=>i.objectApiName);return r.parts.flatMap(s=>{if(s.part===r.part||n.has(s.part))return[];let i=new Set(qo(o(s),r.parts.flatMap(d=>d.part===s.part?[]:o(d)))),a=t.filter(d=>i.has(d));return a.length>0?[{part:s.part,objects:a}]:[]})}function rm(r){return r.map(({part:e,objects:t})=>`of what this removal kept for records that stay, what the run's part ${e} (its summary's "part") holds \u2014 its ${t.join(", ")} records \u2014 goes with --remove of that part's summary, once that part's own records are gone, without --include-changed`)}function Bm(r,e,t){return r.parts.flatMap(n=>{if(n.part===e)return[];let o=sn(n.created,r.earlier?.removalLeft),s=_n(n);if(o.length===0||!s)return[];let i=ar(r.parts,n.part);return[{part:n.part,alongside:{plan:o,span:s,...Object.keys(t).length>0?{removalStamps:t}:{},...i.length>0?{laterParts:i}:{}}}]})}function Lm(r){return r?.part===void 0?[]:[...new Set(r.parts.flatMap(e=>e.part===r.part?[]:sn(e.created,r.earlier?.removalLeft).map(t=>t.objectApiName)))]}function bO(r,e){let t=r.earlier,n=[...new Set([...t?.partsRemoved??[],...e.parts])].sort((i,a)=>i-a);if(Object.keys(e.stamps).length===0&&e.spans.length===0&&e.gone.length===0&&n.length===(t?.partsRemoved?.length??0))return;let o=new Set(e.gone.map(i=>i.slice(0,15))),s=(t?.removalLeft??qn(r.created)).filter(i=>!o.has(i.slice(0,15)));return{tool:"sandforge-clone",version:1,run:r.key,removalStamps:{...t?.removalStamps,...e.stamps},removalSpans:Cr(t?.removalSpans,e.spans),removalLeft:s,...t?.sweep?{sweep:t.sweep}:{},...t?.made?{made:t.made}:{},...t?.late?{late:t.late}:{},partsRemoved:n}}function RO(r){let e={};for(let o of r)for(let s of[...o.otherPartStamps??[],o.stamps])Object.assign(e,s);let n=r.flatMap(o=>o.span?[o.span]:[]).reduce((o,s)=>o?{...o,first:Date.parse(s.first)<Date.parse(o.first)?s.first:o.first,last:Date.parse(s.last)>Date.parse(o.last)?s.last:o.last}:s,void 0);return{stamps:e,...n?{span:n}:{},gone:r.flatMap(o=>o.gone)}}function Wm(r,e){return e?{...r,removalStamps:{...r?.removalStamps,...e.removalStamps},removalSpans:Cr(r?.removalSpans,e.removalSpans)}:r}function cc(r,e){let t=`${r}.${process.pid}.tmp`;try{cm(t,JSON.stringify(e,null,2)+`
|
|
854
|
-
`,"utf8"),am(t,r);return}catch(n){try{qs(t,{force:!0})}catch{}return n instanceof Error?n.message:String(n)}}async function OO(r=process.argv){let e={};try{await kO(r,e)}finally{e.lock?.release()}}async function kO(r,e){let t=Date.now(),n=GR(r),o=F=>n.json?console.error(F):console.log(F),s;try{s=pn(n.summaryPath,"utf8")}catch(F){process.stderr.write(`--remove ${n.summaryPath} cannot be read: ${F instanceof Error?F.message:String(F)}
|
|
855
|
-
`),process.exit(2)}let i=await sc(n.summaryPath,s,n.target);"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
|
|
856
|
-
`),process.exit(2));let a=F=>({code:Ai,message:`${sd(F)}. A removal now would delete under it what it goes on writing: ${id(F)}, then remove it. Nothing was read or deleted.`}),d=i.summary.journal;if(n.preview){let F=d!==void 0?hh(d):void 0;return F&&Tt(a(F)),jO(n,i.summary,o,t)}if(d!==void 0){let F=js(d,{journalId:lc(d).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,removes:!0});"busy"in F&&Tt(a(F.busy)),e.lock=F.lock}let c,u=async()=>{if(!c){let F=await Cn(n.target),Y=bn(F);c={session:F,conn:Y,org:await un(Y)}}return c},l=i.summary.journal;if(l!==void 0&&Yt(l)&&Pt(kt()).callsInFlightAt(l)>0){let{conn:F,org:Y}=await u();i.summary.targetOrgId!==void 0&&!Ys(i.summary.targetOrgId,Y.id)&&Tt(yt(i.summary.targetOrgId));let ne=await Pt(kt()).reconcileAt(l,Ss(F));for(let oe of Ts(ne,n.target,"removal"))o(oe);let Ee=(ne.underway??[]).reduce((oe,{rows:rt})=>oe+rt,0),re=Lp(ne)-Ee;re>0&&o(` the journal names none of the ${re} row(s) that may be in ${n.target}: they stay, and ${ln("--sweep-list")} shows what the run's user created in the run's window`),i=await sc(n.summaryPath,pn(n.summaryPath,"utf8"),n.target),"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
|
|
857
|
-
`),process.exit(2))}let{summary:f}=i;f.targetOrgId===void 0&&f.target!==n.target&&(process.stderr.write(`The run wrote to ${f.target}, and its records are removed from that org only: give --target ${f.target}.
|
|
858
|
-
`),process.exit(2));let p=(f.result.mayHaveBeenWritten??[]).reduce((F,{sourceIds:Y})=>F+Y.length,0),h=0,g,m,y,k=[],O=!1,R=!1,w,A=F=>{let Y={sweep:n.sweep,windowUntold:O,inParts:R};return w?[...Xd(w.own,Y),...w.others.flatMap(({part:ne,objects:Ee})=>Xd(Ee,{...Y,part:ne}))]:Xd(F,Y)},S=(F,Y,ne,Ee,re)=>{if(n.json){process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"remove",summary:n.summaryPath,target:n.target,...ne?{targetOrgId:ne}:{},includeChanged:n.includeChanged,result:{status:F,planned:Y.reduce((oe,rt)=>oe+rt.planned,0),objects:Y,...p>0?{mayHaveBeenWritten:p}:{},...h>0?{removedEarlier:h}:{},...re?{sweep:re}:{},...g?{sweepListing:g}:{},...om(f,n)!==void 0?{wholeOrgNotSwept:!0}:{},...m?{mutedAutomation:m}:{},...k.length>0?{heldByOtherParts:k}:{}},...Ee?{removalsFile:Ee}:{},elapsedMs:Fe(t)},null,2)+`
|
|
859
|
-
`);for(let oe of A(Y))console.error(oe);for(let oe of rm(k))console.error(oe);return}if(Y.length>0||!re)for(let oe of tO(F,Y,p))console.log(oe);if(re)for(let oe of cO(re))console.log(oe);for(let oe of A(Y))console.log(oe);for(let oe of rm(k))console.log(oe);Ee&&console.log(`what this removal left on the run's records is kept in ${Ee}, which the next --remove of this summary reads`),console.log(`
|
|
860
|
-
done in ${Fe(t)}ms`)},v=mc(f);if(v.length===0){o("The run created no record: there is nothing of it to remove."),S("success",[]);return}let j=si(v),P=oi(n.summaryPath),B;try{B=pn(P,"utf8")}catch(F){F?.code!=="ENOENT"&&(process.stderr.write(`${P} cannot be read: ${F instanceof Error?F.message:String(F)}
|
|
861
|
-
`),process.exit(2))}let I=ii(B,j);"refusal"in I&&(process.stderr.write(`${P} ${I.refusal}
|
|
862
|
-
`),process.exit(2));let{otherRun:z,earlier:Z}=I,H=await Cm(f);H&&"refusal"in H&&(process.stderr.write(`${H.refusal}
|
|
863
|
-
`),process.exit(2)),R=H!==void 0;let U=H&&Dt(P)!==Dt(H.file)?H:void 0,J=Wm(Z,U?.earlier);o(`sandforge clone --remove ${n.summaryPath} from ${n.target}`);let je=om(f,n);je!==void 0&&o(je);let pe=go({objects:v,removalLeft:Z?.removalLeft}),ae=sn(pe,U?.earlier?.removalLeft),K=F=>F.reduce((Y,ne)=>Y+ne.ids.length,0);h=K(v)-K(ae),K(v)>K(pe)&&o(`${K(v)-K(pe)} record(s) removed by an earlier --remove of this summary`),K(pe)>K(ae)&&o(`${K(pe)-K(ae)} record(s) removed by an earlier --remove of the run's other part or of its journal`);let X=U?Nm(U):[],ce=H&&!("refusal"in H)&&!U?H:void 0,Te=ce?Mm(ce,ae):void 0,we=n.includeChanged&&f.result.runUserId!==void 0;if(ae.length===0&&X.length===0&&!n.sweep&&!n.sweepList&&!we){o("nothing left of the run to remove"),S("success",[]);return}let{session:de,conn:_,org:L}=await u(),Re=new Map([[L.id,{alias:n.target,username:de.username}]]),Ie=`sandforge-clone-${Hs()}`,Ne,he=F=>Vs(n.audit,Re,{action:"cleanup_delete",module:"forge",operationId:Ie,orgId:L.id,...F,...m?{muted:mo(m)}:{}}),Ke=n.sweepList?void 0:Zr(n.target,L,"remove");Ke&<({code:"PRODUCTION_TARGET",message:Ke}),f.targetOrgId!==void 0&&!Ys(f.targetOrgId,L.id)&&Tt(yt(f.targetOrgId));let ve=f.result.writtenBetween===void 0?f:void 0;f=await Qs(_,f);let E=()=>Fm(L.id,n.target,f,v,J,U);if(n.sweepList){let F=await od(dc(_,"sandforge clone --sweep-list"),await ac(_,n.target,f,v,await E(),{ofTheRun:U,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),J?.removalSpans??[]);for(let ne of Gs(F,n.target,n,!0))o(ne);let Y=oc(F.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Y!==void 0&&o(Y);for(let ne of zs(U,F))o(ne);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"sweep-list",summary:n.summaryPath,target:n.target,targetOrgId:L.id,listing:F,elapsedMs:Fe(t)},null,2)+`
|
|
864
|
-
`):console.log(`
|
|
865
|
-
done in ${Fe(t)}ms`),F.refusal!==void 0&&process.exit(nm);return}let W=f.result.runUserId,q=new AbortController,ge=()=>q.abort(),ee=ae.length>0||X.length>0||we;ae.length>0||X.length>0?Ct():o(we?"nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run":"nothing left of the run to remove");let te=n.sweep?ah(dc(_,"sandforge clone --sweep",q.signal),await ac(_,n.target,f,v,await E(),{signal:q.signal,ofTheRun:U,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),{includeChanged:n.includeChanged,removalSpans:J?.removalSpans??[],...fO(n),approve:async F=>{g=F,o("");for(let ne of Gs(F,n.target,n))o(ne);let Y=oc(F.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Y!==void 0&&o(Y);for(let ne of zs(U,F))o(ne)}}):void 0;if(te){let F=Xn(ge);try{await te.ask()}finally{F()}let Y=iO(te,g);if(Y){g=Y,o("");for(let ne of Gs(Y,n.target,n))o(ne);for(let ne of zs(U,Y))o(ne)}}let G=te?.takes??[];(ee||G.length>0)&&!q.signal.aborted&&await nt(G);let Oe,ye=[];if(ee)Oe=await dt(),Oe.stoppedForUndeletable&&(y&<(y),process.exit(1));else if(te){let F=await At(),Y=Xn(ge);try{await te.first(),await te.afterRemoval()}finally{if(Y(),F){m=await F.release();for(let ne of er(m,n.target))o(ne)}}}let ue=te?.result();ue&&Vs(n.audit,Re,{action:"cleanup_delete",module:"forge",operationId:`${Ie}-sweep`,orgId:L.id,outcome:ue.status==="refused"?"stopped":ue.status,...ue.status==="refused"?{code:"SWEEP_REFUSED"}:{},objects:ch(ue),details:uh(ue,j),...!ee&&m?{muted:mo(m)}:{}});function Ct(){for(let F of JR(f,ae,n))o(F);for(let F of QR(X))o(F);Z?o(`what earlier removals of this summary left on the run's records, read from ${P}, is not a change since the run`):z&&o(`${P} is of another run: it is not read, and what this removal leaves on the records, if anything, takes its place`),U?.earlier&&o(`what the removals of the run's other part or of its journal left on its records, read from ${U.file}, is no change since the run`)}function lt(F){return he({outcome:"stopped",code:F.code}),Tt(F)}function Tt(F){return process.stderr.write(`${Ot(F)}
|
|
866
|
-
`),n.json&&process.stdout.write(bo({tool:"sandforge-clone",summary:n.summaryPath,target:n.target,elapsedMs:Fe(t)},F)),process.exit(1)}function yt(F){return{code:yo,message:`${n.target} is not the org the run wrote to (${F}), and its records are removed from that org only. Nothing was deleted.`}}async function nt(F){let Y=[...new Set([...ae,...X.flatMap(fe=>fe.plan)].map(fe=>fe.objectApiName))],ne=[...new Set([...qo(Y,Lm(U),{userKept:W!==void 0}),...Y.length===0&&we?[_o]:[],...F])],Ee=Ji(Y),re=await ni(_).read(n.target,ne);o("");for(let fe of Ca(re,n.target,ne.length,Ee))o(fe);if(n.muteAutomation){let fe=new Set(Ee);try{Ne=await na(async()=>ea(_),re,{writes:(qe,Ve)=>Ve==="delete"||Ve==="update"&&fe.has(qe)}),m=Ne.muted;for(let qe of er(Ne.muted,n.target))o(` ${qe}`)}catch(qe){if(!Nr(qe))throw qe;lt(qe.refusal)}}let oe=Ne?.automation??re,rt=Fa(oe,n.target,{drafted:Ee,assign:ps(oe,Ti(oe,Ee)),mayMute:Ne===void 0&&St("--mute-automation")});rt&&!n.acceptAutomation&<({code:"AUTOMATION_NOT_ACCEPTED",message:rt})}async function At(){let F=Ne?.prepared&&!q.signal.aborted?await Ne.prepared.acquire(`sandforge clone --remove ${Ie}`).catch(Y=>{if(!Nr(Y))throw Y;return lt(Y.refusal)}):void 0;return F&&(m=F.outcome),F}async function dt(){let F,Y=Xn(ge),ne=f.result.writtenBetween,Ee=ne?{runStartedAt:new Date(ne.first),runEndedAt:new Date(ne.last)}:{runDurationMs:f.elapsedMs,...f.finishedAt?{runRecordedAt:new Date(f.finishedAt)}:{}},re=tl,oe=[],rt=xg(n.leaveUndeletable,n.target,Je=>{y=Je}),[fe,...qe]=Te??[],Ve=U??(fe?ce:void 0),bt=U?.part??fe?.part.part,Zt=Ve&&bt!==void 0?Bm(Ve,bt,J?.removalStamps??{}):[],En=Ve&&bt!==void 0?ar(Ve.parts,bt):[];try{if(ae.length>0||we){let Ze=fe?fe.plan:ae;re=await Fr(Zn(_,"sandforge clone --remove"),Ze,{...(fe&&_n(fe.part))??Ee,...J?{removalStamps:J.removalStamps,removalSpans:J.removalSpans}:{},...pO(te),...W?{runUserId:W}:{},...En.length>0?{laterParts:En}:{},...Zt.length>0?{otherParts:Zt.map(_t=>_t.alongside)}:{},includeChanged:n.includeChanged,onUndeletable:rt,beforeFirstWrite:async()=>{F=await At()},signal:q.signal})}else F=await At();let Je={...J?.removalStamps,...re.stamps};for(let Ze of re.otherPartStamps??[])Object.assign(Je,Ze);let en=[...bt!==void 0?[{part:bt,plan:fe?fe.plan:ae}]:[],...[...qe,...X].map(Ze=>({part:Ze.part.part,plan:Ze.plan}))];for(let{part:Ze,plan:_t}of[...qe,...X]){if(re.stoppedForUndeletable||re.cancelled||q.signal.aborted)break;let Mt=_n(Ze)??(fe?Ee:void 0);if(!Mt)continue;let Et=Cr(J?.removalSpans,[re,...ye].flatMap(Me=>Me.span?[Me.span]:[])),Bt=ar(Ve?.parts??[],Ze.part),ot=await Fr(Zn(_,"sandforge clone --remove"),_t,{...Mt,removalStamps:Je,removalSpans:Et,...W?{runUserId:W}:{},...Bt.length>0?{laterParts:Bt}:{},otherPartRecords:en.flatMap(Me=>Me.part===Ze.part?[]:Me.plan),includeChanged:n.includeChanged,onUndeletable:rt,signal:q.signal});Object.assign(Je,ot.stamps),ye.push(ot),U&&oe.push({part:Ze.part,objects:ot.objects})}}finally{if(Y(),F){m=await F.release();for(let Je of er(m,n.target))o(Je)}}if(oe.length>0&&(w={own:re.objects,others:oe}),re.stoppedForUndeletable)return re;let Nt=J?.removalSpans.at(-1)?.last,Kn=Uo(re.objects,...ye.map(Je=>Je.objects)),vt=re.cancelled||ye.some(Je=>Je.cancelled);return he({outcome:rl({status:Yi(Kn,vt)}),objects:ol(Kn),...Nt?{leftBy:Nt}:{}}),re}let Xt=ue&&dh(ue,new Date().toISOString(),J?.sweep),ke=wO(j,J,Oe&&Te?RO([Oe,...ye]):Oe??{stamps:{}},ae,Xt,te?.made??[],te?.late??[],te?.gone??[]);ke&&H&&!U&&(ke.partsRemoved=H.parts.map(F=>F.part));let ft=ke?cc(P,ke):void 0;if(ft&&process.stderr.write(`What this removal left on the run's records could not be kept in ${P} (${ft}): a later --remove of this summary may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
|
|
867
|
-
`),U?.part!==void 0&&Oe&&!Oe.stoppedForUndeletable){let F=[Oe,...ye],Y={};for(let re of F)for(let oe of[re.stamps,...re.otherPartStamps??[]])Object.assign(Y,oe);let ne=bO(U,{stamps:Y,spans:F.flatMap(re=>re.span?[re.span]:[]),gone:F.flatMap(re=>re.gone),parts:[U.part,...X.map(re=>re.part.part)]}),Ee=ne?cc(U.file,ne):void 0;Ee&&process.stderr.write(`What this removal left on the run's records could not be kept in ${U.file} (${Ee}): a later --remove of the run's other part or of its journal may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
|
|
868
|
-
`)}let _e=Uo(Oe?.objects??[],...ye.map(F=>F.objects)),pt=Oe?.cancelled===!0||ye.some(F=>F.cancelled),$t=nl(Oe?Yi(_e,pt):"success",ue);U?.part!==void 0&&(k=yO(U,_e)),ve&&!n.sweep&&_e.some(F=>(F.heldByAutomation??0)>0)&&(O=(await Qs(_,ve)).result.writtenBetween===void 0),S($t,_e,L.id,ke&&!ft?P:void 0,ue),$t!=="success"&&process.exit(nm)}var SO="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function TO(r){return`${JSON.stringify({tool:"sandforge-clone",version:1,action:"remove-preview",summary:r.summary,target:r.target,...r.targetOrgId!==void 0?{targetOrgId:r.targetOrgId}:{},includeChanged:r.includeChanged,preview:r.preview,...r.sweepListing?{sweepListing:r.sweepListing}:{},refusals:r.refusals.map(({message:e})=>e),refusalCodes:r.refusals.map(({code:e})=>e),notes:r.notes,elapsedMs:r.elapsedMs},null,2)}
|
|
869
|
-
`}function AO(r,e,t,n){let o=i=>r.userNames[i]??i,s=["preview: what a removal would do; nothing was written"];for(let i of r.objects){let a=[i.toDelete>0?`${i.toDelete} to delete`:"",n&&i.changedSince>0?`${i.changedSince} of them changed since the run`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the run`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);s.push(` ${i.objectApiName}: ${a.join(", ")||"nothing"} of ${i.planned}${jm(i)}`);let d=Object.entries(i.changedBy).sort((c,u)=>u[1]-c[1]);d.length>0&&s.push(` last changed by: ${d.map(([c,u])=>`${o(c)} ${u}`).join(" \xB7 ")}`);for(let c of i.reasons)s.push(` ${c}`)}for(let i of e)s.push(Nn(i,"a removal"));return[...s,...t]}async function jO(r,e,t,n){let o=e,s=[],i,a=(E,W,q)=>{if(s.push(SO),r.json){process.stdout.write(TO({summary:r.summaryPath,target:r.target,...q!==void 0?{targetOrgId:q}:{},includeChanged:r.includeChanged,preview:E,refusals:W,notes:s,elapsedMs:Fe(n),...i?{sweepListing:i}:{}}));return}t("");for(let ge of AO(E,W,s,r.includeChanged))t(ge);t(`
|
|
870
|
-
done in ${Fe(n)}ms`)};t(`sandforge clone --remove ${r.summaryPath} --preview of ${r.target}`),o.targetOrgId===void 0&&o.target!==r.target&&(process.stderr.write(`The run wrote to ${o.target}, and its records are read in that org only: give --target ${o.target}.
|
|
871
|
-
`),process.exit(2));let d,c=async()=>{if(d)return d;let E=bn(await Cn(r.target)),W=await un(E);if(o.targetOrgId!==void 0&&!Ys(o.targetOrgId,W.id)){let q={code:yo,message:`${r.target} is not the org the run wrote to (${o.targetOrgId}): its records are read in that org only. Nothing of the run was read.`};process.stderr.write(`${Ot(q)}
|
|
872
|
-
`),r.json&&process.stdout.write(bo({tool:"sandforge-clone",action:"remove-preview",summary:r.summaryPath,target:r.target,elapsedMs:Fe(n)},q)),process.exit(1)}return d={conn:E,org:W},d},u=o.journal;if(u!==void 0&&Yt(u)&&Pt(kt()).callsInFlightAt(u)>0){let{conn:E}=await c(),W=await Pt(kt()).reconcileAt(u,Ss(E,{leaveOpen:!0}),{keep:!1});s.push(...Ts(W,r.target,"preview"))}let l=(o.result.mayHaveBeenWritten??[]).reduce((E,{sourceIds:W})=>E+W.length,0);l>0&&s.push(`${l} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned: no removal reaches them`);let f=mc(o);if(f.length===0){s.push("The run created no record: there is nothing of it to remove."),a({planned:0,objects:[],userNames:{}},[]);return}let p=oi(r.summaryPath),h;try{h=pn(p,"utf8")}catch(E){E?.code!=="ENOENT"&&(process.stderr.write(`${p} cannot be read: ${E instanceof Error?E.message:String(E)}
|
|
873
|
-
`),process.exit(2))}let g=ii(h,si(f));"refusal"in g&&(process.stderr.write(`${p} ${g.refusal}
|
|
874
|
-
`),process.exit(2));let m=await Cm(o);m&&"refusal"in m&&(process.stderr.write(`${m.refusal}
|
|
875
|
-
`),process.exit(2));let y=m&&Dt(p)!==Dt(m.file)?m:void 0,k=Wm(g.earlier,y?.earlier),O=go({objects:f,removalLeft:g.earlier?.removalLeft}),R=sn(O,y?.earlier?.removalLeft),w=y?Nm(y):[],A=E=>E.reduce((W,q)=>W+q.ids.length,0);A(f)>A(O)&&s.push(`${A(f)-A(O)} record(s) removed by an earlier --remove of this summary`),A(O)>A(R)&&s.push(`${A(O)-A(R)} record(s) removed by an earlier --remove of the run's other part or of its journal`);for(let{part:E,plan:W}of w)s.push(`with them, ${A(W)} record(s) of the run's part ${E.part} an earlier --remove of that part left, read against that part, once these are gone`);let S=r.includeChanged&&o.result.runUserId!==void 0;if(R.length===0&&w.length===0&&!r.sweep&&!S){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},[]);return}let{conn:v,org:j}=await c(),P=[],B=Zr(r.target,j,"remove");if(B&&P.push({code:"PRODUCTION_TARGET",message:B}),o=await Qs(v,o),r.sweep){i=await od(dc(v,"sandforge clone --remove --preview --sweep"),await ac(v,r.target,o,f,await Fm(j.id,r.target,o,f,k,y),{ofTheRun:y,...r.sweepUser!==void 0?{user:r.sweepUser}:{}}),k?.removalSpans??[]),t("");for(let W of Gs(i,r.target,r,!0))t(W);let E=oc(i.refusal,{kept:o.result.runUserId!==void 0,given:r.sweepUser!==void 0,target:r.target});E!==void 0&&t(E);for(let W of zs(y,i))t(W)}let I=[...new Set([...R,...w.flatMap(E=>E.plan)].map(E=>E.objectApiName))],z=i?Jc(i,r):[],Z=[...new Set([...qo(I,Lm(y),{userKept:o.result.runUserId!==void 0}),...I.length===0&&S?[_o]:[],...z])],H=Ji(I),U=await ni(v).read(r.target,Z);t("");for(let E of Ca(U,r.target,Z.length,H))t(E);let J=Fa(U,r.target,{drafted:H,assign:ps(U,Ti(U,H)),mayMute:!r.muteAutomation&&St("--mute-automation")});if(J&&!r.acceptAutomation&&P.push({code:"AUTOMATION_NOT_ACCEPTED",message:J}),R.length===0&&w.length===0&&!S){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},P,j.id);return}R.length===0&&w.length===0&&s.push("nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run");let je=new AbortController,pe,ae=Xn(E=>{pe=E,je.abort()}),K=o.result.writtenBetween,X=K?{runStartedAt:new Date(K.first),runEndedAt:new Date(K.last)}:{runDurationMs:o.elapsedMs,...o.finishedAt?{runRecordedAt:new Date(o.finishedAt)}:{}},ce,Te=[],[we,...de]=(m&&!y?Mm(m,R):[])??[],_=y??(we?m:void 0),L=y?.part??we?.part.part,Re=_&&L!==void 0?ar(_.parts,L):[],Ie=_&&L!==void 0?Bm(_,L,k?.removalStamps??{}):[],Ne=[...L!==void 0?[{part:L,plan:we?we.plan:R}]:[],...[...de,...w].map(E=>({part:E.part.part,plan:E.plan}))];try{ce=await Fr(Zn(v,"sandforge clone --remove --preview"),we?we.plan:R,{...(we&&_n(we.part))??X,...k?{removalStamps:k.removalStamps,removalSpans:k.removalSpans}:{},...Re.length>0?{laterParts:Re}:{},...Ie.length>0?{otherParts:Ie.map(E=>E.alongside)}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},includeChanged:r.includeChanged,previewOnly:!0,signal:je.signal});for(let{part:E,plan:W}of[...de,...w]){let q=_n(E)??(we?X:void 0);if(!q||!ce.preview||je.signal.aborted)continue;let ge=ar(_?.parts??[],E.part);Te.push(await Fr(Zn(v,"sandforge clone --remove --preview"),W,{...q,...k?{removalStamps:k.removalStamps,removalSpans:k.removalSpans}:{},...ge.length>0?{laterParts:ge}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},otherPartRecords:Ne.flatMap(ee=>ee.part===E.part?[]:ee.plan),includeChanged:r.includeChanged,previewOnly:!0,signal:je.signal}))}}finally{ae()}let he=ce.preview&&Te.every(E=>E.preview)?{objects:Xi(ce.preview.objects,...Te.map(E=>E.preview?.objects??[])),userNames:Object.assign({},ce.preview.userNames,...Te.map(E=>E.preview?.userNames??{}))}:void 0;he||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
|
|
876
|
-
`),process.exit(vr(pe??"SIGINT")));let Ke=[ce,...Te].flatMap(E=>E.undeletable??[]);if(Ke.length>0&&!r.leaveUndeletable){let E=Ke.map(W=>`${W.objectApiName} (${W.records} records)`).join(", ");P.push({code:zd,message:`The user SandForge connects as may not delete the records of ${E} in ${r.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}let ve=R.length>0||w.length>0;ve&&s.push(Tm(o)),a({planned:he.objects.reduce((E,W)=>E+W.planned,0),objects:he.objects,...Ke.length>0?{undeletable:Ke}:{},userNames:he.userNames,...ve?{alreadyHeld:Am(o)}:{}},P,j.id)}async function Qs(r,e,t=Pt(kt())){if(e.result.writtenBetween||e.journal===void 0||!Yt(e.journal))return e;let n={query:(s=>r.query(s,{scanAll:!0}))},o=await t.writtenBetweenAt(e.journal,r)??await t.writtenBetweenAt(e.journal,n);return o?{...e,result:{...e.result,writtenBetween:o}}:e}function Ys(r,e){return r.slice(0,15)===e.slice(0,15)}var $O=new Set(["--verify","--target","--source","--json","--audit"]),vO=new Set(["--verify","--target","--source","--audit"]);function EO(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(fc),process.exit(0));let t=s=>{let i=e.indexOf(s),a=i>=0?e[i+1]:void 0;return a!==void 0&&!a.startsWith("--")?a:void 0};for(let s=0;s<e.length;s++){let i=e[s];if(vO.has(i)){e[s+1]!==void 0&&!e[s+1].startsWith("--")&&s++;continue}$O.has(i)||(process.stderr.write(`--verify takes --target, --source, --json and --audit, not "${i}". Run with --help for usage.
|
|
877
|
-
`),process.exit(2))}let n=t("--verify"),o=t("--target");return(!n||!o||e.includes("--source")&&!t("--source"))&&(process.stderr.write(`--verify takes the file a run printed its --json summary to, --target the org the run wrote to, and --source, when given, the org it read from. Run with --help for usage.
|
|
878
|
-
`),process.exit(2)),{summaryPath:n,target:o,source:t("--source"),json:e.includes("--json"),audit:pc(e)}}var IO=M.object({result:M.object({writtenWithoutFields:M.array(M.object({objectApiName:M.string().regex(tt),fields:M.array(M.object({field:M.string().regex(tt)}))}))})}),xO=M.object({result:M.object({lookupsLeftEmptyByFilter:M.array(M.object({objectApiName:M.string().regex(tt),field:M.string().regex(tt),records:M.number().int().nonnegative(),recordIds:M.array(ut)}))})}),PO={verified:0,partial:3,unstable:4};function FO(r,e){let t=[r.verdict==="unstable"?`verification: UNSTABLE \u2014 no two of ${r.attempts} readings of ${e} agreed: something still writes to the run's records; verify again once it is done`:`verification: ${r.verdict.toUpperCase()} (${r.attempts} readings of ${e})`,...r.roots?[` roots: ${r.roots.inTarget} of ${r.roots.of} in ${e}`]:[]],n=[];for(let s of r.objects){if(s.error!==void 0){t.push(` ${s.objectApiName}: not read (${s.error})`);continue}let i=[s.deleted>0?`${s.deleted} in the recycle bin`:"",s.notVisible>0?`${s.notVisible} neither there nor in the recycle bin, out of sight`:""].filter(Boolean),a=s.linksLeftEmptyByFilter??0,d=s.linksSetByAutomation??0,c=s.linksLeftEmptyByTheRun??0,u=[c>0?`${c} left empty by the run, as it said`:"",a>0?`${a} left empty by the target's lookup filter, as the run said`:"",d>0?`${d} set by the target's automation during the run`:""].filter(Boolean),l=s.linksChecked-s.linksBroken-a-d-c,f=s.withTheirRecord??0,p=s.linksUnchecked!==void 0?`lookups not checked (${s.linksUnchecked})`:s.linksChecked===0?"no lookup the run set to check":s.linksBroken===0&&u.length===0?`lookups: ${s.linksChecked} checked, all hold`:`lookups: ${s.linksChecked} checked, `+[...s.linksBroken>0?[`${s.linksBroken} do not hold`]:[`${l} hold`],...u].join(", ");t.push(s.expected===0&&f>0?` ${s.objectApiName}: none written by the run, and ${f} written by the platform with their record there`:` ${s.objectApiName}: ${s.present} of ${s.expected} there`+(i.length>0?`, ${i.join(", ")}`:"")+(f>0?`, and ${f} written by the platform with their record`:"")+`; ${p}`);for(let h of s.brokenLinks)t.push(h.found===null?` ${h.recordId}: ${h.field} is empty, the run set it to ${h.expected}`:` ${h.recordId}: ${h.field} points at ${h.found}, the run set it to ${h.expected}`);for(let h of s.explainedLinks??[])t.push(h.cause==="automation"?` ${h.recordId}: ${h.field} points at ${h.found??""}, which the target's automation created during the run; the run set it to ${h.expected}`:h.cause==="run"?` ${h.recordId}: ${h.field} is empty: left empty by the run, as it said, rather than set to ${h.expected}`:` ${h.recordId}: ${h.field} is empty: the target's lookup filter refused ${h.expected}, and the run left it empty`);s.recycleBinUnread!==void 0&&t.push(` the recycle bin could not be read (${s.recycleBinUnread})`),(s.moreInTheWindow??0)>0&&t.push(` ${s.moreInTheWindow} more ${s.objectApiName} record(s) were created in ${e} during the run by the run's user than the run wrote`+(f>0?" and the platform wrote with its records":"")+": the target's automation, another session writing as that user, or a call written twice");for(let h of s.changedRecords)n.push(` ${s.objectApiName} ${h.recordId}: modified ${h.modifiedAt}`+(h.modifiedById?` by ${h.modifiedById}`:""))}let o=r.objects.reduce((s,i)=>s+i.changed,0);return o>0&&t.push(`changed since the run: ${o} record(s), which --remove keeps unless --include-changed`,...n),r.linksUnchecked!==void 0&&t.push(`lookups not checked: ${r.linksUnchecked}`),t}async function CO(r=process.argv){let e=Date.now(),t=EO(r),n=I=>t.json?console.error(I):console.log(I),o;try{o=pn(t.summaryPath,"utf8")}catch(I){process.stderr.write(`--verify ${t.summaryPath} cannot be read: ${I instanceof Error?I.message:String(I)}
|
|
879
|
-
`),process.exit(2)}let s;try{s=JSON.parse(o)}catch{}M.object({tool:M.literal("sandforge-clone"),dryRun:M.literal(!0)}).safeParse(s).success&&(process.stderr.write(`--verify ${t.summaryPath} is the summary of a dry run, which wrote nothing to the target: there is nothing of it to verify.
|
|
880
|
-
`),process.exit(2));let a=$i(s,"sandforge-clone");a&&(process.stderr.write(`--verify ${t.summaryPath} ${vi(a,"verify")}
|
|
881
|
-
`),process.exit(2));let d=await sc(t.summaryPath,o,t.target);"refusal"in d&&(process.stderr.write(`--verify ${t.summaryPath} ${d.refusal}
|
|
882
|
-
`),process.exit(2));let{summary:c}=d;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are verified in that org only: give --target ${c.target}.
|
|
883
|
-
`),process.exit(2));let u=mc(c);if(u.length===0){n("The run created no record: there is nothing of it to verify.");return}let l,f=oi(t.summaryPath),p;try{p=pn(f,"utf8")}catch{}let h=ii(p,si(u)),g=u;if("refusal"in h)n(`${f} ${h.refusal}`);else if(l=h.earlier?.removalStamps,g=go({objects:u,removalLeft:h.earlier?.removalLeft}),g.length===0){n("An earlier --remove of this summary took every record the run created: there is nothing of it to verify.");return}let m=IO.safeParse(s),y=xO.safeParse(s);n(`sandforge clone --verify ${t.summaryPath} in ${t.target}`);let k=await Cn(t.target),O=bn(k),R=await un(O);if(c.targetOrgId!==void 0&&!Ys(c.targetOrgId,R.id)){let I={code:yo,message:`${t.target} is not the org the run wrote to (${c.targetOrgId}), and its records are verified in that org only. Nothing of the run was read.`};process.stderr.write(`${Ot(I)}
|
|
884
|
-
`),t.json&&process.stdout.write(bo({tool:"sandforge-clone",action:"verify",summary:t.summaryPath,target:t.target,elapsedMs:Fe(e)},I)),process.exit(1)}c=await Qs(O,c);let w=c.roots!==void 0&&c.journal!==void 0&&Yt(c.journal)?(await Pt(kt()).readAt(c.journal,"all"))?.roots:void 0,A=t.source??c.source,S;try{S=cd(bn(await Cn(A)),"sandforge clone --verify source")}catch(I){S={unavailable:`the org the run read from, ${A}, could not be reached: ${V(I)}`}}let v=new Map([[R.id,{alias:t.target,username:k.username}]]),j=I=>Vs(t.audit,v,{action:"forge_verify",module:"forge",operationId:`sandforge-clone-${Hs()}`,orgId:R.id,...I}),P;try{P=await new wh({target:cd(O,"sandforge clone --verify"),source:S}).verify({records:g,remapTable:c.result.remapTable,...c.result.writtenBetween?{runStartedAt:new Date(c.result.writtenBetween.first),runEndedAt:new Date(c.result.writtenBetween.last)}:c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{},...l?{removalStamps:l}:{},...m.success?{writtenWithout:Rh(m.data.result.writtenWithoutFields)}:{},...y.success?{leftEmptyByFilter:y.data.result.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:bh(c.wholeOrg===!0),...c.result.withTheirRecordSourceIds?{withTheirRecord:c.result.withTheirRecordSourceIds}:{},...w?{roots:{objectApiName:w.objectApiName,sourceIds:w.ids}}:{}})}catch(I){throw j({outcome:"failure"}),I}if(j({outcome:P.verdict==="verified"?"success":"partial",verdict:P.verdict,details:yh(P)}),t.json)process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"verify",summary:t.summaryPath,target:t.target,targetOrgId:R.id,source:A,result:P,elapsedMs:Fe(e)},null,2)+`
|
|
885
|
-
`);else{for(let I of FO(P,t.target))console.log(I);console.log(`
|
|
886
|
-
done in ${Fe(e)}ms`)}let B=PO[P.verdict];B!==0&&process.exit(B)}var NO=new Set(["done","error","stopped"]);function MO(r){return r?`interrupted: the clone stopped before it was through; ${r} says what it created, and --remove ${r} takes it back`:"interrupted: the clone stopped before it was through; the summary above says what it created, and --remove takes it back from that summary saved to a file (--json)"}function om(r,e){if(!(r.wholeOrg!==!0||e.sweep||e.sweepList))return`the sweep is off for a clone of the whole org: its window spans the hours the run wrote in, and a sweep looks at ${rd} objects at most; ${ln("--sweep-list")} lists what the target's automation made for it, and ${ln("--sweep")} takes it`}var sm="ROOT_NEVER_CREATED",BO="TABLE_NEVER_CLONED",uc="No record was read or written.";async function LO(r,e,t){let n=[];for(let i of r)try{await t.createable(i.objectApiName)===!1&&n.push(i)}catch{}if(n.length===0)return;let o=n.find(i=>jo(i.objectApiName));if(o){let i=o.objectApiName;return{code:sm,message:`${o.named}: SandForge never copies ${i} records, setup or the platform's own, and ${e}'s user may not create them: a clone has nothing to write of what it starts from. ${uc}`}}let s;try{s=await t.whyNot(n.map(i=>i.objectApiName))}catch{return}for(let i of n){let a=s.get(i.objectApiName);if(a===void 0||!rf(a))continue;let d=i.objectApiName,c=a==="platform"?"the platform writes them itself":"not even one with Modify All Data: they are setup the org keeps as records, or the platform's own";return{code:sm,message:`${i.named}: no user can create ${d} records in ${e}, ${c}, and a clone has nothing to write of what it starts from. ${uc}`}}}async function WO(r,e){if(r.tables)return r.tables.map(({objectApiName:a})=>({objectApiName:a,named:`--object ${a}`}));if(r.roots?.query){let a=r.roots.query.objectApiName;return[{objectApiName:a,named:`--query (FROM ${a})`}]}let t=r.record??"";if(t==="")return[];let n=t.slice(0,3),o;try{o=await e(r.source)}catch{return[]}let s=o.find(a=>a.keyPrefix===n)?.name;if(!s)return[];let i=r.roots?.ids;return[{objectApiName:s,named:i!==void 0?`--record ${i.length} times (${s} records)`:`--record ${t} (a ${s})`}]}function im(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return{describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`);return{fields:(await e(o,s)).fields.map(ha),sent:i}},query:async(o,s)=>Ln({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s)}}function fr(r,e){let t=r.get(e);if(!t)throw new Error(`No connection for ${e}`);return t}var DO=new Set(["Lead","Case"]);function _O(r,e,t,n){return{bulkWriteRecords:async(o,s,i,a,d)=>{if(e.dryRun)throw new Error("A dry run sends no Bulk API job.");if(e.applyAssignmentRules&&DO.has(s))return{answers:[],rows:[],unmatchedIds:[],untouched:{reason:"the run applies the target's assignment rules, which a job cannot",unsupported:!0},requests:0};try{let c=await Ql(Vi(fr(r,o)),d.bulkManager,s,i,a,{...d.externalIdField?{externalIdField:d.externalIdField}:{},...d.signal?{signal:d.signal}:{},...d.onOpened?{onOpened:d.onOpened}:{}});return(c.unmatchedIds.length>0||c.answers.some(u=>u.success))&&n(),c}catch(c){throw c instanceof Jl&&(n(),t?.note({orgId:o,objectApiName:s,...c.jobId?{jobId:c.jobId}:{}})),c}},duplicateRuleObjects:async o=>Yp(fr(r,o))}}async function qO(r,e,t){let n=r?.since(0,e)??[];if(!r||n.length===0)return[];t(`waiting for ${n.length} Bulk API job(s) the run could not read back to end, before the mute is given back\u2026`);let o=await r.stillRunning(n);if(o.length>0){let s=o.map(i=>`${i.objectApiName}${i.jobId?` (${i.jobId})`:""}`).join(", ");t(`warning: ${o.length} Bulk API job(s) were still running as the mute was given back: ${s}; their records may have gone in with the target's automation on`)}return o}async function UO(r,e,t){let n=r.get(e);if(!n)throw new Error(`No connection for ${e}`);return Ln({query:async o=>n.tooling.query(o),queryMore:async o=>n.tooling.queryMore(o)},t)}async function GO(r=process.argv){if(await zO(),r.slice(2).includes("--verify"))return CO(r);if(r.slice(2).includes("--remove"))return OO(r);let e={};try{await KO(r,e)}finally{e.release?.(),e.journalLock?.release()}}async function zO(){let r=kt();try{await $p(r,new Date)}catch(e){process.stderr.write(`The plans of samples drawn a day ago or more could not all be removed from ${Ks(r,"forge-samples")} (${V(e)}).
|
|
887
|
-
`)}}var Xs=class extends Error{constructor(e){super(e),this.name="CheckpointTakeInterrupted"}},Zs=class extends Error{constructor(e){super(e),this.name="QuestionInterrupted"}};async function HO(r,e){let t=r.roots?.plan;if(t===void 0)return;let n=s=>(process.stderr.write(`${Ot(s)}
|
|
888
|
-
`),r.json&&process.stdout.write(nn({tool:"sandforge-clone",source:r.source,target:r.target,dryRun:r.dryRun,elapsedMs:Fe(e)},s)),process.exit(2)),o=`${Ut("clone")} \u2026 --dry-run --roots-plan ${t}`;if(r.dryRun){if(!Yt(t))return;try{await Za(t)}catch(s){if(!(s instanceof Xa))throw s;let i=!1;try{let a=JSON.parse(pn(t,"utf8"));i=a?.version===1&&Array.isArray(a.ids)}catch{}i||(process.stderr.write(`--roots-plan ${t} exists, and is no plan of roots: a dry run puts the records it chooses in its place. Give another file, or move it.
|
|
889
|
-
`),process.exit(2))}return}try{return await Za(t)}catch(s){if(!(s instanceof Xa))throw s;return n(s.fault==="gone"?{code:"ROOTS_PLAN_GONE",message:`--roots-plan ${t}: no plan of roots is there. The dry run keeps the records its query chooses there, for the run to write those and no other: run ${o} first. Nothing was read or written.`}:{code:"ROOTS_PLAN_MISMATCH",message:`--roots-plan ${t}: ${s.message} Run ${o} again, and give the run the plan it keeps. Nothing was read or written.`})}}async function KO(r,e){let t=Date.now(),n=gb(r),o=n.depth==="all",s=b=>n.json?console.error(b):console.log(b);s(`sandforge clone ${n.source} -> ${n.target} ${Ky(n)}`);for(let b of Hb(n))s(b);if(n.resume&&n.files===void 0){let b=Pt(kt()),T=await b.headAt(Dg(n.resume,b));T?.resume?.files&&(n={...n,files:T.resume.files},s("files: copied as the run taken up was begun, with --files"))}let i=await HO(n,t),a=await Cn(n.source),d=await Cn(n.target),c,u=()=>c??=new ph({...tc(n),depth:n.depth,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,keepContactPoints:n.keepContactPoints,skipEmpty:!0,batchSize:"auto",excludedObjects:n.excludedObjects,...n.decisions},{reviewSkipped:!0}),l=new Map;l.set(n.source,bn(a)),l.set(n.target,bn(d));let f=new Map([...l].map(([b,T])=>[b,[wo(T)]])),p=b=>(f.get(b)??[]).reduce((T,C)=>T+C(),0),h,g=new Map,m,y=`sandforge-clone-${Hs()}`,k,O=b=>{if(h===void 0||n.dryRun||n.listObjects||n.rehearse)return;let T=c?.fit();Vs(n.audit,g,{action:"forge_execute",module:"forge",operationId:y,orgId:h,...b,...k?{muted:mo(k)}:{},...T?{fit:T}:{}})},R;if(!n.dryRun&&!n.listObjects){let b=await un(l.get(n.target));R=b,h=b.id,g.set(b.id,{alias:n.target,username:d.username}),n.audit&&!n.rehearse&&(m=(await un(l.get(n.source))).id,g.set(m,{alias:n.source,username:a.username}));let T=Zr(n.target,b,"clone");T&&(O({outcome:"stopped",code:"PRODUCTION_TARGET",context:u().context()}),process.stderr.write(`${T}
|
|
890
|
-
`),process.exit(1))}let w;if(o){let b=await un(l.get(n.source));w=b.id;let T=Zr(n.source,b,"clone")!==void 0;T&&!n.anonymizeGiven&&(n={...n,anonymize:!0},n.files&&!n.files.acceptedAsIs&&(process.stderr.write(`--files: ${n.source} is a production org, whose personal data a clone of the whole org anonymizes unless --no-anonymize is given, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, give --no-anonymize, or leave out --files.
|
|
891
|
-
`),process.exit(2))),s(n.anonymize?`anonymize: on${T&&!n.anonymizeGiven?`, ${n.source} being a production org (--no-anonymize copies its personal data as it is)`:""}`:`anonymize: off, the personal data copied as ${n.source} holds it`)}let A=await CR(n,async b=>{let T=l.get(n.source);return(await vo({query:async C=>T.query(C),queryMore:async C=>T.queryMore(C)},b,wn+1)).records},i);if(A&&"refused"in A){let{refused:b}=A;O({outcome:"stopped",code:b.code,context:u().context()}),process.stderr.write(`${Ot(b)}
|
|
892
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:lr({target:p(n.target),source:p(n.source)},{})},b)),process.exit(1)}let S=A?.chosen;if(!n.listObjects){let b=await Rs(n.ownerMappings,async T=>(await l.get(n.target).query(T)).records);if(b){O({outcome:"stopped",code:b.code,context:u().context()});let T={code:b.code,message:b.message};process.stderr.write(`${Ot(T)}
|
|
893
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:lr({target:p(n.target),source:p(n.source)},{})},T)),process.exit(1)}}let v=n.checkpointFirst?Eg({module:"forge",operationId:y,request:n.checkpointFirst,session:d,org:vg(d,R??await un(l.get(n.target))),connect:b=>{let T=bn(b);return f.get(n.target)?.push(wo(T)),T},journalDir:kt(),say:s}):void 0,j=[...l.values()].map(wo),P=()=>j.reduce((b,T)=>b+T(),0),B={...tc(n),depth:n.depth,customDepth:n.depth==="custom"?n.customDepth:void 0,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,skipEmpty:!0,batchSize:"auto",...(n.tables||o)&&Object.keys(n.objectSoqlFilters).length>0?{objectSoqlFilters:n.objectSoqlFilters}:{},...o&&n.excludedObjects.length>0?{excludedObjects:n.excludedObjects}:{}},I=new ll,z=new Set,Z=Pb(async(b,T)=>{z.add(`${b}::${T}`);let C=l.get(b);if(!C)throw new Error(`No connection for ${b}`);return C.sobject(T).describe()}),H=new Map,U={describeObject:async(b,T)=>Ib(await Z(b,T)),queryCount:async(b,T,C,N)=>{let x=l.get(b);if(!x)throw new Error(`No connection for ${b}`);return(await x.query(T,N?.all?{scanAll:!0}:void 0)).totalSize},detectPII:b=>ul(I,b),describeGlobal:b=>{let T=H.get(b);if(!T){let C=l.get(b);if(!C)throw new Error(`No connection for ${b}`);T=C.describeGlobal().then(N=>N.sobjects.map(x=>o?{name:x.name,keyPrefix:x.keyPrefix??null,queryable:x.queryable,createable:x.createable,updateable:x.updateable,deletable:x.deletable,customSetting:x.customSetting,layoutable:x.layoutable}:{name:x.name,keyPrefix:x.keyPrefix??null})),H.set(b,T)}return T},...o?{toolingObjects:async b=>{let T=l.get(b);if(!T)throw new Error(`No connection for ${b}`);return(await T.tooling.describeGlobal()).sobjects.map(C=>C.name)},recordCounts:async b=>{let T=l.get(b);if(!T)throw new Error(`No connection for ${b}`);return T.request(`/services/data/v${T.version}/limits/recordCount`)},createFacts:async b=>(await pa(im(l,Z,z),b)).facts}:{}},J=await WO(n,U.describeGlobal),je=await LO(J,n.target,{createable:async b=>(await Z(n.target,b)).createable!==!1,whyNot:b=>of((T,C)=>UO(l,T,C),async T=>(await pa(im(l,Z,z),T)).facts)(n.target,b)});je&&(O({outcome:"stopped",code:je.code,context:u().context()}),process.stderr.write(`${Ot(je)}
|
|
894
|
-
`),n.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,refused:je,elapsedMs:Fe(t)},null,2)}
|
|
895
|
-
`),process.exit(1));let pe=(n.tables??[]).flatMap(({objectApiName:b})=>{let T=Wy(b);return T!==void 0?[T]:[]});if(pe.length>0){let b={code:BO,message:`${pe.join(" ")} ${uc}`};O({outcome:"stopped",code:b.code,context:u().context()}),process.stderr.write(`${Ot(b)}
|
|
896
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t)},b)),process.exit(2)}s("discovery\u2026");let ae=new mf(U),K={source:p(n.source),target:p(n.target)},X=o?await oR(ae,B,s):await ae.discover(B,n.maxNodes===void 0?void 0:{maxNodes:n.maxNodes}),ce={source:p(n.source)-K.source,target:p(n.target)-K.target};o&&s(iR(ce,n.source,n.target));let Te=o?void 0:X.nodes[0]?.objectApiName;Te!==void 0&&n.excludedObjects.includes(Te)&&(process.stderr.write(`${Tn(`--exclude-object ${Te}`,`the resource's template leaves out ${Te}`)}: the ${n.tables?"first table":"record"} to clone is of this object, and nothing would be left to clone.
|
|
897
|
-
`),process.exit(2));let we=n.tables?Ly(X,n.tables):[];we.length>0&&(process.stderr.write(`${_y(we,{root:Te??n.tables?.[0]?.objectApiName??"",objects:X.nodes.length,depth:n.depth,customDepth:n.customDepth,truncated:X.truncated===!0,env:Kt()})}
|
|
898
|
-
`),process.exit(2));let de=n.tables?zy(n,X):o?Qy(n):B,_=de.excludedObjects??n.excludedObjects,L=o?Xy(X,new Set(_)):MR(es(X,new Set(_)),n.anonymizeFields),Re=new nf().generate(L);if(s(o?nR(L,Re,n.source):tR(L,Re,n.maxNodes??hf)),n.listObjects){let b=PR(L),T=b.map(C=>` ${C.objectApiName.padEnd(42)}${String(C.recordCount).padStart(8)} depth ${C.depth}${C.included?"":" (excluded)"}`);s(`
|
|
899
|
-
objects in the graph (${L.nodes.length}):`),s(T.join(`
|
|
900
|
-
`)),L.truncated&&s(`
|
|
901
|
-
The graph was truncated: discovery stopped before it had walked everything. Raise --max-nodes if an object you need is missing.`),n.json&&process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"list-objects",source:n.source,target:n.target,...n.tables?{tables:n.tables}:o?{wholeOrg:!0}:{record:n.record},graph:_s(L,Re),objects:b,...o?{leftOut:us(L)}:{},elapsedMs:Fe(t)},null,2)+`
|
|
902
|
-
`);return}let Ie=await Lb(n.fieldExclusions,L,async b=>(await Z(n.source,b)).fields.map(T=>T.name)),Ne=Ie.length>0?{code:Qd,message:qg(Ie,n.choicesFrom).replace(/ Nothing was read or written\.$/,"")}:void 0;if(Ne!==void 0&&!n.dryRun){O({outcome:"stopped",code:Qd,context:u().context()});let b={code:Qd,message:qg(Ie,n.choicesFrom)};process.stderr.write(`${Ot(b)}
|
|
903
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:lr({target:p(n.target),source:p(n.source)},{},o?ce:void 0)},b)),process.exit(2)}Ne!==void 0&&s(` ${Nn(Ne)}`);let he=o?Kp(L):void 0;he&&(O({outcome:"stopped",code:he.code,context:u().context()}),process.stderr.write(`${Ot(he)}
|
|
904
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:lr({target:p(n.target),source:p(n.source)},{},ce)},he)),process.exit(1));let Ke=b=>(O({outcome:"stopped",code:b.code,context:u().context()}),process.stderr.write(`${Ot(b)}
|
|
905
|
-
`),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:lr({target:p(n.target),source:p(n.source)},{},ce)},b)),process.exit(Qg(b.code))),ve=kt(),E="",W;if(n.sample){let b=h??(await un(l.get(n.target))).id,T={...w?{sourceOrgId:w}:{}};E=ed(L,_g(n,b,T));let C=n.sample.options.plan;if(C!==void 0)try{if(W=await sr.open(C,{sourceOrgId:n.source,fingerprint:E}),W.ageMs(new Date)>=Op)throw new ks("gone","The plan of this sample is a day old or more.")}catch(N){let x=fs(N,"replay");if(!x)throw N;Ke({code:x.code,message:x.message.replace(/ Nothing was written\.$/,` Given: ${C}. Nothing was written.`)})}}let q=!n.dryRun&&!n.rehearse?Pt(ve):void 0,ge=(b,T)=>_g(n,b,{...w?{sourceOrgId:w}:{},...T?{planSha256:T}:{}}),ee=h!==void 0?ed(L,ge(h,W?.sha256)):"",te,G,Oe=n.muteAutomation;if(q&&h!==void 0&&n.resume){te=Dg(n.resume,q);let b=js(te,{journalId:lc(te).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,resumes:!0});if("busy"in b)return Ke({code:Ai,message:`--resume ${te}: ${sd(b.busy)}. Two runs would write it at once: ${id(b.busy)}, then take it up. Nothing was written.`});e.journalLock=b.lock;let T=h,C=await Rb(q,te,{target:n.target,targetOrgId:h,graph:L,setup:ge(h),sample:{asked:n.sample!==void 0,setupWith:x=>ge(T,x)},config:de,...n.record?{record:n.record}:{}});C&&Ke(C),G=await q.lastEndAt(te),(await q.headAt(te))?.resume?.muteAutomation===!0&&(Oe=!0),s(`taking up the run of ${te}`);let N=await q.reconcileAt(te,Ss(l.get(n.target)));for(let x of Ts(N,n.target))s(x);if(As(N)>0&&!n.writeUncertain){let x=yb(N),Q={code:"RESUME_UNCERTAIN",message:wb(N,n.target),...x!==void 0?{retryAt:x}:{}};Ke(Q)}}let ye=new Xp,ue=new AbortController,Ct={},lt,Tt=b=>{lt=b,process.stderr.write(`
|
|
906
|
-
interrupted: the clone stops after the call under way, and says what it created (Ctrl-C again ends it at once)
|
|
907
|
-
`),ye.stop(void 0,{discovery:()=>{},run:()=>{ue.abort(),Ct.executor?.abort()}})};if(!n.dryRun&&!n.rehearse&&!n.listObjects){ye.beginRun(y,ue);let b=Xn(Tt);e.release=()=>{b(),ye.endRun(y)}}let yt=async b=>{ue.signal.aborted&&(O({outcome:"stopped",code:Wi,context:u().context()}),await b?.(),s("interrupted: the clone stopped before it wrote anything"),process.exit(vr(lt??"SIGINT")))},nt=await ni(l.get(n.target)).readForGraph(n.target,L,new Set(_));s("");for(let b of ff(nt,n.target,{applyAssignmentRules:n.applyAssignmentRules,mayMute:St("--mute-automation"),mayApplyAssignmentRules:St("--apply-assignment-rules")}))s(b);let At=Qc(nt,new Set(_));for(let b of Lf(At,n.target,nt.unread,Tn("--remove","destroy, or a replace")))s(b);s(n.keepContactPoints?`contact points: written as read (${Tn("--keep-contact-points","keepContactPoints")})`:"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range)");let dt=await BR(l,Z,z).read(n.source,n.target,L,{inputMode:B.inputMode,recordId:B.recordId,maxRecordsPerObject:n.maxRecordsPerObject,fieldExclusions:n.fieldExclusions,fieldMappings:n.fieldMappings,excludedObjects:_}),Xt={...n.decisions,fieldExclusions:n.fieldExclusions,excludedObjects:_},ke=Mf(L,{leftOut:new Set(_),upsert:n.upsert}),ft=new Set(ke.map(b=>b.objectApiName)),_e=(b,T)=>T==="insert"||T==="update"&&ft.has(b),pt=Oe?wl(nt,_e).plan.alsoLifts:void 0;s("");for(let b of df(dt,n.target,{decisions:Xt,...pt?{lifted:pt}:{}}))s(b);let $t=n.upsert&&!n.keepContactPoints?Jb(await Promise.all(L.nodes.filter(b=>b.included).map(async({objectApiName:b})=>({objectApiName:b,fields:await Z(n.source,b).then(T=>T.fields).catch(()=>[])})))):[];for(let b of Qb($t,n.target))s(b);let F,Y,ne={},Ee=()=>({apiRequests:lr({target:p(n.target),source:p(n.source)},ne,o?ce:void 0)}),re=(b,T=[],C=1)=>{let N={...b,message:Xr(b.message)},x=T.map(Q=>({...Q,message:Xr(Q.message)}));for(let Q of[N,...x])process.stderr.write(`${Ot(Q)}
|
|
908
|
-
`);return n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),...Ee()},N,x)),process.exit(C)};if(Oe){n.muteAutomation||s(" mute: the run taken up was muted, and so is this part of it");try{F=await na(async()=>ea(l.get(n.target)),nt,{writes:_e});for(let b of er(F.muted,n.target))s(` ${b}`)}catch(b){if(!Nr(b))throw b;n.dryRun||(O({outcome:"stopped",code:b.code,context:u().context()}),re(b.refusal)),Y=b.refusal,s(` ${Nn(b.refusal)}`)}}let oe=F?.automation??nt,rt=Wf(oe,n.target,{updated:ke,assign:ps(oe,Bf(oe,ke.map(b=>b.objectApiName))),mayMute:!Oe&&St("--mute-automation")});u().automationRead({automation:oe},ke),rt&&n.acceptAutomation&&u().confirm("automation");let fe=n.rehearse?void 0:await ml({read:nt,...F?.plan?{plan:F.plan}:{},writes:_e,applyAssignmentRules:n.applyAssignmentRules,readDeliverability:async()=>{let b=l.get(n.target),T=R??await un(b);return Zr(n.target,T,"clone")!==void 0?hl:gl(b)},accepted:n.acceptEmails,target:n.target,run:"clone",keepsAddresses:n.keepContactPoints,mayMute:!Oe&&St("--mute-automation")});fe?.gate.line!==void 0&&s(` ${fe.gate.line}`),u().emailsRead(fe?.gate.audit),fe?.gate.verdict==="asks"&&n.acceptEmails&&u().confirm("emails");let qe=fe?.gate.stop,Ve=[...Ne!==void 0?[Ne]:[],...Y!==void 0?[Y]:[]],bt=rt!==void 0&&!n.acceptAutomation;(bt||qe)&&!n.dryRun&&(O({outcome:"stopped",code:bt?"AUTOMATION_NOT_ACCEPTED":Ff,context:u().context()}),bt&&re({code:"AUTOMATION_NOT_ACCEPTED",message:rt},qe?[qe]:[]),qe&&re(qe)),bt&&(Ve.push({code:"AUTOMATION_NOT_ACCEPTED",message:rt}),s(" a real run would be refused (AUTOMATION_NOT_ACCEPTED): it writes nothing without --accept-automation: see what fires as it inserts and updates, or could not be read, above")),qe&&(Ve.push(qe),s(` ${Nn(qe)}`)),await yt(),s("record-type mapping\u2026");let Zt=P(),En=[],Nt=await xb(l.get(n.source),l.get(n.target),b=>En.push(b)),Kn=P()-Zt;s(`record-types: ${Nt.length} mappings`);for(let b of En)s(` warning: ${b}`);await yt();let vt={statements:0,pages:0},Je=!1,en=b=>(b.some(T=>T.success)&&(Je=!0),b),Ze=o?new Qp(async(b,T)=>(await Vi(fr(l,b)).bulk2.job("ingest",{id:T}).check()).state):void 0,_t={...o?_O(l,n,Ze,()=>Je=!0):{},queryRecords:async(b,T,C)=>{let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);let{records:x,truncated:Q}=await vo({query:async Be=>N.query(Be),queryMore:async Be=>N.queryMore(Be)},T,n.readCeiling);return Q&&C?.(),x},queryPages:(b,T,C)=>{let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);return vt.statements++,Tu({query:async x=>(vt.pages++,N.query(x)),queryAll:async x=>(vt.pages++,N.query(x,{scanAll:!0})),queryMore:async x=>(vt.pages++,N.queryMore(x))},T,C)},countRecords:async(b,T,C)=>{let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);return(await N.query(T,C?.all?{scanAll:!0}:void 0)).totalSize},queryTooling:async(b,T)=>{let C=l.get(b);if(!C)throw new Error(`No connection for ${b}`);return(await C.tooling.query(T)).records},insertRecords:async(b,T,C)=>{if(n.dryRun)return C.map(()=>({id:"",success:!0,errors:[]}));let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);let x=await N.sobject(T).create(C,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})});return en(Ki(x,T))},updateRecords:async(b,T,C)=>{if(n.dryRun)return[];let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);let x=await N.sobject(T).update(C,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})}),Q=Array.isArray(x)?x:[x];return en(Q.map((Be,Rt)=>({id:Be.id??C[Rt].Id??"",success:Be.success,errors:(Be.errors??[]).map(Yu),errorDetails:(Be.errors??[]).map(Qu)})))},describeFields:async(b,T)=>Eb(await Z(b,T)),isObjectCreatable:async(b,T)=>(await Z(b,T)).createable!==!1,describeObject:async(b,T)=>{let C=l.get(b);if(!C)throw new Error(`No connection for ${b}`);return Kd(C,T)},describeObjectAgain:async(b,T)=>{let C=l.get(b);if(!C)throw new Error(`No connection for ${b}`);return Kd(C,T,!0)},recordTypePicklists:async(b,T,C)=>{let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);return Zp(N,T,C)},upsertRecords:async(b,T,C,N)=>{if(n.dryRun)return N.map(()=>({id:"",success:!0,errors:[]}));let x=l.get(b);if(!x)throw new Error(`No connection for ${b}`);let Q=await x.sobject(T).upsert(N,C,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})});return en(Ki(Q,T))},readFileBody:async(b,T,C)=>{let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);return eh(N,T,C)},insertFile:async(b,T,C)=>{if(n.dryRun)return{id:"",success:!0,errors:[]};let N=l.get(b);if(!N)throw new Error(`No connection for ${b}`);let[x]=en([await th(N,T,C)]);return x},remainingFileStorageMB:async b=>{let T=l.get(b);if(!T)throw new Error(`No connection for ${b}`);return nh(T)},requestsSent:P,runningUser:async b=>{let T=l.get(b);if(!T)throw new Error(`No connection for ${b}`);return(await T.identity()).user_id},orgCurrency:async b=>{let T=l.get(b);if(!T)throw new Error(`No connection for ${b}`);return $u(await T.soap.getUserInfo())}},Mt={};if(n.roots){try{Mt.sourceRequestsLeft=(await Dn(l.get(n.source))).remaining}catch{}i&&(Mt.plan=i),S&&(Mt.chosen=S),n.dryRun&&n.roots.plan!==void 0&&(qs(n.roots.plan,{force:!0}),Mt.keepAt=n.roots.plan)}if(n.rehearse){let b=l.get(n.target),T=Sr({applyAssignmentRules:n.applyAssignmentRules});s(`
|
|
909
|
-
rehearsing\u2026 (the rows are read and prepared as the run would; nothing stays in the target)`);let C;try{C=await dd({prepare:async x=>{await new ur(ad(_t,x)).execute(L,n.source,n.target,()=>{},{...Yg(n,L,Nt,Q=>ae.personalFields(Q),Mt),dryRun:!1,files:void 0})},keyPrefixOf:async x=>(await Kd(b,x)).keyPrefix,runningUser:async()=>(await b.identity()).user_id,composite:x=>b.request({method:"POST",url:"/composite",body:JSON.stringify(x),headers:{"Content-Type":"application/json",...T}}),apiPath:`/services/data/v${b.version}`,writeHeaders:T,recordTypeNames:new Map(Nt.map(x=>[x.targetId.slice(0,15),x.developerName])),targetRecordTypes:Pg(_t,n.target),targetFields:x=>_t.describeFields(n.target,x),validationRules:async()=>gh(dt.gaps),confirm:async x=>{s("");for(let Q of WR(x,n.target))s(Q)},onProgress:x=>{x.phase==="rehearsing"&&s(` call ${x.call} of ${x.calls}\u2026`)}})}catch(x){throw x instanceof mh&&(process.stderr.write(`${x.message}
|
|
910
|
-
`),process.exit(1)),x}let N=Fe(t);s("");for(let x of DR(C,n.target,pt?{lifted:pt}:{}))s(x);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"rehearse",source:n.source,target:n.target,...h?{targetOrgId:h}:{},record:n.record,graph:_s(L,Re),targetAutomation:nt,rehearsal:_R(C,pt),elapsedMs:N},null,2)+`
|
|
911
|
-
`):console.log(`
|
|
912
|
-
done in ${N}ms`);return}if(!n.skipPreflight){s(`
|
|
913
|
-
preflight (target row counts)\u2026`);let b=l.get(n.target),T=L.nodes.slice(0,30),C=[];for(let x of T)try{let Q=await b.query(`SELECT COUNT() FROM ${x.objectApiName}`);C.push({name:x.objectApiName,existing:Q.totalSize})}catch{C.push({name:x.objectApiName,existing:-1})}let N=C.filter(x=>x.existing>0);if(N.length===0)s(" target is empty for all sampled objects.");else{let x=N.sort((Q,Be)=>Be.existing-Q.existing).slice(0,10);s(` ${N.length}/${C.length} sampled objects have existing rows. Top 10:`);for(let Q of x){let Be=Q.existing>1e3?" \u26A0":"";s(` ${Q.name.padEnd(40)} ${String(Q.existing).padStart(8)}${Be}`)}L.nodes.length>T.length&&s(` (sampled first ${T.length}/${L.nodes.length} nodes; --skip-preflight to bypass)`)}}await yt();let Et=l.get(n.target),Bt=Of(Et,h??d.orgId),ot,Me,In=[],Vn={},eo,xn,ai=async(b,T)=>{if(!v||T.totalRows===0)return;let C=new Set(T.objects.map(({objectApiName:x})=>x)),N={written:b.objects.map(({objectApiName:x})=>x).filter(x=>C.has(x)),running:{firing:Yn(oe,void 0,_e).firing}};try{Me={ask:N,estimate:await v.scope(N)};return}catch(x){return ya(x).replace(/ Nothing was written\.$/,"")}},$=b=>({unread:V(b)}),D=()=>({target:Math.max(0,p(n.target)-(fe?.ofRun.read?.requests??0)),source:p(n.source)}),me=async b=>{let T=b.wholeOrg;if(!T)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 C=jf(T.readWholeOver);if(C&&!b.dryRun)throw Pe.of({...C,message:Kg(C.message,T.sample!==void 0)});let N=vf(b.objects,T),x=hs({firing:Yn(oe,void 0,_e).firing},(se,xt)=>_e(se,xt)).perRecord,Q=T.sample?.report;Q&&(xn=Q,u().sampled(Q));let Be=await ai(b,N),Rt=[...ft],gt,Lt,Qe,st,qt;if(b.dryRun)gt=await Ef({objects:b.objects,measures:T,graph:L,anonymizePII:n.anonymize,updatedAfterInsert:Rt,...Me?{checkpoint:Me.estimate}:{},...b.readBack!==void 0?{readBack:b.readBack}:{},mute:Go(F?.plan),deliverability:fe?.ofRun.read?.requests??0,sentBefore:D,...Q?{sample:Q}:{},...Q&&n.sample?{sampleAsked:rc(n.sample)}:{},automation:x,target:{org:n.target,limits:Bt},source:{org:n.source,limits:fr(l,n.source)}}),Lt=Vp(gt),Qe=gt.storage,st=gt.files,qt=gt.wouldBeRefused;else{let se=await as(Bt).catch($),xt="unread"in se?await Dn(Et).catch($):se.dailyApiRequests;Qe=Ra(N,se,cs(N,x));let co=xa(Qe,n.target),hi=Q?Pf({sample:Q,storage:se,target:n.target,...n.sample?{asked:rc(n.sample)}:{}}):void 0,gi=$f(T.files,se,n.target);st=gi.files;let Km=await Dn(fr(l,n.source)).catch($),$c=D(),Or=ba({plan:N,updatedAfterInsert:Rt,...b.readBack!==void 0?{readBack:b.readBack}:{},...Me?{checkpoint:Me.estimate}:{},mute:Go(F?.plan),...Ea(fe?.ofRun),sentBefore:$c.target,budget:xt,target:n.target,wholeOrg:{measures:T,bulkBatches:"unread"in se?se:se.dailyBulkApiBatches,sourceBudget:Km,source:n.source,sourceSentBefore:$c.source}});Lt={api:Or.api,wholeOrg:Or.wholeOrg},qt=[...hi?[hi]:[],...hi===void 0&&co!==void 0&&Qe.verdict==="exceeds"?[{code:"STORAGE_EXCEEDED",message:`${co} Nothing was written.`,storage:{estimateMB:Number(Wt(Qe.estimateMB)),remainingMB:Qe.remainingMB,...ds(Qe)}}]:[],...gi.stop?[gi.stop]:[],...Or.stop?[Or.stop]:[],...Or.alsoRefused??[]]}let wr=Q?void 0:fR(Qe,n.target);wr!==void 0&&(qt=qt.map(se=>se.code==="STORAGE_EXCEEDED"?{...se,message:`${wr} Nothing was written.`}:se));let yr={...Jp({run:{source:n.source,graph:L,anonymizePII:n.anonymize,...le()},measures:T,plan:N,budget:Lt,...st?{files:st}:{},...Q?{sample:Q,now:Date.now()}:{}}),discovery:ce};if(ne={target:Lt.api,source:Lt.wholeOrg.source},eo={...gt?{dry:gt}:{},question:yr},s(""),Q)for(let se of SR(Q,{source:n.source,target:n.target,dryRun:b.dryRun===!0,replayed:n.sample?.options.plan!==void 0}))s(se);for(let se of Pa(N,Qe,n.target))s(se);let br=dR(T,n.source,n.target);br!==void 0&&s(br);for(let se of sR(yr,us(L).counts,n.target,T.writes))s(se);if(Me)for(let se of qd(Me.estimate))s(se);let io=Si(oe),Rr;if(io.length>0){let se=await Sa(Et).catch($),xt=Ta(N,io,se);for(let co of va(xt,n.target))s(co);Rr=$a(xt,n.target)}let ao=ja(oe,Aa(N));ao!==void 0&&s(` emails: not counted, ${ao} could not be read`);let mn=se=>Xr(Kg(se,Q!==void 0)).replace(/ Nothing was written\.$/,""),Ae=[...N.totalRows>n.maxTotal?[{code:"MAX_TOTAL_EXCEEDED",message:cR(N.totalRows,n.maxTotal,Q!==void 0,n.dryRun)}]:[],...Be!==void 0?[{code:Sn,message:Be}]:[],...qt.map(se=>({code:se.code,message:se.code===Sn&&se.refusal!==void 0?Ws(se.refusal):mn(se.message),stop:se})),...Rr!==void 0?[{code:"EMAILS_EXCEEDED",message:Rr}]:[]];if(gt){for(let{code:se,message:xt}of Ae)s(` ${Nn({code:se,message:xt})}`);throw Ve.push(...Ae.map(({code:se,message:xt})=>({code:se,message:xt}))),ot={totalRows:N.totalRows,storageBytes:N.storageBytes,objects:N.objects,...N.leftOut?{leftOut:N.leftOut}:{}},new td(gt)}let Ue=se=>`${se} Nothing was written.`,[xe,...pi]=Ae;if(xe)throw In=pi.map(({code:se,message:xt})=>({code:se,message:Ue(xt)})),xe.stop?Pe.of({...xe.stop,message:Ue(xe.message)}):new Pe(xe.code,Ue(xe.message));Vn=Hi(Lt.api),await Ce(yr,N,Q)},le=()=>{let b=Hp(de);return b?{carried:b}:{}},Ce=async(b,T,C)=>{let N=Hg(b,T,n.target,C);if(n.yes){s(` --yes: written without the question: ${N}`),u().confirm("volume");return}if(process.stdin.isTTY!==!0)throw new Pe("CONFIRMATION_UNAVAILABLE",`A clone of the whole org asks before it writes ${N}, and no terminal is there to answer: give --yes to write it. Nothing was written.`);let x=await Yf(zg(N),void 0,ue.signal);if(ue.signal.aborted)throw new Zs("interrupted at its question: the clone stopped before it wrote anything");if(!x)throw new Pe("WRITE_DECLINED","The clone of the whole org was declined at its question. Nothing was written.");u().confirm("volume")},ht=async b=>{if(o)return me(b);let T=Rf(b.objects),C;try{C=await as(Bt)}catch(Ae){C={unread:V(Ae)}}let N=hs({firing:Yn(oe,void 0,_e).firing},(Ae,Ue)=>_e(Ae,Ue)).perRecord,x=Ra(T,C,cs(T,N));s("");for(let Ae of Pa(T,x,n.target))s(Ae);let Q="unread"in C?await Dn(Et).catch(Ae=>({unread:V(Ae)})):C.dailyApiRequests,Be;if(v&&T.totalRows>0){let Ae=new Set(T.objects.map(({objectApiName:xe})=>xe)),Ue={written:b.objects.map(({objectApiName:xe})=>xe).filter(xe=>Ae.has(xe)),running:{firing:Yn(oe,void 0,_e).firing}};try{Me={ask:Ue,estimate:await v.scope(Ue)}}catch(xe){Be=ya(xe).replace(/ Nothing was written\.$/,"")}}let Rt=ba({plan:T,updatedAfterInsert:[...ft],...b.readBack!==void 0?{readBack:b.readBack}:{},...Me?{checkpoint:Me.estimate}:{},mute:Go(F?.plan),...Ea(fe?.ofRun),sentBefore:D().target,budget:Q,target:n.target});if(Vn=Hi(Rt.api),ne={target:Rt.api},s(xy(Rt.api,n.target)),Me)for(let Ae of qd(Me.estimate))s(Ae);let gt=Si(oe),Lt,Qe;if(gt.length>0){let Ae=await Sa(Et).catch(xe=>({unread:V(xe)})),Ue=Ta(T,gt,Ae);for(let xe of va(Ue,n.target))s(xe);Lt=$a(Ue,n.target),Qe=Ue.map(xe=>({limit:xe.limit,emails:xe.emails}))}let st=ja(oe,Aa(T));st!==void 0&&s(` emails: not counted, ${st} could not be read`);let qt=n.roots?.query?.roots,wr=Vg(b,qt,{taken:T.totalRows,room:n.maxTotal,each:Ae=>`about ${Math.ceil(Ae)} records`,past:`the ${n.maxTotal} --max-total holds the run to`}),yr=T.totalRows>n.maxTotal?wr?uR(T.totalRows,n.maxTotal,wr,n.dryRun):wc(T.totalRows,n.maxTotal,n.dryRun):void 0,br=x.verdict==="exceeds"?Vg(b,qt,{taken:x.estimateMB,room:bf(x),each:Ae=>`about ${Wt(Ae)} MB`,past:`what ${n.target} has left`}):void 0,io=br?lR(x,n.target,br):xa(x,n.target),Rr=Be??(Rt.stop?.refusal!==void 0?Ws(Rt.stop.refusal):void 0),ao=Sf(Rt.api,n.target,el)?.replace(/ Nothing was written\.$/,""),mn=[[Sn,Rr],["MAX_TOTAL_EXCEEDED",yr],["STORAGE_EXCEEDED",io],["EMAILS_EXCEEDED",Lt],[kf,ao]].flatMap(([Ae,Ue])=>Ue!==void 0?[{code:Ae,message:Ue}]:[]);if(b.dryRun){for(let pi of mn)s(` ${Nn(pi)}`);Ve.push(...mn);let Ae=qe&&fe?Cf(fe.ofRun.senders,T):[],Ue=Nf(Ae);Ue!==void 0&&s(Ue);let xe=cs(T,N);ot={totalRows:T.totalRows,storageBytes:T.storageBytes,...xe>0?{automationBytes:xe}:{},objects:T.objects,...T.leftOut?{leftOut:T.leftOut}:{},...Qe!==void 0?{emails:Qe}:{},...st!==void 0?{emailsUncounted:st}:{},...Ae.length>0?{emailSendersOfNothingWritten:Ae}:{}};return}if(mn.length>0){let Ae=Ue=>`${Ue} Nothing was written.`;throw In=mn.slice(1).map(({code:Ue,message:xe})=>({code:Ue,message:Ae(xe)})),new Pe(mn[0].code,Ae(mn[0].message))}h!==void 0&&!n.rehearse&&hu({action:"forge_execute",orgId:h,operationId:y},x.estimateMB)},hr=n.dryRun||n.rehearse?void 0:await lh(()=>Et.identity(),"sandforge clone");s(`
|
|
914
|
-
executing\u2026 (${n.dryRun?"DRY-RUN":"REAL"}${n.tables?", WHOLE TABLES":""}${o?", WHOLE ORG":""}${n.upsert?", UPSERT":""}${n.expandOrphans?", EXPAND-ORPHANS":""}${n.applyAssignmentRules?", ASSIGNMENT-RULES":""}${n.files?", FILES":""}${n.pageSize!==void 0?`, READ IN PAGES OF ${n.pageSize}`:""})`);let to=b=>b.apiCalls===void 0?b:{...b,apiCalls:b.apiCalls+Kn},no=(b,T,C={},N)=>({tool:"sandforge-clone",version:1,source:n.source,target:n.target,...h?{targetOrgId:h}:{},...n.tables?{objects:n.tables}:o?{wholeOrg:!0}:n.roots?{roots:Db(n.roots,L)}:{record:n.record},dryRun:n.dryRun,upsert:n.upsert,expandOrphans:n.expandOrphans,applyAssignmentRules:n.applyAssignmentRules,files:n.files!==void 0,...n.choicesFrom?{choices:{from:n.choicesFrom.flag,file:n.choicesFrom.path,...n.decisions?{decisions:n.decisions}:{}}}:{},graph:_s(L,Re),...xn?{sample:Jg(xn)}:{},targetAutomation:fe?.ofRun.read?{...nt,deliverability:fe.ofRun.read.reading}:nt,...k?{mutedAutomation:k}:n.dryRun?ta(F):{},...Ee(),removalRisks:At,targetGaps:ga(dt,Xt),...Yb(n.dryRun,dt,b.gaps,pt),...$t.length>0?{neutralizedUpsertKeys:$t}:{},result:{...N?{status:N}:{},...Xb(b,n.readCeiling),...hr?{runUserId:hr}:{}},...n.dryRun&&ot!==void 0?{writePlan:ot}:{},...yc(),...n.dryRun?ji(Ve):{},elapsedMs:Fe(t,T.getTime()),finishedAt:T.toISOString(),...te&&gn?{journal:te}:{},...ci()!==void 0?{part:ci()}:{},...li.length>0?{bulkJobsPastMute:li}:{},...C}),Dm=b=>{let T=eo?.question;return{tool:"sandforge-clone",version:1,source:n.source,target:n.target,dryRun:!0,anonymize:n.anonymize,files:n.files!==void 0,graph:_s(L,Re),result:{wouldInsertCount:ot?.totalRows??b.totalRows,failedCount:0},...ot!==void 0?{writePlan:ot}:{},targetAutomation:fe?.ofRun.read?{...nt,deliverability:fe.ofRun.read.reading}:nt,...ta(F),removalRisks:At,targetGaps:ga(dt,Xt),wholeOrg:{...b.sample?{sample:Jg(b.sample)}:{},wouldInsert:b.wouldInsert,totalRows:b.totalRows,requests:{target:b.targetRequests,source:b.sourceRequests},...b.bulkBatches?{bulkBatches:b.bulkBatches}:{},storage:b.storage,...b.files?{files:b.files}:{},durationSeconds:b.durationSeconds,leftOut:b.leftOut,personalAsIs:b.personalAsIs,...b.personAccountsAsBusiness!==void 0?{personAccountsAsBusiness:b.personAccountsAsBusiness}:{},managedPackages:T?.managedPackages??[],...T?.contactPointsBlanked!==void 0?{contactPointsBlanked:T.contactPointsBlanked}:{},...T?.carried?{carried:T.carried}:{},...T&&ot&&Ve.length===0?{question:zg(Hg(T,ot,n.target,xn))}:{}},...yc(),...Ee(),...ji(Ve),elapsedMs:Fe(t)}},hn,gr,yc=()=>{let b=n.dryRun?Me?.estimate:gr??hn;return b!==void 0?{checkpoint:b}:{}},di=async()=>{if(!(!v||!hn||gr)){try{gr=await v.settle(hn,Je)}catch(b){gr=hn,s(`warning: the checkpoint '${hn.name}' taken before the run, which wrote nothing, could not be deleted (${V(b)}): delete it with ${Ut("checkpoint")} delete --org ${n.target} --checkpoint ${hn.checkpointId}`)}for(let b of Gd(gr))s(b)}},gn,It;if(q&&h!==void 0){if(te&&n.resume)await q.resumingAt(te),It=(await q.headAt(te))?.journalId;else{It=`sandforge-clone-${new Date(t).toISOString().replace(/[:.]/g,"-")}-${Hs().slice(0,8)}`,te=q.pathOf(It);let b=js(te,{journalId:It,ranFrom:"commandLine",target:n.target});"lock"in b&&(e.journalLock=b.lock),await q.begin(It,h,new Date,{sourceOrgId:n.source,fingerprint:ee,targetSalesforceOrgId:h,...n.record?{recordId:n.record}:{},...n.muteAutomation?{muteAutomation:!0}:{},...n.files?{files:n.files}:{},startedWith:{graph:L,config:de}},hr)}gn=q.openAt(te),s(Kt()?`journal: ${te}`:`journal: ${te} (--resume ${te} takes the run up if it stops)`)}let ci=()=>gn&&gn.partCount>0?gn.partCount-1:void 0,_m=async()=>{if(!n.sample||n.dryRun||n.resume||It===void 0)return;let b=Qa(ve,It);if(W&&Yt(b)&&!Yt(W.dir))try{am(b,W.dir);return}catch{}await jp(b)},mr=async(b,T)=>{if(!q||!te||!gn)return;gn.close();let C=te;try{!T&&G?await q.stopAt(C,G.status,G.forgeId):!T&&!n.resume?(qs(C,{force:!0}),qs(C.replace(/\.ndjson$/,".end.json"),{force:!0}),await _m()):await q.stopAt(C,b,`${It??"run"}#${ci()??0}`)}catch(N){process.stderr.write(`The journal ${C} could not be ended (${V(N)}).
|
|
915
|
-
`)}finally{e.journalLock?.release()}},bc;if(n.sample){let b=n.sample,T=W;if(W&&!n.dryRun&&It!==void 0)try{T=await Ap(W,ve,It)}catch(x){await mr("failure",!1),process.stderr.write(`The plan of --fit-plan ${W.dir} could not be moved beside the run's journal (${V(x)}): keep it in ${Ks(ve,"forge-samples")}, where its dry run put it. Nothing was written.
|
|
916
|
-
`),process.exit(1)}if(T)s(`sample: takes up the plan ${T.dir}, drawn ${T.manifest.drawnAt}: no root is drawn again`);else if(n.resume)s("sample: the run taken up goes on with the plan its journal names");else{s(jR(L,b.options,n.source));let x=n.dryRun?void 0:await Tp(ve,E,new Date).catch(()=>{});x instanceof sr&&s(` a dry run drew a plan of this setup at ${x.manifest.drawnAt}: this run draws its own; --fit-plan ${x.dir} writes that one's records instead`)}let C=hs({firing:Yn(oe,void 0,_e).firing},(x,Q)=>_e(x,Q)).perRecord,N=T||n.resume?void 0:await Dn(fr(l,n.source)).catch($);bc={options:fm(b),budget:async()=>{let x=await as(Bt).catch($),Q="unread"in x?await Dn(Et).catch($):x.dailyApiRequests,Be="unread"in x?void 0:x.dailyBulkApiBatches;return hR({storage:x,sample:b,target:n.target,automation:C,allowances:{...Q?{requests:Q}:{},...Be?{bulkBatches:Be}:{},sentBefore:D().target,updatedAfterInsert:[...ft]}})},keepAt:n.dryRun||It===void 0?kp(ve,E):Qa(ve,It),fingerprint:E,...T?{plan:T}:{},...N&&"remaining"in N?{sourceRequestsLeft:N.remaining}:{},onProgress:ER(s)}}let jt,qm=eR(L),ui=new ur(_t),Rc=!1,ro=b=>{if(!n.summary)return;let T=cc(n.summary,b);T&&!Rc&&(Rc=!0,process.stderr.write(`The summary could not be written to ${n.summary} (${T}).
|
|
917
|
-
`))},Oc=-1,Um=()=>{let b=ui.summarySoFar();if(!b)return;let T=b.successCount+b.linkedCount+b.updatedCount+b.failedCount;T!==Oc&&(Oc=T,ro(no(to(b),new Date,{running:!0})))};Ct.executor=ui,await yt(()=>mr("cancelled",!1));let oo,li=[],Gm,kc=()=>Gm??=qO(Ze,n.target,s).then(b=>{li=b.map(({objectApiName:T,jobId:C})=>({objectApiName:T,...C?{jobId:C}:{}}))}),zm=async b=>{if(await ht(b),b.dryRun||n.dryRun)return;if(v&&Me&&!hn){let N=Me,x=await Af(()=>v.take(N.ask,N.estimate,{signal:ue.signal}));if("stop"in x)throw x.stop.code!==Sn?new Xs(Ud(x.stop)):new Pe(Sn,Ud(x.stop));hn=x.checkpoint;for(let Q of Ig(x.checkpoint,n.target,Oe))s(Q)}if(!F?.prepared||oo)return Vn;let T=await F.prepared.acquire(`sandforge clone ${t}`).catch(async N=>{if(!Nr(N))throw N;return O({outcome:"stopped",code:N.code,context:u().context()}),await di(),re(N.refusal)});oo=T,k=T.outcome;let C=fe?.afterLease(T.outcome,n.acceptEmails);if(C)throw new Pe(C.code,C.message);return{...Vn,lease:{assigned:T.outcome.assigned.length,giveBack:async()=>(await kc(),T.release())}}};try{let b=await ui.execute(L,n.source,n.target,T=>{let C=qm(T);C&&s(C),n.summary&&NO.has(T.status)&&Um()},NR({...o?Yy(n,de,L,Nt,T=>ae.personalFields(T),bc):n.tables?Hy(n,de,L,Nt,T=>ae.personalFields(T)):Yg(n,L,Nt,T=>ae.personalFields(T),Mt),beforeWrite:zm},gn)).finally(async()=>{if(oo){await kc(),k=await oo.release();for(let T of er(k,n.target))s(T)}});jt=to(b),await di(),n.pageSize!==void 0&&s(`read in pages of ${n.pageSize}: ${vt.statements} statement(s) through the org's cursor, ${vt.pages} page(s) answered`)}catch(b){if(b instanceof td){let st=Dm(b.dryRun);n.json?process.stdout.write(`${JSON.stringify(st,null,2)}
|
|
918
|
-
`):console.log(`
|
|
919
|
-
done in ${st.elapsedMs}ms`),Ve.length>0&&process.exit(1);return}(b instanceof Xs||b instanceof Zs)&&(O({outcome:"stopped",code:Wi,context:u().context()}),await mr("cancelled",!1),s(b.message),process.exit(vr(lt??"SIGINT"))),await di();let T=b instanceof Pe?b:n.sample?fs(b,n.resume?"resume":"draw"):void 0,C=b instanceof An?b:void 0,N=T??C,x=N?void 0:Rp(b),Q=x?Di(x):void 0,Be=Q?_i(Q):[],Rt=lt!==void 0||b instanceof be,gt=N?"stopped":Rt?wu(x,Be):"failure";O({outcome:gt,...N?{code:N.code}:gt==="stopped"?{code:mu}:{},...Q?{objects:Be,...m?{source:{origin:"org",orgId:m}}:{},carried:Ui(Q)}:{},...qi(x?.contactPoints),context:u().context(x?.decisionsApplied)});let Lt=x!==void 0&&x.successCount+x.updatedCount+x.linkedCount>0;if(await mr(Rt?"cancelled":"failure",Lt),N){let st={code:N.code,message:N.message,...T?.sample?{sample:T.sample}:{}};re(st,T?In:[],Qg(N.code))}let Qe=x;if(Qe&&(lt!==void 0||b instanceof be)){let st=no(to(Qe),new Date,{interrupted:!0});if(ro(st),n.json)process.stdout.write(JSON.stringify(st,null,2)+`
|
|
920
|
-
`);else{console.log("");for(let qt of Ug(Qe,n.dryRun,n.readCeiling))console.log(qt)}s(MO(n.summary)),process.exit(vr(lt??"SIGINT"))}throw Qe&&ro(no(to(Qe),new Date,{error:V(b)})),b}finally{e.release?.()}await mr("success",!0);let Sc=Di(jt),so=$o(jt);O({outcome:so,objects:_i(Sc),...m?{source:{origin:"org",orgId:m}}:{},carried:Ui(Sc),...qi(jt.contactPoints),context:u().context(jt.decisionsApplied)});let Tc=new Date,Hm=Fe(t,Tc.getTime()),Ac=no(jt,Tc,{},so);ro(Ac);let fi;if(n.remapCsv){let b=["sourceId,targetId"];for(let[T,C]of Object.entries(jt.remapTable))b.push(`"${T.replace(/"/g,'""')}","${C.replace(/"/g,'""')}"`);try{cm(n.remapCsv,b.join(`
|
|
921
|
-
`)+`
|
|
922
|
-
`,{encoding:"utf8",flag:"wx"}),s(`remap-csv: wrote ${Object.keys(jt.remapTable).length} mappings to ${n.remapCsv}`)}catch(T){fi=T?.code==="EEXIST"?`--remap-csv refuses to overwrite existing file: "${n.remapCsv}"`:`--remap-csv ${n.remapCsv} could not be written: ${V(T)}`}}if(n.json)process.stdout.write(JSON.stringify(Ac,null,2)+`
|
|
923
|
-
`);else{console.log(""),console.log(`status: ${so}`);let b=(F?.plan?.assign.length??0)>0;for(let T of Ug(jt,n.dryRun,n.readCeiling,b))console.log(T);if(jt.roots){console.log("");let T={source:n.source,target:n.target,dryRun:n.dryRun,...n.roots?.plan!==void 0?{plan:n.roots.plan}:{},...n.resume!==void 0?{resumed:!0}:{}};for(let C of qb(jt,T))console.log(C)}if(jt.sample){console.log("");for(let T of AR(jt.sample,n.source))console.log(T)}console.log(`
|
|
924
|
-
done in ${Hm}ms`)}fi!==void 0&&(process.stderr.write(`${fi}: the summary names what the run created.
|
|
925
|
-
`),process.exit(1));let jc=eu(so,n.failOnPartial||o);jc!==0&&process.exit(jc)}function VO(r){return r instanceof Zc?{line:r.message,exitCode:1}:r instanceof Error&&r.message.startsWith("Invalid SF org alias:")?{line:r.message,exitCode:2}:{line:`FATAL: ${r instanceof Error?r.stack??r.message:String(r)}`,exitCode:1}}/sandforge-clone\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(Oh(),GO().catch(r=>{let e=VO(r);process.stderr.write(`${e.line}
|
|
926
|
-
`),process.exit(e.exitCode)}));export{ud as a,Fe as b,Jr as c,_d as d,jg as e,$g as f,vg as g,Eg as h,qd as i,Ws as j,Ud as k,Ig as l,Gd as m,nT as n,zd as o,xg as p,xy as q,Ny as r,lm as s,By as t,Ly as u,Wy as v,_y as w,qy as x,Uy as y,zy as z,Hy as A,tc as B,Ky as C,Jy as D,Qy as E,Yy as F,Xy as G,Zy as H,lb as I,hb as J,gb as K,wb as L,yb as M,Dg as N,_g as O,Rb as P,Sb as Q,Ab as R,Eb as S,Ib as T,xb as U,Pb as V,Kd as W,YA as X,Cb as Y,Nb as Z,Qd as _,hm as $,Bb as aa,qg as ba,Lb as ca,Wb as da,Ug as ea,Db as fa,qb as ga,zb as ha,Hb as ia,Kb as ja,Vb as ka,Jb as la,Qb as ma,Yb as na,Xb as oa,Zb as pa,eR as qa,tR as ra,nR as sa,sR as ta,iR as ua,lr as va,zg as wa,Hg as xa,Kg as ya,Xr as za,dR as Aa,cR as Ba,mm as Ca,uR as Da,lR as Ea,Vg as Fa,hR as Ga,rc as Ha,SR as Ia,Jg as Ja,TR as Ka,AR as La,jR as Ma,ER as Na,Qg as Oa,xR as Pa,km as Qa,PR as Ra,Yg as Sa,FR as Ta,CR as Ua,NR as Va,MR as Wa,ni as Xa,BR as Ya,un as Za,Zr as _a,WR as $a,DR as ab,GR as bb,oc as cb,HR as db,XA as eb,sc as fb,Zg as gb,VR as hb,mc as ib,JR as jb,QR as kb,YR as lb,jm as mb,XR as nb,tO as ob,wc as pb,ln as qb,Gs as rb,iO as sb,Xd as tb,cO as ub,uO as vb,zs as wb,ac as xb,Pm as yb,lO as zb,fO as Ab,pO as Bb,dc as Cb,ZA as Db,hO as Eb,gO as Fb,oi as Gb,si as Hb,ii as Ib,wO as Jb,Cm as Kb,Nm as Lb,Mm as Mb,Bm as Nb,bO as Ob,RO as Pb,Wm as Qb,cc as Rb,OO as Sb,SO as Tb,TO as Ub,AO as Vb,Qs as Wb,EO as Xb,FO as Yb,CO as Zb,MO as _b,om as $b,sm as ac,BO as bc,LO as cc,_O as dc,qO as ec,GO as fc,VO as gc};
|